diff --git a/.golangci.yml b/.golangci.yml index 5c52fc47..6f176e51 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -13,6 +13,8 @@ issues: - should have comment (\([^)]+\) )?or be unexported # For now we are missing a lot of comments. - at least one file in a package should have a package comment + # Package comments. + - "package-comments: should have a package comment" exclude-rules: - path: _test\.go @@ -106,4 +108,3 @@ linters: # - testpackage # linter that makes you use a separate _test package [fast: true, auto-fix: false] # - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers [fast: false, auto-fix: false] # - wrapcheck # Checks that errors returned from external packages are wrapped [fast: false, auto-fix: false] - diff --git a/Makefile b/Makefile index 98c095d7..5fa89b66 100644 --- a/Makefile +++ b/Makefile @@ -169,7 +169,7 @@ ${RESOURCE_FILE}: ./dist/info.rc ./dist/${SRC_ICO} .FORCE ## Dev dependencies .PHONY: install-devel-tools install-linter install-go-mod-outdated install-git-hooks -LINTVER:="v1.47.2" +LINTVER:="v1.50.0" LINTSRC:="https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh" install-dev-dependencies: install-devel-tools install-linter install-go-mod-outdated diff --git a/internal/api/api.go b/internal/api/api.go index 1d17a20a..190f6083 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -18,7 +18,7 @@ // Package api provides HTTP API of the Bridge. // // API endpoints: -// * /focus, see focusHandler +// - /focus, see focusHandler package api import ( diff --git a/internal/bridge/bug_report.go b/internal/bridge/bug_report.go index 3b96158d..e22d7463 100644 --- a/internal/bridge/bug_report.go +++ b/internal/bridge/bug_report.go @@ -23,7 +23,6 @@ import ( "context" "errors" "io" - "io/ioutil" "os" "path/filepath" "sort" @@ -33,7 +32,7 @@ import ( ) const ( - MaxAttachmentSize = 7 * 1024 * 1024 // 7 MB total limit + MaxAttachmentSize = 7 * 1024 * 1024 // MaxAttachmentSize 7 MB total limit MaxCompressedFilesCount = 6 ) @@ -106,7 +105,7 @@ func (b *Bridge) getMatchingLogs(filenameMatchFunc func(string) bool) (filenames return nil, err } - files, err := ioutil.ReadDir(logsPath) + files, err := os.ReadDir(logsPath) if err != nil { return nil, err } diff --git a/internal/clientconfig/applemail.go b/internal/clientconfig/applemail.go index 7f41ca36..8345767f 100644 --- a/internal/clientconfig/applemail.go +++ b/internal/clientconfig/applemail.go @@ -18,7 +18,6 @@ package clientconfig import ( - "io/ioutil" "os" "path/filepath" "strconv" @@ -89,7 +88,7 @@ func prepareMobileConfig( } func saveConfigTemporarily(mc *mobileconfig.Config) (fname string, err error) { - dir, err := ioutil.TempDir("", "protonmail-autoconfig") + dir, err := os.MkdirTemp("", "protonmail-autoconfig") if err != nil { return } diff --git a/internal/config/cache/cache_test.go b/internal/config/cache/cache_test.go index 98a07201..c8ce44b0 100644 --- a/internal/config/cache/cache_test.go +++ b/internal/config/cache/cache_test.go @@ -18,7 +18,6 @@ package cache import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -28,7 +27,7 @@ import ( ) func TestRemoveOldVersions(t *testing.T) { - dir, err := ioutil.TempDir("", "test-cache") + dir, err := os.MkdirTemp("", "test-cache") require.NoError(t, err) cache, err := New(dir, "c4") diff --git a/internal/config/settings/kvs.go b/internal/config/settings/kvs.go index 62168ea1..fedbf0a4 100644 --- a/internal/config/settings/kvs.go +++ b/internal/config/settings/kvs.go @@ -21,7 +21,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "os" "strconv" "sync" @@ -79,7 +78,7 @@ func (p *keyValueStore) save() error { return err } - return ioutil.WriteFile(p.path, b, 0o600) + return os.WriteFile(p.path, b, 0o600) } func (p *keyValueStore) setDefault(key Key, value string) { diff --git a/internal/config/settings/kvs_test.go b/internal/config/settings/kvs_test.go index 3acb6d6f..2fb75067 100644 --- a/internal/config/settings/kvs_test.go +++ b/internal/config/settings/kvs_test.go @@ -18,7 +18,6 @@ package settings import ( - "io/ioutil" "os" "testing" @@ -38,7 +37,7 @@ func TestLoadBadKeyValueStore(t *testing.T) { path, clean := newTmpFile(r) defer clean() - r.NoError(ioutil.WriteFile(path, []byte("{\"key\":\"MISSING_QUOTES"), 0o700)) + r.NoError(os.WriteFile(path, []byte("{\"key\":\"MISSING_QUOTES"), 0o700)) pref := newKeyValueStore(path) r.Equal("", pref.Get("key")) } @@ -115,7 +114,7 @@ func TestKeyValueStoreSetBool(t *testing.T) { } func newTmpFile(r *require.Assertions) (path string, clean func()) { - tmpfile, err := ioutil.TempFile("", "pref.*.json") + tmpfile, err := os.CreateTemp("", "pref.*.json") r.NoError(err) defer r.NoError(tmpfile.Close()) @@ -131,12 +130,12 @@ func newTestEmptyKeyValueStore(r *require.Assertions) (*keyValueStore, func()) { func newTestKeyValueStore(r *require.Assertions) (*keyValueStore, func()) { path, clean := newTmpFile(r) - r.NoError(ioutil.WriteFile(path, []byte("{\"str\":\"value\",\"int\":\"42\",\"bool\":\"true\",\"falseBool\":\"t\"}"), 0o700)) + r.NoError(os.WriteFile(path, []byte("{\"str\":\"value\",\"int\":\"42\",\"bool\":\"true\",\"falseBool\":\"t\"}"), 0o700)) return newKeyValueStore(path), clean } func checkSavedKeyValueStore(r *require.Assertions, path, expected string) { - data, err := ioutil.ReadFile(path) + data, err := os.ReadFile(path) r.NoError(err) r.Equal(expected, string(data)) } diff --git a/internal/config/tls/tls_test.go b/internal/config/tls/tls_test.go index 866c9682..83e84975 100644 --- a/internal/config/tls/tls_test.go +++ b/internal/config/tls/tls_test.go @@ -18,7 +18,7 @@ package tls import ( - "io/ioutil" + "os" "testing" "time" @@ -26,7 +26,7 @@ import ( ) func TestGetOldConfig(t *testing.T) { - dir, err := ioutil.TempDir("", "test-tls") + dir, err := os.MkdirTemp("", "test-tls") require.NoError(t, err) // Create new tls object. @@ -49,7 +49,7 @@ func TestGetOldConfig(t *testing.T) { } func TestGetValidConfig(t *testing.T) { - dir, err := ioutil.TempDir("", "test-tls") + dir, err := os.MkdirTemp("", "test-tls") require.NoError(t, err) // Create new tls object. diff --git a/internal/cookies/jar_test.go b/internal/cookies/jar_test.go index 09438369..35d1609e 100644 --- a/internal/cookies/jar_test.go +++ b/internal/cookies/jar_test.go @@ -18,9 +18,9 @@ package cookies import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "testing" "time" @@ -170,7 +170,7 @@ func getTestServer(t *testing.T, wantCookies []testCookie) *httptest.Server { // newFakeSettings creates a temporary folder for files. func newFakeSettings() *settings.Settings { - dir, err := ioutil.TempDir("", "test-settings") + dir, err := os.MkdirTemp("", "test-settings") if err != nil { panic(err) } diff --git a/internal/imap/backend.go b/internal/imap/backend.go index 1585f4a9..5f93a046 100644 --- a/internal/imap/backend.go +++ b/internal/imap/backend.go @@ -24,10 +24,11 @@ // When IMAP clients request message literals (or parts thereof), we sometimes need to build RFC822 message literals. // To do this, we pass build jobs to the message builder, which internally manages its own parallelism. // Summary: -// - each IMAP fetch request is handled in parallel, -// - within each IMAP fetch request, individual items are handled by a pool of `fetchWorkers` workers, -// - within each worker, build jobs are posted to the message builder, -// - the message builder handles build jobs using its own, independent worker pool, +// - each IMAP fetch request is handled in parallel, +// - within each IMAP fetch request, individual items are handled by a pool of `fetchWorkers` workers, +// - within each worker, build jobs are posted to the message builder, +// - the message builder handles build jobs using its own, independent worker pool, +// // The builder will handle jobs in parallel up to its own internal limit. This prevents it from overwhelming API. package imap diff --git a/internal/imap/backend_cache.go b/internal/imap/backend_cache.go index dd7a75f6..bdf16d08 100644 --- a/internal/imap/backend_cache.go +++ b/internal/imap/backend_cache.go @@ -31,15 +31,16 @@ const ( // addToCache adds item to existing item list. // Starting from following structure: -// { -// "username": {"label": "item1;item2"} -// } +// +// { +// "username": {"label": "item1;item2"} +// } // // After calling addToCache("username", "label", "newItem") we get: -// { -// "username": {"label": "item1;item2;newItem"} -// } // +// { +// "username": {"label": "item1;item2;newItem"} +// } func (ib *imapBackend) addToCache(userID, label, toAdd string) { list := ib.getCacheList(userID, label) diff --git a/internal/imap/mailbox_append.go b/internal/imap/mailbox_append.go index 1239016c..09fc0dc8 100644 --- a/internal/imap/mailbox_append.go +++ b/internal/imap/mailbox_append.go @@ -21,7 +21,7 @@ import ( "bufio" "bytes" "fmt" - "io/ioutil" + "io" "net/mail" "strings" "time" @@ -55,7 +55,7 @@ func (im *imapMailbox) createMessage(imapFlags []string, date time.Time, r imap. im.user.appendExpungeLock.Lock() defer im.user.appendExpungeLock.Unlock() - body, err := ioutil.ReadAll(r) + body, err := io.ReadAll(r) if err != nil { return err } diff --git a/internal/imap/mailbox_root.go b/internal/imap/mailbox_root.go index 8736781b..c840ebd9 100644 --- a/internal/imap/mailbox_root.go +++ b/internal/imap/mailbox_root.go @@ -30,11 +30,11 @@ import ( // The purpose of this mailbox is to see "Folders" and "Labels" // at the root of the mailbox tree, e.g.: // -// Folders << this -// Folders/Family +// Folders << this +// Folders/Family // -// Labels << this -// Labels/Security +// Labels << this +// Labels/Security // // This mailbox cannot be modified or read in any way. type imapRootMailbox struct { diff --git a/internal/imap/uidplus/extension.go b/internal/imap/uidplus/extension.go index ac22adae..9e2285fb 100644 --- a/internal/imap/uidplus/extension.go +++ b/internal/imap/uidplus/extension.go @@ -18,8 +18,8 @@ // Package uidplus DOES NOT implement full RFC4315! // // Excluded parts are: -// * Response `UIDNOTSTICKY`: All mailboxes of Bridge support stable -// UIDVALIDITY so it would never return this response +// - Response `UIDNOTSTICKY`: All mailboxes of Bridge support stable +// UIDVALIDITY so it would never return this response // // Otherwise the standard RFC4315 is followed. package uidplus @@ -48,9 +48,10 @@ const ( // ranges or out of the bound ranges are possible. // // NOTE: potential issue with response length -// * the user selects large number of messages to be copied and the -// response line will be long, -// * list of UIDs which high values +// - the user selects large number of messages to be copied and the +// response line will be long, +// - list of UIDs which high values +// // which can create long response line. We didn't find a maximum length of one // IMAP response line or maximum length of IMAP "response code" with parameters. type OrderedSeq []uint32 diff --git a/internal/locations/locations_test.go b/internal/locations/locations_test.go index 7c7c7a70..2b430fdc 100644 --- a/internal/locations/locations_test.go +++ b/internal/locations/locations_test.go @@ -18,7 +18,6 @@ package locations import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -118,10 +117,10 @@ func TestCleanRemovesUnexpectedFilesAndFolders(t *testing.T) { } func newFakeAppDirs(t *testing.T) *fakeAppDirs { - configDir, err := ioutil.TempDir("", "test-locations-config") + configDir, err := os.MkdirTemp("", "test-locations-config") require.NoError(t, err) - cacheDir, err := ioutil.TempDir("", "test-locations-cache") + cacheDir, err := os.MkdirTemp("", "test-locations-cache") require.NoError(t, err) return &fakeAppDirs{ diff --git a/internal/logging/clear.go b/internal/logging/clear.go index ee64ef1f..e5d6f60e 100644 --- a/internal/logging/clear.go +++ b/internal/logging/clear.go @@ -18,7 +18,6 @@ package logging import ( - "io/ioutil" "os" "path/filepath" "sort" @@ -27,7 +26,7 @@ import ( ) func clearLogs(logDir string, maxLogs int, maxCrashes int) error { - files, err := ioutil.ReadDir(logDir) + files, err := os.ReadDir(logDir) if err != nil { return err } diff --git a/internal/logging/logging_test.go b/internal/logging/logging_test.go index 291b6322..047d3551 100644 --- a/internal/logging/logging_test.go +++ b/internal/logging/logging_test.go @@ -18,7 +18,7 @@ package logging import ( - "io/ioutil" + "os" "path/filepath" "testing" @@ -27,14 +27,14 @@ import ( // TestClearLogs tests that cearLogs removes only bridge old log files keeping last three of them. func TestClearLogs(t *testing.T) { - dir, err := ioutil.TempDir("", "clear-logs-test") + dir, err := os.MkdirTemp("", "clear-logs-test") require.NoError(t, err) - require.NoError(t, ioutil.WriteFile(filepath.Join(dir, "other.log"), []byte("Hello"), 0o755)) - require.NoError(t, ioutil.WriteFile(filepath.Join(dir, "v1_10.log"), []byte("Hello"), 0o755)) - require.NoError(t, ioutil.WriteFile(filepath.Join(dir, "v1_11.log"), []byte("Hello"), 0o755)) - require.NoError(t, ioutil.WriteFile(filepath.Join(dir, "v2_12.log"), []byte("Hello"), 0o755)) - require.NoError(t, ioutil.WriteFile(filepath.Join(dir, "v2_13.log"), []byte("Hello"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "other.log"), []byte("Hello"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "v1_10.log"), []byte("Hello"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "v1_11.log"), []byte("Hello"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "v2_12.log"), []byte("Hello"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "v2_13.log"), []byte("Hello"), 0o755)) require.NoError(t, clearLogs(dir, 3, 0)) checkFileNames(t, dir, []string{ @@ -51,7 +51,7 @@ func checkFileNames(t *testing.T, dir string, expectedFileNames []string) { } func getFileNames(t *testing.T, dir string) []string { - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) require.NoError(t, err) fileNames := []string{} diff --git a/internal/logging/rotator_test.go b/internal/logging/rotator_test.go index e361b310..a4f2d723 100644 --- a/internal/logging/rotator_test.go +++ b/internal/logging/rotator_test.go @@ -20,7 +20,6 @@ package logging import ( "bytes" "io" - "io/ioutil" "os" "testing" @@ -77,7 +76,7 @@ func TestRotator(t *testing.T) { } func BenchmarkRotateRAMFile(b *testing.B) { - dir, err := ioutil.TempDir("", "rotate-benchmark") + dir, err := os.MkdirTemp("", "rotate-benchmark") require.NoError(b, err) defer os.RemoveAll(dir) //nolint:errcheck @@ -88,7 +87,7 @@ func BenchmarkRotateDiskFile(b *testing.B) { cache, err := os.UserCacheDir() require.NoError(b, err) - dir, err := ioutil.TempDir(cache, "rotate-benchmark") + dir, err := os.MkdirTemp(cache, "rotate-benchmark") require.NoError(b, err) defer os.RemoveAll(dir) //nolint:errcheck @@ -113,7 +112,7 @@ func getTestFile(b *testing.B, dir string, length int) func() (io.WriteCloser, e b.StopTimer() defer b.StartTimer() - f, err := ioutil.TempFile(dir, "log") + f, err := os.CreateTemp(dir, "log") if err != nil { return nil, err } diff --git a/internal/smtp/dump_qa.go b/internal/smtp/dump_qa.go index 27f3a670..6af16fe6 100644 --- a/internal/smtp/dump_qa.go +++ b/internal/smtp/dump_qa.go @@ -22,7 +22,6 @@ package smtp import ( "fmt" - "io/ioutil" "os" "path/filepath" "time" @@ -48,7 +47,7 @@ func dumpMessageData(b []byte, subject string) { subject = subject[:16] } - if err := ioutil.WriteFile( + if err := os.WriteFile( filepath.Join(path, fmt.Sprintf("%v-%v.eml", subject, time.Now().Unix())), b, 0o600, diff --git a/internal/smtp/preferences.go b/internal/smtp/preferences.go index 48622222..8a58a2d1 100644 --- a/internal/smtp/preferences.go +++ b/internal/smtp/preferences.go @@ -163,17 +163,18 @@ func (b *sendPreferencesBuilder) withPublicKey(v *crypto.KeyRing) { // preferences. Notice that the composer allows to select a sign preference, // an email format preference and an encrypt-to-outside preference. The // object we extract has the following possible value types: -// { -// encrypt: true | false, -// sign: true | false, -// pgpScheme: 1 (protonmail custom scheme) -// | 2 (Protonmail scheme for encrypted-to-outside email) -// | 4 (no cryptographic scheme) -// | 8 (PGP/INLINE) -// | 16 (PGP/MIME), -// mimeType: 'text/html' | 'text/plain' | 'multipart/mixed', -// publicKey: OpenPGPKey | undefined/null -// }. +// +// { +// encrypt: true | false, +// sign: true | false, +// pgpScheme: 1 (protonmail custom scheme) +// | 2 (Protonmail scheme for encrypted-to-outside email) +// | 4 (no cryptographic scheme) +// | 8 (PGP/INLINE) +// | 16 (PGP/MIME), +// mimeType: 'text/html' | 'text/plain' | 'multipart/mixed', +// publicKey: OpenPGPKey | undefined/null +// }. func (b *sendPreferencesBuilder) build() (p SendPreferences) { p.Encrypt = b.shouldEncrypt() p.Sign = b.shouldSign() @@ -207,13 +208,13 @@ func (b *sendPreferencesBuilder) build() (p SendPreferences) { // setPGPSettings returns a SendPreferences with the following possible values: // -// { -// encrypt: true | false | undefined/null/'', -// sign: true | false | undefined/null/'', -// pgpScheme: 'pgp-mime' | 'pgp-inline' | undefined/null/'', -// mimeType: 'text/html' | 'text/plain' | undefined/null/'', -// publicKey: OpenPGPKey | undefined/null -// } +// { +// encrypt: true | false | undefined/null/'', +// sign: true | false | undefined/null/'', +// pgpScheme: 'pgp-mime' | 'pgp-inline' | undefined/null/'', +// mimeType: 'text/html' | 'text/plain' | undefined/null/'', +// publicKey: OpenPGPKey | undefined/null +// } // // These settings are simply a reflection of the vCard content plus the public // key info retrieved from the API via the GET KEYS route. @@ -285,17 +286,17 @@ func (b *sendPreferencesBuilder) setInternalPGPSettings( // pickSendingKey tries to determine which key to use to encrypt outgoing mail. // It returns a keyring containing the chosen key or an error. // -// 1. If there are pinned keys in the vCard, those should be given preference -// (assuming the fingerprint matches one of the keys served by the API). -// 2. If there are pinned keys in the vCard but no matching keys were served -// by the API, we use one of the API keys but first show a modal to the -// user to ask them to confirm that they trust the API key. -// (Use case: user doesn't trust server, pins the only keys they trust to -// the contact, rogue server sends unknown keys, user should have option -// to say they don't recognise these keys and abort the mail send.) -// 3. If there are no pinned keys, then the client should encrypt with the -// first valid key served by the API (in principle the server already -// validates the keys and the first one provided should be valid). +// 1. If there are pinned keys in the vCard, those should be given preference +// (assuming the fingerprint matches one of the keys served by the API). +// 2. If there are pinned keys in the vCard but no matching keys were served +// by the API, we use one of the API keys but first show a modal to the +// user to ask them to confirm that they trust the API key. +// (Use case: user doesn't trust server, pins the only keys they trust to +// the contact, rogue server sends unknown keys, user should have option +// to say they don't recognise these keys and abort the mail send.) +// 3. If there are no pinned keys, then the client should encrypt with the +// first valid key served by the API (in principle the server already +// validates the keys and the first one provided should be valid). func pickSendingKey(vCardData *ContactMetadata, rawAPIKeys []pmapi.PublicKey) (kr *crypto.KeyRing, err error) { contactKeys := make([]*crypto.Key, len(vCardData.Keys)) apiKeys := make([]*crypto.Key, len(rawAPIKeys)) @@ -457,13 +458,13 @@ func (b *sendPreferencesBuilder) setExternalPGPSettingsWithoutWKDKeys( // determined thus far using using the (global) user mail settings. // The object we extract has the following possible value types: // -// { -// encrypt: true | false, -// sign: true | false, -// pgpScheme: 'pgp-mime' | 'pgp-inline', -// mimeType: 'text/html' | 'text/plain', -// publicKey: OpenPGPKey | undefined/null -// } +// { +// encrypt: true | false, +// sign: true | false, +// pgpScheme: 'pgp-mime' | 'pgp-inline', +// mimeType: 'text/html' | 'text/plain', +// publicKey: OpenPGPKey | undefined/null +// } // // The public key can still be undefined as we do not need it if the outgoing // email is not encrypted. diff --git a/internal/store/cache/disk.go b/internal/store/cache/disk.go index 6a611b38..82cfcb50 100644 --- a/internal/store/cache/disk.go +++ b/internal/store/cache/disk.go @@ -23,7 +23,6 @@ import ( "crypto/rand" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "sync" @@ -64,7 +63,7 @@ func NewOnDiskCache(path string, cmp Compressor, opts Options) (Cache, error) { return nil, err } - file, err := ioutil.TempFile(path, "tmp") + file, err := os.CreateTemp(path, "tmp") defer func() { file.Close() //nolint:errcheck,gosec os.Remove(file.Name()) //nolint:errcheck,gosec @@ -210,7 +209,7 @@ func (c *onDiskCache) readFile(path string) ([]byte, error) { // Wait before reading in case the file is currently being written. c.pending.wait(path) - return ioutil.ReadFile(filepath.Clean(path)) + return os.ReadFile(filepath.Clean(path)) } func (c *onDiskCache) writeFile(path string, b []byte) error { @@ -235,7 +234,7 @@ func (c *onDiskCache) writeFile(path string, b []byte) error { defer c.update() // NOTE(GODT-1158): What happens when this fails? Should be fixed eventually. - return ioutil.WriteFile(filepath.Clean(path), b, 0o600) + return os.WriteFile(filepath.Clean(path), b, 0o600) } func (c *onDiskCache) hasSpace(size int) bool { diff --git a/internal/store/store_test.go b/internal/store/store_test.go index b396fb94..5f4446bb 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -20,7 +20,6 @@ package store import ( "context" "fmt" - "io/ioutil" "os" "path/filepath" "runtime" @@ -162,7 +161,7 @@ func initMocks(tb testing.TB) (*mocksForStore, func()) { mocks.panicHandler.EXPECT().HandlePanic().AnyTimes() var err error - mocks.tmpDir, err = ioutil.TempDir("", "store-test") + mocks.tmpDir, err = os.MkdirTemp("", "store-test") require.NoError(tb, err) cacheFile := filepath.Join(mocks.tmpDir, "cache.json") diff --git a/internal/store/user_message.go b/internal/store/user_message.go index 8ce9cec2..f7f0fc98 100644 --- a/internal/store/user_message.go +++ b/internal/store/user_message.go @@ -21,7 +21,6 @@ import ( "bytes" "encoding/json" "io" - "io/ioutil" "net/mail" "net/textproto" "strings" @@ -126,7 +125,7 @@ func encryptDraft(kr *crypto.KeyRing, message *pmapi.Message, attachments []*dra for _, att := range attachments { attachment := att.attachment - attachmentBody, err := ioutil.ReadAll(att.reader) + attachmentBody, err := io.ReadAll(att.reader) if err != nil { return errors.Wrap(err, "failed to read attachment") } @@ -158,7 +157,7 @@ func (store *Store) checkDraftTotalSize(message *pmapi.Message, attachments []*d var attSize int64 for _, att := range attachments { - b, err := ioutil.ReadAll(att.encReader) + b, err := io.ReadAll(att.encReader) if err != nil { return false, err } diff --git a/internal/store/user_sync.go b/internal/store/user_sync.go index 845b2f8b..54cb65dd 100644 --- a/internal/store/user_sync.go +++ b/internal/store/user_sync.go @@ -111,13 +111,13 @@ func (store *Store) isSynced(countsOnAPI []*pmapi.MessagesCount) (bool, error) { // All Mail mailbox contains all messages, so we download all meta data needed // to generate any address/mailbox IMAP UIDs. // Sync state can be in three states: -// * Nothing in database. For example when user logs in for the first time. -// `triggerSync` will start full sync. -// * Database has syncIDRangesKey and syncIDsToBeDeletedKey keys with data. -// Sync is in progress or was interrupted. In later case when, `triggerSync` -// will continue where it left off. -// * Database has only syncStateKey with time when database was last synced. -// `triggerSync` will reset it and start full sync again. +// - Nothing in database. For example when user logs in for the first time. +// `triggerSync` will start full sync. +// - Database has syncIDRangesKey and syncIDsToBeDeletedKey keys with data. +// Sync is in progress or was interrupted. In later case when, `triggerSync` +// will continue where it left off. +// - Database has only syncStateKey with time when database was last synced. +// `triggerSync` will reset it and start full sync again. func (store *Store) triggerSync() { syncState := store.loadSyncState() diff --git a/internal/updater/install_darwin.go b/internal/updater/install_darwin.go index 2ae74c8a..56a30453 100644 --- a/internal/updater/install_darwin.go +++ b/internal/updater/install_darwin.go @@ -20,7 +20,6 @@ package updater import ( "compress/gzip" "io" - "io/ioutil" "os" "path/filepath" @@ -43,7 +42,7 @@ func (i *InstallerDarwin) InstallUpdate(_ *semver.Version, r io.Reader) error { } defer func() { _ = gr.Close() }() - tempDir, err := ioutil.TempDir("", "proton-update-source") + tempDir, err := os.MkdirTemp("", "proton-update-source") if err != nil { return errors.Wrap(err, "failed to get temporary update directory") } diff --git a/internal/updater/sync_test.go b/internal/updater/sync_test.go index c7d816b6..3b9b74fa 100644 --- a/internal/updater/sync_test.go +++ b/internal/updater/sync_test.go @@ -18,7 +18,6 @@ package updater import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -104,10 +103,10 @@ func checkThatFilesAreSame(r *require.Assertions, src, dst string) { r.Equal(srcLnk, dstLnk) } else { - srcContent, err := ioutil.ReadFile(srcPath) + srcContent, err := os.ReadFile(srcPath) r.NoError(err) - dstContent, err := ioutil.ReadFile(dstPath) + dstContent, err := os.ReadFile(dstPath) r.NoError(err) r.Equal(srcContent, dstContent) @@ -155,7 +154,7 @@ func createTestFolder(dirPath, dirType string) error { path := filepath.Join(dirPath, "testpath") switch dirType { case FileType: - err = ioutil.WriteFile(path, []byte("This is a test"), 0o640) + err = os.WriteFile(path, []byte("This is a test"), 0o640) if err != nil { return err } @@ -172,7 +171,7 @@ func createTestFolder(dirPath, dirType string) error { return err } - err = ioutil.WriteFile(filepath.Join(path, "another_file"), []byte("This is a test"), 0o640) + err = os.WriteFile(filepath.Join(path, "another_file"), []byte("This is a test"), 0o640) if err != nil { return err } diff --git a/internal/updater/updater_test.go b/internal/updater/updater_test.go index 6b61c3de..bbcca1c5 100644 --- a/internal/updater/updater_test.go +++ b/internal/updater/updater_test.go @@ -21,7 +21,7 @@ import ( "encoding/json" "errors" "io" - "io/ioutil" + "os" "sync" "testing" "time" @@ -314,7 +314,7 @@ type fakeSettings struct { // newFakeSettings creates a temporary folder for files. func newFakeSettings(rollout float64, earlyAccess bool) *fakeSettings { - dir, err := ioutil.TempDir("", "test-settings") + dir, err := os.MkdirTemp("", "test-settings") if err != nil { panic(err) } diff --git a/internal/updater/version.go b/internal/updater/version.go index d057fca1..0cdfb906 100644 --- a/internal/updater/version.go +++ b/internal/updater/version.go @@ -50,41 +50,42 @@ type VersionInfo struct { // VersionMap represents the structure of the version.json file. // It looks like this: -// { -// "stable": { -// "Version": "2.3.4", -// "Package": "https://protonmail.com/.../bridge_2.3.4_linux.tgz", -// "Installers": [ -// "https://protonmail.com/.../something.deb", -// "https://protonmail.com/.../something.rpm", -// "https://protonmail.com/.../PKGBUILD" -// ], -// "LandingPage": "https://protonmail.com/bridge", -// "ReleaseNotesPage": "https://protonmail.com/.../release_notes.html", -// "RolloutProportion": 0.5 -// }, -// "early": { -// "Version": "2.4.0", -// "Package": "https://protonmail.com/.../bridge_2.4.0_linux.tgz", -// "Installers": [ -// "https://protonmail.com/.../something.deb", -// "https://protonmail.com/.../something.rpm", -// "https://protonmail.com/.../PKGBUILD" -// ], -// "LandingPage": "https://protonmail.com/bridge", -// "ReleaseNotesPage": "https://protonmail.com/.../release_notes.html", -// "RolloutProportion": 0.5 -// }, -// "...": { -// ... -// } -// }. +// +// { +// "stable": { +// "Version": "2.3.4", +// "Package": "https://protonmail.com/.../bridge_2.3.4_linux.tgz", +// "Installers": [ +// "https://protonmail.com/.../something.deb", +// "https://protonmail.com/.../something.rpm", +// "https://protonmail.com/.../PKGBUILD" +// ], +// "LandingPage": "https://protonmail.com/bridge", +// "ReleaseNotesPage": "https://protonmail.com/.../release_notes.html", +// "RolloutProportion": 0.5 +// }, +// "early": { +// "Version": "2.4.0", +// "Package": "https://protonmail.com/.../bridge_2.4.0_linux.tgz", +// "Installers": [ +// "https://protonmail.com/.../something.deb", +// "https://protonmail.com/.../something.rpm", +// "https://protonmail.com/.../PKGBUILD" +// ], +// "LandingPage": "https://protonmail.com/bridge", +// "ReleaseNotesPage": "https://protonmail.com/.../release_notes.html", +// "RolloutProportion": 0.5 +// }, +// "...": { +// ... +// } +// }. type VersionMap map[string]VersionInfo // getVersionFileURL returns the URL of the version file. // For example: -// - https://protonmail.com/download/bridge/version_linux.json -// - https://protonmail.com/download/ie/version_linux.json +// - https://protonmail.com/download/bridge/version_linux.json +// - https://protonmail.com/download/ie/version_linux.json func (u *Updater) getVersionFileURL() string { return fmt.Sprintf("%v/%v/version_%v.json", Host, u.updateURLName, u.platform) } diff --git a/internal/users/cache.go b/internal/users/cache.go index e9292b12..e7b63818 100644 --- a/internal/users/cache.go +++ b/internal/users/cache.go @@ -20,7 +20,6 @@ package users import ( "errors" "io" - "io/ioutil" "os" "path/filepath" @@ -30,7 +29,7 @@ import ( // isFolderEmpty checks whether a folder is empty. // path must point to an existing folder. func isFolderEmpty(path string) (bool, error) { - files, err := ioutil.ReadDir(path) + files, err := os.ReadDir(path) if err != nil { return true, err } @@ -90,13 +89,13 @@ func copyFolder(srcPath, dstPath string) error { if err = os.MkdirAll(dstPath, 0o700); err != nil { return err } - files, err := ioutil.ReadDir(srcPath) + files, err := os.ReadDir(srcPath) if err != nil { return err } // copy only regular files and folders for _, fileInfo := range files { - mode := fileInfo.Mode() + mode := fileInfo.Type() if mode&os.ModeSymlink != 0 { continue // we skip symbolic links to avoid potential endless recursion } @@ -227,7 +226,7 @@ func (u *Users) MigrateCache(srcPath, dstPath string) error { // GODT-1381 Edge case: read-only source migration: prevent re-naming // (read-only is conserved). Do copy instead. - tmp, err := ioutil.TempFile(srcPath, "tmp") + tmp, err := os.CreateTemp(srcPath, "tmp") if err == nil { // Removal of tmp file cannot be deferred, as we are going to try to move the containing folder. if err = tmp.Close(); err == nil { diff --git a/internal/users/cache_test.go b/internal/users/cache_test.go index fb4777eb..29475c2f 100644 --- a/internal/users/cache_test.go +++ b/internal/users/cache_test.go @@ -21,7 +21,6 @@ import ( "crypto/sha1" "encoding/hex" "io" - "io/ioutil" "os" "path/filepath" "testing" @@ -37,7 +36,7 @@ const ( // tempFileWithContent() creates a temporary file in folderPath containing the string content. // Returns the path of the created file. func tempFileWithContent(folderPath, content string) (string, error) { - file, err := ioutil.TempFile(folderPath, "") + file, err := os.CreateTemp(folderPath, "") if err != nil { return "", err } @@ -49,7 +48,7 @@ func tempFileWithContent(folderPath, content string) (string, error) { // itemCountInFolder() counts the number of items (files, folders, etc) in a folder. // Returns -1 if an error occurred. func itemCountInFolder(path string) int { - files, err := ioutil.ReadDir(path) + files, err := os.ReadDir(path) if err != nil { return -1 } @@ -83,13 +82,13 @@ func filesAreIdentical(path1, path2 string) bool { func TestCache_IsFolderEmpty(t *testing.T) { _, err := isFolderEmpty("") r.Error(t, err) - tempDirPath, err := ioutil.TempDir("", "") + tempDirPath, err := os.MkdirTemp("", "") defer func() { r.NoError(t, os.Remove(tempDirPath)) }() r.NoError(t, err) result, err := isFolderEmpty(tempDirPath) r.NoError(t, err) r.True(t, result) - tempFile, err := ioutil.TempFile(tempDirPath, "") + tempFile, err := os.CreateTemp(tempDirPath, "") r.NoError(t, err) defer func() { r.NoError(t, os.Remove(tempFile.Name())) }() r.NoError(t, tempFile.Close()) @@ -101,10 +100,10 @@ func TestCache_IsFolderEmpty(t *testing.T) { } func TestCache_CheckFolderIsSuitableDestinationForCache(t *testing.T) { - tempDirPath, err := ioutil.TempDir("", "") + tempDirPath, err := os.MkdirTemp("", "") defer func() { _ = os.Remove(tempDirPath) }() // cleanup in case we fail before removing it. r.NoError(t, err) - tempFile, err := ioutil.TempFile(tempDirPath, "") + tempFile, err := os.CreateTemp(tempDirPath, "") r.NoError(t, err) defer func() { _ = os.Remove(tempFile.Name()) }() // cleanup in case we fail before removing it. r.NoError(t, tempFile.Close()) @@ -122,10 +121,10 @@ func TestCache_CopyFolder(t *testing.T) { // |-srcSubDir/ // |-file2 - srcDir, err := ioutil.TempDir("", "") + srcDir, err := os.MkdirTemp("", "") defer func() { r.NoError(t, os.RemoveAll(srcDir)) }() r.NoError(t, err) - srcSubDir, err := ioutil.TempDir(srcDir, "") + srcSubDir, err := os.MkdirTemp(srcDir, "") r.NoError(t, err) subDirName := filepath.Base(srcSubDir) file1, err := tempFileWithContent(srcDir, str1) @@ -162,7 +161,7 @@ func TestCache_CopyFolder(t *testing.T) { } func TestCache_IsSubfolderOf(t *testing.T) { - dir, err := ioutil.TempDir("", "") + dir, err := os.MkdirTemp("", "") defer func() { r.NoError(t, os.Remove(dir)) }() r.NoError(t, err) r.True(t, isSubfolderOf(dir, dir)) diff --git a/internal/users/users_test.go b/internal/users/users_test.go index b8a4fa11..ed3dfd2b 100644 --- a/internal/users/users_test.go +++ b/internal/users/users_test.go @@ -19,7 +19,6 @@ package users import ( "fmt" - "io/ioutil" "os" "runtime" "runtime/debug" @@ -166,7 +165,7 @@ func initMocks(t *testing.T) mocks { mockCtrl = gomock.NewController(t) } - cacheFile, err := ioutil.TempFile("", "bridge-store-cache-*.db") + cacheFile, err := os.CreateTemp("", "bridge-store-cache-*.db") r.NoError(t, err, "could not get temporary file for store cache") r.NoError(t, cacheFile.Close()) @@ -193,7 +192,7 @@ func initMocks(t *testing.T) mocks { m.storeMaker.EXPECT().New(gomock.Any()).DoAndReturn(func(user store.BridgeUser) (*store.Store, error) { var sentryReporter *sentry.Reporter // Sentry reporter is not used under unit tests. - dbFile, err := ioutil.TempFile(t.TempDir(), "bridge-store-db-*.db") + dbFile, err := os.CreateTemp(t.TempDir(), "bridge-store-db-*.db") r.NoError(t, err, "could not get temporary file for store db") r.NoError(t, dbFile.Close()) diff --git a/internal/versioner/version.go b/internal/versioner/version.go index adfe3836..a55aec35 100644 --- a/internal/versioner/version.go +++ b/internal/versioner/version.go @@ -21,7 +21,6 @@ import ( "bytes" "encoding/base64" "fmt" - "io/ioutil" "os" "path/filepath" @@ -65,12 +64,12 @@ func (v *Version) SemVer() *semver.Version { // VerifyFiles verifies all files in the version directory. func (v *Version) VerifyFiles(kr *crypto.KeyRing) error { - fileBytes, err := ioutil.ReadFile(filepath.Join(v.path, sumFile)) //nolint:gosec + fileBytes, err := os.ReadFile(filepath.Join(v.path, sumFile)) //nolint:gosec if err != nil { return err } - sigBytes, err := ioutil.ReadFile(filepath.Join(v.path, sumFile+".sig")) //nolint:gosec + sigBytes, err := os.ReadFile(filepath.Join(v.path, sumFile+".sig")) //nolint:gosec if err != nil { return err } diff --git a/internal/versioner/version_test.go b/internal/versioner/version_test.go index 47af5112..881dab0f 100644 --- a/internal/versioner/version_test.go +++ b/internal/versioner/version_test.go @@ -19,7 +19,6 @@ package versioner import ( "crypto/rand" - "io/ioutil" "os" "path/filepath" "testing" @@ -33,7 +32,7 @@ import ( ) func TestVerifyFiles(t *testing.T) { - tempDir, err := ioutil.TempDir("", "verify-test") + tempDir, err := os.MkdirTemp("", "verify-test") require.NoError(t, err) version := &Version{ @@ -53,7 +52,7 @@ func TestVerifyFiles(t *testing.T) { } func TestVerifyWithBadFile(t *testing.T) { - tempDir, err := ioutil.TempDir("", "verify-test") + tempDir, err := os.MkdirTemp("", "verify-test") require.NoError(t, err) version := &Version{ @@ -76,7 +75,7 @@ func TestVerifyWithBadFile(t *testing.T) { } func TestVerifyWithBadSubFile(t *testing.T) { - tempDir, err := ioutil.TempDir("", "verify-test") + tempDir, err := os.MkdirTemp("", "verify-test") require.NoError(t, err) version := &Version{ @@ -136,10 +135,10 @@ func makeFile(t *testing.T, path string) { } func signFile(t *testing.T, path string, kr *crypto.KeyRing) { - file, err := ioutil.ReadFile(path) + file, err := os.ReadFile(path) require.NoError(t, err) sig, err := kr.SignDetached(crypto.NewPlainMessage(file)) require.NoError(t, err) - require.NoError(t, ioutil.WriteFile(path+".sig", sig.GetBinary(), 0o700)) + require.NoError(t, os.WriteFile(path+".sig", sig.GetBinary(), 0o700)) } diff --git a/internal/versioner/versioner.go b/internal/versioner/versioner.go index 568d23da..be815c51 100644 --- a/internal/versioner/versioner.go +++ b/internal/versioner/versioner.go @@ -19,7 +19,7 @@ package versioner import ( "errors" - "io/ioutil" + "os" "path/filepath" "sort" @@ -43,7 +43,7 @@ func New(root string) *Versioner { // ListVersions returns a collection of all available version numbers, sorted from newest to oldest. func (v *Versioner) ListVersions() (Versions, error) { - dirs, err := ioutil.ReadDir(v.root) + dirs, err := os.ReadDir(v.root) if err != nil { return nil, err } diff --git a/internal/versioner/versioner_remove_test.go b/internal/versioner/versioner_remove_test.go index 0c3a47f0..dcc22f1c 100644 --- a/internal/versioner/versioner_remove_test.go +++ b/internal/versioner/versioner_remove_test.go @@ -21,7 +21,7 @@ package versioner import ( - "io/ioutil" + "os" "path/filepath" "testing" @@ -33,7 +33,7 @@ import ( // RemoveOldVersions is a noop on darwin; we don't test it there. func TestRemoveOldVersions(t *testing.T) { - updates, err := ioutil.TempDir(t.TempDir(), "updates") + updates, err := os.MkdirTemp(t.TempDir(), "updates") require.NoError(t, err) v := newTestVersioner(t, "myCoolApp", updates, "2.3.4-beta", "2.3.4", "2.3.5", "2.4.0") diff --git a/internal/versioner/versioner_test.go b/internal/versioner/versioner_test.go index f8ec703f..dafe1acf 100644 --- a/internal/versioner/versioner_test.go +++ b/internal/versioner/versioner_test.go @@ -18,7 +18,6 @@ package versioner import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -29,7 +28,7 @@ import ( ) func TestListVersions(t *testing.T) { - updates, err := ioutil.TempDir("", "updates") + updates, err := os.MkdirTemp("", "updates") require.NoError(t, err) v := newTestVersioner(t, "myCoolApp", updates, "2.3.4-beta", "2.3.4", "2.3.5", "2.4.0") diff --git a/pkg/files/removal_test.go b/pkg/files/removal_test.go index 038d6939..4f3cdcd5 100644 --- a/pkg/files/removal_test.go +++ b/pkg/files/removal_test.go @@ -18,7 +18,6 @@ package files import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -93,7 +92,7 @@ func TestRemoveWithExceptions(t *testing.T) { } func newTestDir(t *testing.T, subdirs ...string) string { - dir, err := ioutil.TempDir("", "test-files-dir") + dir, err := os.MkdirTemp("", "test-files-dir") require.NoError(t, err) for _, target := range subdirs { diff --git a/pkg/message/build.go b/pkg/message/build.go index 8b0e71b8..75e6e8cd 100644 --- a/pkg/message/build.go +++ b/pkg/message/build.go @@ -20,7 +20,6 @@ package message import ( "context" "io" - "io/ioutil" "sync" "github.com/ProtonMail/gopenpgp/v2/crypto" @@ -52,8 +51,8 @@ type Fetcher interface { } // NewBuilder creates a new builder which manages the given number of fetch/attach/build workers. -// - fetchWorkers: the number of workers which fetch messages from API -// - attachWorkers: the number of workers which fetch attachments from API. +// - fetchWorkers: the number of workers which fetch messages from API +// - attachWorkers: the number of workers which fetch attachments from API. // // The returned builder is ready to handle jobs -- see (*Builder).NewJob for more information. // @@ -167,7 +166,7 @@ func newAttacherWorkFunc() pool.WorkFunc { return nil, err } - b, err := ioutil.ReadAll(rc) + b, err := io.ReadAll(rc) if err != nil { return nil, err } @@ -209,7 +208,7 @@ func newFetcherWorkFunc(attachmentPool *pool.Pool) pool.WorkFunc { return nil, err } - b, err := ioutil.ReadAll(rc) + b, err := io.ReadAll(rc) if err != nil { _ = rc.Close() return nil, err diff --git a/pkg/message/build_encrypted.go b/pkg/message/build_encrypted.go index 7e7273d8..7d3c8fa4 100644 --- a/pkg/message/build_encrypted.go +++ b/pkg/message/build_encrypted.go @@ -21,7 +21,6 @@ import ( "bytes" "encoding/base64" "io" - "io/ioutil" "mime" "mime/multipart" "net/http" @@ -83,7 +82,7 @@ func BuildEncrypted(m *pmapi.Message, readers []io.Reader, kr *crypto.KeyRing) ( return nil, err } - data, err := ioutil.ReadAll(r) + data, err := io.ReadAll(r) if err != nil { return nil, err } diff --git a/pkg/message/encrypt.go b/pkg/message/encrypt.go index 77464cb3..b3c5927d 100644 --- a/pkg/message/encrypt.go +++ b/pkg/message/encrypt.go @@ -21,7 +21,6 @@ import ( "bytes" "encoding/base64" "io" - "io/ioutil" "mime" "mime/quotedprintable" "strings" @@ -33,7 +32,7 @@ import ( ) func EncryptRFC822(kr *crypto.KeyRing, r io.Reader) ([]byte, error) { - b, err := ioutil.ReadAll(r) + b, err := io.ReadAll(r) if err != nil { return nil, err } @@ -118,7 +117,7 @@ func writeEncryptedPart(kr *crypto.KeyRing, header *textproto.Header, r io.Reade } func writeEncryptedTextPart(w io.Writer, r io.Reader, kr *crypto.KeyRing) error { - dec, err := ioutil.ReadAll(r) + dec, err := io.ReadAll(r) if err != nil { return err } @@ -146,7 +145,7 @@ func writeEncryptedTextPart(w io.Writer, r io.Reader, kr *crypto.KeyRing) error } func writeEncryptedAttachmentPart(w io.Writer, r io.Reader, kr *crypto.KeyRing) error { - dec, err := ioutil.ReadAll(r) + dec, err := io.ReadAll(r) if err != nil { return err } diff --git a/pkg/message/encrypt_test.go b/pkg/message/encrypt_test.go index 2f0bd4aa..11a0fcaf 100644 --- a/pkg/message/encrypt_test.go +++ b/pkg/message/encrypt_test.go @@ -19,7 +19,7 @@ package message import ( "bytes" - "io/ioutil" + "os" "testing" "github.com/ProtonMail/gopenpgp/v2/crypto" @@ -27,7 +27,7 @@ import ( ) func TestEncryptRFC822(t *testing.T) { - literal, err := ioutil.ReadFile("testdata/text_plain_latin1.eml") + literal, err := os.ReadFile("testdata/text_plain_latin1.eml") require.NoError(t, err) key, err := crypto.GenerateKey("name", "email", "rsa", 2048) @@ -46,7 +46,7 @@ func TestEncryptRFC822(t *testing.T) { } func TestEncryptRFC822Multipart(t *testing.T) { - literal, err := ioutil.ReadFile("testdata/multipart_alternative_nested.eml") + literal, err := os.ReadFile("testdata/multipart_alternative_nested.eml") require.NoError(t, err) key, err := crypto.GenerateKey("name", "email", "rsa", 2048) diff --git a/pkg/message/header.go b/pkg/message/header.go index f333338c..eccfd0ef 100644 --- a/pkg/message/header.go +++ b/pkg/message/header.go @@ -21,7 +21,6 @@ import ( "bufio" "bytes" "io" - "io/ioutil" "unicode" "github.com/emersion/go-message/textproto" @@ -141,7 +140,7 @@ func splitHeaderBody(b []byte) ([]byte, []byte, error) { } } - body, err := ioutil.ReadAll(br) + body, err := io.ReadAll(br) if err != nil && !errors.Is(err, io.EOF) { return nil, nil, err } diff --git a/pkg/message/parser.go b/pkg/message/parser.go index 653246ec..ad552aee 100644 --- a/pkg/message/parser.go +++ b/pkg/message/parser.go @@ -215,8 +215,8 @@ func collectAttachments(p *parser.Parser) ([]*pmapi.Attachment, []io.Reader, err } // buildBodies collects all text/html and text/plain parts and returns two bodies, -// - a rich text body (in which html is allowed), and -// - a plaintext body (in which html is converted to plaintext). +// - a rich text body (in which html is allowed), and +// - a plaintext body (in which html is converted to plaintext). // // text/html parts are converted to plaintext in order to build the plaintext body, // unless there is already a plaintext part provided via multipart/alternative, diff --git a/pkg/message/parser/parser.go b/pkg/message/parser/parser.go index 4aec2dcc..0fbd5c35 100644 --- a/pkg/message/parser/parser.go +++ b/pkg/message/parser/parser.go @@ -19,7 +19,6 @@ package parser import ( "io" - "io/ioutil" "github.com/emersion/go-message" "github.com/sirupsen/logrus" @@ -129,7 +128,7 @@ func (p *Parser) parseEntity(e *message.Entity) error { } func (p *Parser) parsePart(e *message.Entity) (err error) { - bytes, err := ioutil.ReadAll(e.Body) + bytes, err := io.ReadAll(e.Body) if err != nil { return } diff --git a/pkg/message/parser/parser_test.go b/pkg/message/parser/parser_test.go index d6e3c1db..b39f4190 100644 --- a/pkg/message/parser/parser_test.go +++ b/pkg/message/parser/parser_test.go @@ -19,7 +19,6 @@ package parser import ( "io" - "io/ioutil" "os" "path/filepath" "testing" @@ -44,7 +43,7 @@ func getFileReader(filename string) io.ReadCloser { } func getFileAsString(filename string) string { - b, err := ioutil.ReadAll(getFileReader(filename)) + b, err := io.ReadAll(getFileReader(filename)) if err != nil { panic(err) } diff --git a/pkg/message/parser_test.go b/pkg/message/parser_test.go index 5ac01b60..714e2c6c 100644 --- a/pkg/message/parser_test.go +++ b/pkg/message/parser_test.go @@ -20,7 +20,6 @@ package message import ( "image/png" "io" - "io/ioutil" "os" "path/filepath" "testing" @@ -603,7 +602,7 @@ func getFileReader(filename string) io.Reader { } func readerToString(r io.Reader) string { - b, err := ioutil.ReadAll(r) + b, err := io.ReadAll(r) if err != nil { panic(err) } diff --git a/pkg/message/section.go b/pkg/message/section.go index a2b38ce1..7be0acc7 100644 --- a/pkg/message/section.go +++ b/pkg/message/section.go @@ -21,7 +21,6 @@ import ( "bufio" "bytes" "io" - "io/ioutil" "net/textproto" "strconv" "strings" @@ -166,7 +165,7 @@ func (bs *BodyStructure) parseAllChildSections(r io.Reader, currentPath []int, s } } else { // Count length. - _, _ = bodyReader.WriteTo(ioutil.Discard) + _, _ = bodyReader.WriteTo(io.Discard) } // Clear all buffers. diff --git a/pkg/message/section_test.go b/pkg/message/section_test.go index 6b6568e8..9e15ad70 100644 --- a/pkg/message/section_test.go +++ b/pkg/message/section_test.go @@ -20,7 +20,7 @@ package message import ( "bytes" "fmt" - "io/ioutil" + "os" "path/filepath" "runtime" "sort" @@ -93,7 +93,7 @@ func TestParseBodyStructurePGP(t *testing.T) { "2": "application/pgp-signature; name=\"OpenPGP_signature.asc\"", } - b, err := ioutil.ReadFile("testdata/enc-body-structure.eml") + b, err := os.ReadFile("testdata/enc-body-structure.eml") require.NoError(t, err) bs, err := NewBodyStructure(bytes.NewReader(b)) diff --git a/pkg/pmapi/attachments_test.go b/pkg/pmapi/attachments_test.go index 9c14a121..2c5bbdc5 100644 --- a/pkg/pmapi/attachments_test.go +++ b/pkg/pmapi/attachments_test.go @@ -24,7 +24,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "mime/multipart" "net/http" "net/textproto" @@ -114,7 +113,7 @@ func TestClient_CreateAttachment(t *testing.T) { r.NoError(err) defer r.NoError(dataFile.Close()) - b, err := ioutil.ReadAll(dataFile) + b, err := io.ReadAll(dataFile) r.NoError(err) r.Equal(testAttachmentCleartext, string(b)) @@ -146,7 +145,7 @@ func TestClient_GetAttachment(t *testing.T) { defer att.Close() //nolint:errcheck // In reality, r contains encrypted data - b, err := ioutil.ReadAll(att) + b, err := io.ReadAll(att) r.NoError(err) r.Equal(testAttachmentCleartext, string(b)) @@ -181,7 +180,7 @@ func TestAttachmentEncrypt(t *testing.T) { func decryptAndCheck(r *require.Assertions, data io.Reader) { // First separate KeyPacket from encrypted data. In our case keypacket // has 271 bytes. - raw, err := ioutil.ReadAll(data) + raw, err := io.ReadAll(data) r.NoError(err) rawKeyPacket := raw[:271] rawDataPacket := raw[271:] @@ -195,7 +194,7 @@ func decryptAndCheck(r *require.Assertions, data io.Reader) { decryptedReader, err := haveAttachment.Decrypt(bytes.NewBuffer(rawDataPacket), testPrivateKeyRing) r.NoError(err) - b, err := ioutil.ReadAll(decryptedReader) + b, err := io.ReadAll(decryptedReader) r.NoError(err) r.Equal(testAttachmentCleartext, string(b)) diff --git a/pkg/pmapi/dialer_pinning_report.go b/pkg/pmapi/dialer_pinning_report.go index 36c6b8bf..8d9c5143 100644 --- a/pkg/pmapi/dialer_pinning_report.go +++ b/pkg/pmapi/dialer_pinning_report.go @@ -20,7 +20,7 @@ package pmapi import ( "bytes" "encoding/json" - "io/ioutil" + "io" "net/http" "strconv" "time" @@ -139,6 +139,6 @@ func (r tlsReport) sendReport(cfg Config, uri string) { logrus.WithField("status", http.StatusOK).Error("StatusCode was not OK") } - _, _ = ioutil.ReadAll(res.Body) + _, _ = io.ReadAll(res.Body) _ = res.Body.Close() } diff --git a/pkg/pmapi/events.go b/pkg/pmapi/events.go index 89c5b644..08f356d8 100644 --- a/pkg/pmapi/events.go +++ b/pkg/pmapi/events.go @@ -54,10 +54,10 @@ type Event struct { type EventAction int const ( - EventDelete EventAction = iota // Item has been deleted. - EventCreate // Item has been created. - EventUpdate // Item has been updated. - EventUpdateFlags // For messages: flags have been updated. + EventDelete EventAction = iota // EventDelete Item has been deleted. + EventCreate // EventCreate Item has been created. + EventUpdate // EventUpdate Item has been updated. + EventUpdateFlags // EventUpdateFlags For messages: flags have been updated. ) // Flags for event refresh. diff --git a/pkg/pmapi/import.go b/pkg/pmapi/import.go index aa243bdf..0cb50130 100644 --- a/pkg/pmapi/import.go +++ b/pkg/pmapi/import.go @@ -29,7 +29,7 @@ import ( const ( MaxImportMessageRequestLength = 10 - MaxImportMessageRequestSize = 25 * 1024 * 1024 // 25 MB total limit + MaxImportMessageRequestSize = 25 * 1024 * 1024 // MaxImportMessageRequestSize 25 MB total limit ) type ImportMsgReq struct { diff --git a/pkg/pmapi/import_test.go b/pkg/pmapi/import_test.go index f8a5a160..5bae84e2 100644 --- a/pkg/pmapi/import_test.go +++ b/pkg/pmapi/import_test.go @@ -22,7 +22,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "math/rand" "mime/multipart" "net/http" @@ -76,7 +75,7 @@ func TestClient_Import(t *testing.T) { //nolint:funlen r.Equal(t, "form-data", contentDisp) r.Equal(t, "0", params["name"]) - b, err := ioutil.ReadAll(p) + b, err := io.ReadAll(p) r.NoError(t, err) r.Equal(t, string(testImportReqs[0].Message), string(b)) diff --git a/pkg/pmapi/keyring.go b/pkg/pmapi/keyring.go index c3bc1bb9..e9281667 100644 --- a/pkg/pmapi/keyring.go +++ b/pkg/pmapi/keyring.go @@ -22,7 +22,6 @@ import ( "encoding/base64" "encoding/json" "io" - "io/ioutil" "github.com/ProtonMail/gopenpgp/v2/crypto" "github.com/pkg/errors" @@ -231,7 +230,7 @@ func encryptAttachment(kr *crypto.KeyRing, data io.Reader, filename string) (enc return nil, err } - dataBytes, err := ioutil.ReadAll(data) + dataBytes, err := io.ReadAll(data) if err != nil { return } @@ -253,7 +252,7 @@ func decryptAttachment(kr *crypto.KeyRing, keyPackets []byte, data io.Reader) (d if kr == nil { return nil, ErrNoKeyringAvailable } - dataBytes, err := ioutil.ReadAll(data) + dataBytes, err := io.ReadAll(data) if err != nil { return } @@ -269,7 +268,7 @@ func signAttachment(encrypter *crypto.KeyRing, data io.Reader) (signature io.Rea if encrypter == nil { return nil, ErrNoKeyringAvailable } - dataBytes, err := ioutil.ReadAll(data) + dataBytes, err := io.ReadAll(data) if err != nil { return } diff --git a/pkg/pmapi/manager_download.go b/pkg/pmapi/manager_download.go index 58563be5..55fab5b3 100644 --- a/pkg/pmapi/manager_download.go +++ b/pkg/pmapi/manager_download.go @@ -18,7 +18,7 @@ package pmapi import ( - "io/ioutil" + "io" "github.com/ProtonMail/gopenpgp/v2/crypto" "golang.org/x/net/context" @@ -56,7 +56,7 @@ func (m *manager) fetchFile(url string) ([]byte, error) { return nil, err } - b, err := ioutil.ReadAll(res.RawBody()) + b, err := io.ReadAll(res.RawBody()) if err != nil { return nil, err } diff --git a/pkg/pmapi/manager_report_test.go b/pkg/pmapi/manager_report_test.go index 0117fc86..65738991 100644 --- a/pkg/pmapi/manager_report_test.go +++ b/pkg/pmapi/manager_report_test.go @@ -20,7 +20,7 @@ package pmapi import ( "context" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "strings" @@ -68,7 +68,7 @@ func TestClient_BugReportWithAttachment(t *testing.T) { attReader, err := req.MultipartForm.File["log"][0].Open() r.NoError(t, err) - _, err = ioutil.ReadAll(attReader) + _, err = io.ReadAll(attReader) r.NoError(t, err) w.Header().Set("Content-Type", "application/json") diff --git a/pkg/pmapi/messages.go b/pkg/pmapi/messages.go index a3541746..5cb4df83 100644 --- a/pkg/pmapi/messages.go +++ b/pkg/pmapi/messages.go @@ -27,7 +27,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "net/mail" "net/url" @@ -133,10 +132,10 @@ const ( type LabelsOperation int const ( - KeepLabels LabelsOperation = iota // Do nothing. - ReplaceLabels // Replace current labels with new ones. - AddLabels // Add new labels to current ones. - RemoveLabels // Remove specified labels from current ones. + KeepLabels LabelsOperation = iota // KeepLabels Do nothing. + ReplaceLabels // ReplaceLabels Replace current labels with new ones. + AddLabels // AddLabels Add new labels to current ones. + RemoveLabels // RemoveLabels Remove specified labels from current ones. ) // Due to API limitations, we shouldn't make requests with more than 100 message IDs at a time. @@ -309,7 +308,7 @@ func (m *Message) ExtractSignatures(kr *crypto.KeyRing) ([]Signature, error) { return nil, err } - if _, err := ioutil.ReadAll(msg.UnverifiedBody); err != nil { + if _, err := io.ReadAll(msg.UnverifiedBody); err != nil { return nil, err } diff --git a/pkg/pmapi/pmapi_test.go b/pkg/pmapi/pmapi_test.go index 9da33668..619aa944 100644 --- a/pkg/pmapi/pmapi_test.go +++ b/pkg/pmapi/pmapi_test.go @@ -18,7 +18,7 @@ package pmapi import ( - "io/ioutil" + "os" "strings" "github.com/ProtonMail/gopenpgp/v2/crypto" @@ -65,7 +65,7 @@ func init() { } func readTestFile(name string, trimNewlines bool) string { //nolint:unparam - data, err := ioutil.ReadFile("testdata/" + name) + data, err := os.ReadFile("testdata/" + name) if err != nil { panic(err) } diff --git a/pkg/sum/sum_test.go b/pkg/sum/sum_test.go index 87c8a2aa..e8601970 100644 --- a/pkg/sum/sum_test.go +++ b/pkg/sum/sum_test.go @@ -18,7 +18,7 @@ package sum import ( - "io/ioutil" + "io" "os" "path/filepath" "testing" @@ -27,7 +27,7 @@ import ( ) func TestRecursiveSum(t *testing.T) { - tempDir, err := ioutil.TempDir("", "verify-test") + tempDir, err := os.MkdirTemp("", "verify-test") require.NoError(t, err) createFiles(t, tempDir, @@ -97,7 +97,7 @@ func modifyFile(t *testing.T, path string, data []byte) []byte { r, err := os.Open(path) require.NoError(t, err) - b, err := ioutil.ReadAll(r) + b, err := io.ReadAll(r) require.NoError(t, err) require.NoError(t, r.Close()) diff --git a/test/accounts/account.go b/test/accounts/account.go index 58804b58..6aee9e82 100644 --- a/test/accounts/account.go +++ b/test/accounts/account.go @@ -19,7 +19,6 @@ package accounts import ( "encoding/json" - "io/ioutil" "os" "path/filepath" "sort" @@ -90,7 +89,7 @@ func (a *TestAccount) initKeys() { func readTestFile(fileName string) []byte { testDataFolder := os.Getenv("TEST_DATA") path := filepath.Join(testDataFolder, fileName) - data, err := ioutil.ReadFile(path) //nolint:gosec + data, err := os.ReadFile(path) //nolint:gosec if err != nil { panic(err) } diff --git a/test/accounts/accounts.go b/test/accounts/accounts.go index 6dc186e8..143b43c2 100644 --- a/test/accounts/accounts.go +++ b/test/accounts/accounts.go @@ -19,7 +19,7 @@ package accounts import ( "encoding/json" - "io/ioutil" + "os" "github.com/ProtonMail/proton-bridge/v2/pkg/pmapi" "github.com/pkg/errors" @@ -37,7 +37,7 @@ type TestAccounts struct { } func Load(path string) (*TestAccounts, error) { - data, err := ioutil.ReadFile(path) //nolint:gosec + data, err := os.ReadFile(path) //nolint:gosec if err != nil { return nil, errors.Wrap(err, "failed to load JSON") } diff --git a/test/context/bridge_panic_handler.go b/test/context/bridge_panic_handler.go index 7aa04041..1b608af3 100644 --- a/test/context/bridge_panic_handler.go +++ b/test/context/bridge_panic_handler.go @@ -19,7 +19,7 @@ package context import ( "bytes" - "io/ioutil" + "io" "runtime/pprof" ) @@ -41,7 +41,7 @@ func (ph *panicHandler) HandlePanic() { r := bytes.NewBufferString("") _ = pprof.Lookup("goroutine").WriteTo(r, 2) - b, err := ioutil.ReadAll(r) + b, err := io.ReadAll(r) ph.t.Errorf("pprof details: %s %s", err, b) ph.t.FailNow() diff --git a/test/context/cache.go b/test/context/cache.go index db6489f9..9d52e3b4 100644 --- a/test/context/cache.go +++ b/test/context/cache.go @@ -18,7 +18,7 @@ package context import ( - "io/ioutil" + "os" "path/filepath" ) @@ -29,7 +29,7 @@ type fakeCache struct { // newFakeCache creates a temporary folder for files. // It's expected the test calls `ClearData` before finish to remove it from the file system. func newFakeCache() *fakeCache { - dir, err := ioutil.TempDir("", "test-cache") + dir, err := os.MkdirTemp("", "test-cache") if err != nil { panic(err) } diff --git a/test/context/locations.go b/test/context/locations.go index d08be13c..4568568b 100644 --- a/test/context/locations.go +++ b/test/context/locations.go @@ -18,7 +18,6 @@ package context import ( - "io/ioutil" "os" ) @@ -27,7 +26,7 @@ type fakeLocations struct { } func newFakeLocations() *fakeLocations { - dir, err := ioutil.TempDir("", "test-cache") + dir, err := os.MkdirTemp("", "test-cache") if err != nil { panic(err) } diff --git a/test/context/settings.go b/test/context/settings.go index 1f6936df..8f1b2cc3 100644 --- a/test/context/settings.go +++ b/test/context/settings.go @@ -18,8 +18,8 @@ package context import ( - "io/ioutil" "math/rand" + "os" "github.com/ProtonMail/proton-bridge/v2/internal/config/settings" ) @@ -32,7 +32,7 @@ type fakeSettings struct { // newFakeSettings creates a temporary folder for files. // It's expected the test calls `ClearData` before finish to remove it from the file system. func newFakeSettings() *fakeSettings { - dir, err := ioutil.TempDir("", "test-settings") + dir, err := os.MkdirTemp("", "test-settings") if err != nil { panic(err) } diff --git a/test/fakeapi/attachments.go b/test/fakeapi/attachments.go index d73d7263..b26f5d24 100644 --- a/test/fakeapi/attachments.go +++ b/test/fakeapi/attachments.go @@ -23,7 +23,6 @@ import ( "encoding/base64" "fmt" "io" - "io/ioutil" "net/textproto" "github.com/ProtonMail/proton-bridge/v2/pkg/pmapi" @@ -32,8 +31,8 @@ import ( // dataPacketOutlineLightInstagram48png is data packet with encrypted data and // session key // -// gpg: encrypted with 2048-bit RSA key, ID 70B8CA23079F2167, created 2019-09-23 -// "james-test@protonmail.blue " +// gpg: encrypted with 2048-bit RSA key, ID 70B8CA23079F2167, created 2019-09-23 +// "james-test@protonmail.blue " // // If you need to rebuild you can dump KeyPacket string from `CreateAttachment` // function when called during message sending test. @@ -63,14 +62,14 @@ func (api *FakePMAPI) GetAttachment(_ context.Context, attachmentID string) (io. return nil, err } r := bytes.NewReader(b) - return ioutil.NopCloser(r), nil + return io.NopCloser(r), nil } func (api *FakePMAPI) CreateAttachment(_ context.Context, attachment *pmapi.Attachment, data io.Reader, signature io.Reader) (*pmapi.Attachment, error) { if err := api.checkAndRecordCall(POST, "/mail/v4/attachments", nil); err != nil { return nil, err } - bytes, err := ioutil.ReadAll(data) + bytes, err := io.ReadAll(data) if err != nil { return nil, err } diff --git a/test/fakeapi/messages.go b/test/fakeapi/messages.go index 0b0cf8c0..f8bf74c6 100644 --- a/test/fakeapi/messages.go +++ b/test/fakeapi/messages.go @@ -41,13 +41,13 @@ func (api *FakePMAPI) GetMessage(_ context.Context, apiID string) (*pmapi.Messag } // ListMessages does not implement following filters: -// * Sort (it sorts by ID only), but Desc works -// * Keyword -// * To -// * Subject -// * ID -// * Attachments -// * AutoWildcard +// - Sort (it sorts by ID only), but Desc works +// - Keyword +// - To +// - Subject +// - ID +// - Attachments +// - AutoWildcard func (api *FakePMAPI) ListMessages(_ context.Context, filter *pmapi.MessagesFilter) ([]*pmapi.Message, int, error) { if err := api.checkAndRecordCall(GET, "/mail/v4/messages", filter); err != nil { return nil, 0, err diff --git a/test/liveapi/persistent_clients.go b/test/liveapi/persistent_clients.go index 3729421f..e3de0299 100644 --- a/test/liveapi/persistent_clients.go +++ b/test/liveapi/persistent_clients.go @@ -64,7 +64,7 @@ func (pc *persistentClient) AuthDelete(_ context.Context) error { // AuthSalt returns cached string. Otherwise after some time there is an error: // -// Access token does not have sufficient scope +// Access token does not have sufficient scope // // while all other routes works normally. Need to confirm with Aron that this // is expected behaviour. diff --git a/test/liveapi/transport.go b/test/liveapi/transport.go index 02e406e6..28a7b594 100644 --- a/test/liveapi/transport.go +++ b/test/liveapi/transport.go @@ -18,7 +18,7 @@ package liveapi import ( - "io/ioutil" + "io" "net/http" "github.com/pkg/errors" @@ -49,7 +49,7 @@ func (t *fakeTransport) RoundTrip(req *http.Request) (*http.Response, error) { return nil, errors.Wrap(err, "failed to get body") } if bodyReader != nil { - body, err = ioutil.ReadAll(bodyReader) + body, err = io.ReadAll(bodyReader) if err != nil { return nil, errors.Wrap(err, "failed to read body") }