Other: add straightforward linters

This commit is contained in:
Jakub
2021-04-08 08:00:39 +02:00
parent 7d0af7624c
commit 2d95f21567
49 changed files with 148 additions and 139 deletions

View File

@ -69,7 +69,7 @@ const (
flagMemProfileShort = "m"
flagLogLevel = "log-level"
flagLogLevelShort = "l"
// FlagCLI indicate to start with command line interface
// FlagCLI indicate to start with command line interface.
FlagCLI = "cli"
flagCLIShort = "c"
flagRestart = "restart"

View File

@ -34,7 +34,7 @@ import (
// | prefs | ~/.cache/protonmail/<app>/c11/prefs.json | ~/.config/protonmail/<app>/prefs.json |
// | c11 1.5.x | ~/.cache/protonmail/<app>/c11 | ~/.cache/protonmail/<app>/cache/c11 |
// | c11 1.6.x | ~/.cache/protonmail/<app>/cache/c11 | ~/.config/protonmail/<app>/cache/c11 |
// | updates | ~/.cache/protonmail/<app>/updates | ~/.config/protonmail/<app>/updates |
// | updates | ~/.cache/protonmail/<app>/updates | ~/.config/protonmail/<app>/updates |.
func migrateFiles(configName string) error {
locationsProvider, err := locations.NewDefaultProvider(filepath.Join(constants.VendorName, configName))
if err != nil {
@ -50,7 +50,7 @@ func migrateFiles(configName string) error {
if err := migrateCacheFromBoth15xAnd16x(locations, userCacheDir); err != nil {
return err
}
if err := migrateUpdatesFrom16x(configName, locations); err != nil {
if err := migrateUpdatesFrom16x(configName, locations); err != nil { //nolint[revive] It is more clear to structure this way
return err
}
return nil

View File

@ -122,11 +122,7 @@ func (t *TLS) GenerateCerts(template *x509.Certificate) error {
}
defer keyOut.Close() // nolint[errcheck]
if err := pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}); err != nil {
return err
}
return nil
return pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
}
// GetConfig tries to load TLS config or generate new one which is then returned.

View File

@ -26,7 +26,7 @@ type currentClientSetter interface {
SetClient(name, version string)
}
// Extension for IMAP server
// Extension for IMAP server.
type extension struct {
extID imapserver.ConnExtension
clientSetter currentClientSetter

View File

@ -227,7 +227,8 @@ func (im *imapMailbox) importMessage(m *pmapi.Message, readers []io.Reader, kr *
}
func (im *imapMailbox) getMessage(storeMessage storeMessageProvider, items []imap.FetchItem, msgBuildCountHistogram *msgBuildCountHistogram) (msg *imap.Message, err error) { //nolint[funlen]
im.log.WithField("msgID", storeMessage.ID()).Trace("Getting message")
msglog := im.log.WithField("msgID", storeMessage.ID())
msglog.Trace("Getting message")
seqNum, err := storeMessage.SequenceNumber()
if err != nil {
@ -267,7 +268,7 @@ func (im *imapMailbox) getMessage(storeMessage storeMessageProvider, items []ima
// Size attribute on the server counts encrypted data. The value is cleared
// on our part and we need to compute "real" size of decrypted data.
if m.Size <= 0 {
im.log.WithField("msgID", storeMessage.ID()).Trace("Size unknown - downloading body")
msglog.Debug("Size unknown - downloading body")
// We are sure the size is not a problem right now. Clients
// might not first check sizes of all messages so we couldn't
// be sure if seeing 1st or 2nd sync is all right or not.
@ -283,6 +284,8 @@ func (im *imapMailbox) getMessage(storeMessage storeMessageProvider, items []ima
if err != nil {
return nil, err
}
case imap.FetchAll, imap.FetchFast, imap.FetchFull, imap.FetchRFC822, imap.FetchRFC822Header, imap.FetchRFC822Text:
fallthrough // this is list of defined items by go-imap, but items can be also sections generated from requests
default:
if err = im.getLiteralForSection(item, msg, storeMessage, msgBuildCountHistogram); err != nil {
return
@ -295,8 +298,8 @@ func (im *imapMailbox) getMessage(storeMessage storeMessageProvider, items []ima
func (im *imapMailbox) getLiteralForSection(itemSection imap.FetchItem, msg *imap.Message, storeMessage storeMessageProvider, msgBuildCountHistogram *msgBuildCountHistogram) error {
section, err := imap.ParseBodySectionName(itemSection)
if err != nil { // Ignore error
return nil
if err != nil {
return nil //nolint[nilerr] ignore error
}
var literal imap.Literal
@ -743,7 +746,7 @@ func (im *imapMailbox) buildMessageInner(m *pmapi.Message, kr *crypto.KeyRing) (
}
processCallback := func(value interface{}) (interface{}, error) {
att := value.(*pmapi.Attachment)
att := value.(*pmapi.Attachment) //nolint[forcetypeassert] we want to panic here
buf := &bytes.Buffer{}
if err = im.writeAttachmentBody(buf, m, att); err != nil {
@ -753,7 +756,7 @@ func (im *imapMailbox) buildMessageInner(m *pmapi.Message, kr *crypto.KeyRing) (
}
collectCallback := func(idx int, value interface{}) error {
buf := value.(*bytes.Buffer)
buf := value.(*bytes.Buffer) //nolint[forcetypeassert] we want to panic here
defer buf.Reset()
att := atts[idx]

View File

@ -141,7 +141,7 @@ func (im *imapMailbox) addOrRemoveFlags(operation imap.FlagsOp, messageIDs, flag
for _, f := range flags {
switch f {
case imap.SeenFlag:
switch operation {
switch operation { //nolint[exhaustive] imap.SetFlags is processed by im.setFlags
case imap.AddFlags:
if err := im.storeMailbox.MarkMessagesRead(messageIDs); err != nil {
return err
@ -152,7 +152,7 @@ func (im *imapMailbox) addOrRemoveFlags(operation imap.FlagsOp, messageIDs, flag
}
}
case imap.FlaggedFlag:
switch operation {
switch operation { //nolint[exhaustive] imap.SetFlag is processed by im.setFlags
case imap.AddFlags:
if err := im.storeMailbox.MarkMessagesStarred(messageIDs); err != nil {
return err
@ -163,7 +163,7 @@ func (im *imapMailbox) addOrRemoveFlags(operation imap.FlagsOp, messageIDs, flag
}
}
case imap.DeletedFlag:
switch operation {
switch operation { //nolint[exhaustive] imap.SetFlag is processed by im.setFlags
case imap.AddFlags:
if err := im.storeMailbox.MarkMessagesDeleted(messageIDs); err != nil {
return err
@ -182,7 +182,7 @@ func (im *imapMailbox) addOrRemoveFlags(operation imap.FlagsOp, messageIDs, flag
}
// Handle custom junk flags for Apple Mail and Thunderbird.
switch operation {
switch operation { //nolint[exhaustive] imap.SetFlag is processed by im.setFlags
// No label removal is necessary because Spam and Inbox are both exclusive labels so the backend
// will automatically take care of label removal.
case imap.AddFlags:
@ -536,7 +536,7 @@ func (im *imapMailbox) listMessages(isUID bool, seqSet *imap.SeqSet, items []ima
}
processCallback := func(value interface{}) (interface{}, error) {
apiID := value.(string)
apiID := value.(string) //nolint[forcetypeassert] we want to panic here
storeMessage, err := im.storeMailbox.GetMessage(apiID)
if err != nil {
@ -570,7 +570,7 @@ func (im *imapMailbox) listMessages(isUID bool, seqSet *imap.SeqSet, items []ima
}
collectCallback := func(idx int, value interface{}) error {
msg := value.(*imap.Message)
msg := value.(*imap.Message) //nolint[forcetypeassert] we want to panic here
msgResponse <- msg
return nil
}

View File

@ -32,7 +32,7 @@ import (
// - 100 messages were downloaded first time
// - 100 messages were downloaded second time
// - 99 messages were downloaded 10th times
// - 1 messages were downloaded 100th times
// - 1 messages were downloaded 100th times.
type msgBuildCountHistogram struct {
// Key represents how many times message was build.
// Value stores how many messages are build X times based on the key.

View File

@ -33,7 +33,7 @@ import (
"github.com/sirupsen/logrus"
)
// Capability extension identifier
// Capability extension identifier.
const Capability = "UIDPLUS"
const (
@ -228,7 +228,9 @@ func getStatusResponseCopy(uidValidity uint32, sourceSeq, targetSeq *OrderedSeq)
// CopyResponse prepares OK response with extended UID information about copied message.
func CopyResponse(uidValidity uint32, sourceSeq, targetSeq *OrderedSeq) error {
return imap.ErrStatusResp{getStatusResponseCopy(uidValidity, sourceSeq, targetSeq)}
return &imap.ErrStatusResp{
Resp: getStatusResponseCopy(uidValidity, sourceSeq, targetSeq),
}
}
func getStatusResponseAppend(uidValidity uint32, targetSeq *OrderedSeq) *imap.StatusResp {
@ -250,5 +252,7 @@ func getStatusResponseAppend(uidValidity uint32, targetSeq *OrderedSeq) *imap.St
// AppendResponse prepares OK response with extended UID information about appended message.
func AppendResponse(uidValidity uint32, targetSeq *OrderedSeq) error {
return imap.ErrStatusResp{getStatusResponseAppend(uidValidity, targetSeq)}
return &imap.ErrStatusResp{
Resp: getStatusResponseAppend(uidValidity, targetSeq),
}
}

View File

@ -88,7 +88,7 @@ func (ie *ImportExport) ReportBug(osType, osVersion, description, accountName, a
return nil
}
// ReportFile submits import report file
// ReportFile submits import report file.
func (ie *ImportExport) ReportFile(osType, osVersion, accountName, address string, logdata []byte) error {
c := ie.clientManager.GetAnonymousClient()
defer c.Logout()

View File

@ -34,7 +34,7 @@ import (
// - logs: ~/.cache/protonmail/<app>/logs
// - cache: ~/.config/protonmail/<app>/cache
// - updates: ~/.config/protonmail/<app>/updates
// - lockfile: ~/.cache/protonmail/<app>/<app>.lock
// - lockfile: ~/.cache/protonmail/<app>/<app>.lock .
type Locations struct {
userConfig, userCache string
configName string

View File

@ -173,7 +173,7 @@ func (b *sendPreferencesBuilder) withPublicKey(v *crypto.KeyRing) {
// | 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()
@ -492,6 +492,8 @@ func (b *sendPreferencesBuilder) setEncryptionPreferences(mailSettings pmapi.Mai
b.withSchemeDefault(pgpInline)
case pmapi.PGPMIMEPackage:
b.withSchemeDefault(pgpMIME)
case pmapi.ClearMIMEPackage, pmapi.ClearPackage, pmapi.EncryptedOutsidePackage, pmapi.InternalPackage:
// nothing to set
}
// Its value is constrained by the sign flag and the PGP scheme:

View File

@ -156,6 +156,7 @@ func (loop *eventLoop) loop() {
return
case <-t.C:
// Randomise periodic calls within range pollInterval ± pollSpread to reduces potential load spikes on API.
//nolint[gosec] It is OK to use weaker random number generator here
time.Sleep(time.Duration(rand.Intn(2*int(pollIntervalSpread.Milliseconds()))) * time.Millisecond)
case eventProcessedCh = <-loop.pollCh:
// We don't want to wait here. Polling should happen instantly.
@ -381,6 +382,8 @@ func (loop *eventLoop) processAddresses(log *logrus.Entry, addressEvents []*pmap
log.WithField("email", email).Debug("Address was deleted")
loop.user.CloseConnection(email)
loop.events.Emit(bridgeEvents.AddressChangedLogoutEvent, email)
case pmapi.EventUpdateFlags:
log.Error("EventUpdateFlags for address event is uknown operation")
}
}
@ -409,6 +412,8 @@ func (loop *eventLoop) processLabels(eventLog *logrus.Entry, labels []*pmapi.Eve
if err := loop.store.deleteMailboxEvent(eventLabel.ID); err != nil {
return errors.Wrap(err, "failed to delete label")
}
case pmapi.EventUpdateFlags:
log.Error("EventUpdateFlags for label event is uknown operation")
}
}

View File

@ -254,7 +254,7 @@ func (storeMailbox *Mailbox) txGetAPIIDsBucket(tx *bolt.Tx) *bolt.Bucket {
return storeMailbox.txGetBucket(tx).Bucket(apiIDsBucket)
}
// txGetDeletedIDsBucket returns the bucket with messagesID marked as deleted
// txGetDeletedIDsBucket returns the bucket with messagesID marked as deleted.
func (storeMailbox *Mailbox) txGetDeletedIDsBucket(tx *bolt.Tx) *bolt.Bucket {
return storeMailbox.txGetBucket(tx).Bucket(deletedIDsBucket)
}

View File

@ -25,7 +25,7 @@ import (
)
// ErrAllMailOpNotAllowed is error user when user tries to do unsupported
// operation on All Mail folder
// operation on All Mail folder.
var ErrAllMailOpNotAllowed = errors.New("operation not allowed for 'All Mail' folder")
// GetMessage returns the `pmapi.Message` struct wrapped in `StoreMessage`
@ -177,7 +177,7 @@ func (storeMailbox *Mailbox) MarkMessagesUnstarred(apiIDs []string) error {
}
// MarkMessagesDeleted adds local flag \Deleted. This is not propagated to API
// until RemoveDeleted is called
// until RemoveDeleted is called.
func (storeMailbox *Mailbox) MarkMessagesDeleted(apiIDs []string) error {
log.WithFields(logrus.Fields{
"messages": apiIDs,

View File

@ -64,7 +64,7 @@ func (message *Message) Message() *pmapi.Message {
}
// IsMarkedDeleted returns true if message is marked as deleted for specific
// mailbox
// mailbox.
func (message *Message) IsMarkedDeleted() bool {
isMarkedAsDeleted := false
err := message.storeMailbox.db().View(func(tx *bolt.Tx) error {

View File

@ -34,15 +34,15 @@ import (
)
const (
// PathDelimiter for IMAP
// PathDelimiter for IMAP.
PathDelimiter = "/"
// UserLabelsMailboxName for IMAP
// UserLabelsMailboxName for IMAP.
UserLabelsMailboxName = "Labels"
// UserLabelsPrefix contains name with delimiter for IMAP
// UserLabelsPrefix contains name with delimiter for IMAP.
UserLabelsPrefix = UserLabelsMailboxName + PathDelimiter
// UserFoldersMailboxName for IMAP
// UserFoldersMailboxName for IMAP.
UserFoldersMailboxName = "Folders"
// UserFoldersPrefix contains name with delimiter for IMAP
// UserFoldersPrefix contains name with delimiter for IMAP.
UserFoldersPrefix = UserFoldersMailboxName + PathDelimiter
)

View File

@ -90,10 +90,7 @@ func (store *Store) TestDumpDB(tb assert.TestingT) {
return err
}
}
if err := txMails(tx); err != nil {
return err
}
return nil
return txMails(tx)
}
assert.NoError(tb, store.db.View(txDump))

View File

@ -289,7 +289,7 @@ func clearNonMetadata(onlyMeta *pmapi.Message) {
// If there is stored message in metaBucket the size, header and MIMEType are
// not changed if already set. To change these:
// * size must be updated by Message.SetSize
// * contentType and header must be updated by Message.SetContentTypeAndHeader
// * contentType and header must be updated by Message.SetContentTypeAndHeader.
func txUpdateMetadaFromDB(metaBucket *bolt.Bucket, onlyMeta *pmapi.Message, log *logrus.Entry) {
// Size attribute on the server is counting encrypted data. We need to compute
// "real" size of decrypted data. Negative values will be processed during fetch.

View File

@ -35,7 +35,7 @@ var systemFolderMapping = map[string]string{ //nolint[gochecknoglobals]
// Add more translations.
}
// LeastUsedColor is intended to return color for creating a new inbox or label
// LeastUsedColor is intended to return color for creating a new inbox or label.
func LeastUsedColor(mailboxes []Mailbox) string {
usedColors := []string{}
for _, m := range mailboxes {

View File

@ -27,7 +27,7 @@ import (
type IMAPClientProvider interface {
Capability() (map[string]bool, error)
Support(cap string) (bool, error)
Support(capability string) (bool, error)
State() imap.ConnState
SupportAuth(mech string) (bool, error)
Authenticate(auth sasl.Client) error

View File

@ -329,10 +329,10 @@ func (p *PMAPIProvider) importMessage(msgSourceID string, progress *Progress, re
}
if results[0].Error != nil {
importedErr = errors.Wrap(results[0].Error, "failed to import message")
return nil // Call passed but API refused this message, skip this one.
return nil //nolint[nilerr] Call passed but API refused this message, skip this one.
}
importedID = results[0].MessageID
return nil
})
return
return importedID, importedErr
}

View File

@ -85,7 +85,7 @@ func testTransferFrom(t *testing.T, rules transferRules, provider TargetProvider
progress.finish()
}()
maxWait := time.Duration(len(messages)) * 2 * time.Second
maxWait := time.Duration(len(messages)*2) * time.Second
a.Eventually(t, func() bool {
return progress.updateCh == nil
}, maxWait, 10*time.Millisecond, "Waiting for imported messages timed out")

View File

@ -78,7 +78,7 @@ type VersionInfo struct {
// "...": {
// ...
// }
// }
// }.
type VersionMap map[string]VersionInfo
// getVersionFileURL returns the URL of the version file.

View File

@ -67,7 +67,7 @@ func (s *testCredentials) MarshalGob() string {
if err := enc.Encode(s); err != nil {
return ""
}
fmt.Printf("MarshalGob: %#v\n", buf.String())
log.Infof("MarshalGob: %#v\n", buf.String())
return base64.StdEncoding.EncodeToString(buf.Bytes())
}
@ -88,13 +88,13 @@ func (s *testCredentials) UnmarshalGob(secret string) error {
s.Clear()
b, err := base64.StdEncoding.DecodeString(secret)
if err != nil {
fmt.Println("decode base64", b)
log.Infoln("decode base64", b)
return err
}
buf := bytes.NewBuffer(b)
dec := gob.NewDecoder(buf)
if err = dec.Decode(s); err != nil {
fmt.Println("decode gob", b, buf.Bytes())
log.Info("decode gob", b, buf.Bytes())
return err
}
return nil
@ -102,7 +102,7 @@ func (s *testCredentials) UnmarshalGob(secret string) error {
func (s *testCredentials) ToJSON() string {
if b, err := json.Marshal(s); err == nil {
fmt.Printf("MarshalJSON: %#v\n", string(b))
log.Infof("MarshalJSON: %#v\n", string(b))
return base64.StdEncoding.EncodeToString(b)
}
return ""
@ -134,7 +134,7 @@ func (s *testCredentials) MarshalFmt() string {
s.IsHidden,
s.IsCombinedAddressMode,
)
fmt.Printf("MarshalFmt: %#v\n", buf.String())
log.Infof("MarshalFmt: %#v\n", buf.String())
return base64.StdEncoding.EncodeToString(buf.Bytes())
}
@ -144,7 +144,7 @@ func (s *testCredentials) UnmarshalFmt(secret string) error {
return err
}
buf := bytes.NewBuffer(b)
fmt.Println("decode fmt", b, buf.Bytes())
log.Infoln("decode fmt", b, buf.Bytes())
_, err = fmt.Fscanf(
buf, secretFormat,
&s.UserID,
@ -190,7 +190,7 @@ func (s *testCredentials) MarshalStrings() string { // this is the most space ef
str := strings.Join(items, sep)
fmt.Printf("MarshalJoin: %#v\n", str)
log.Infof("MarshalJoin: %#v\n", str)
return base64.StdEncoding.EncodeToString([]byte(str))
}
@ -237,37 +237,37 @@ func (s *testCredentials) IsSame(rhs *testCredentials) bool {
func TestMarshalFormats(t *testing.T) {
input := testCredentials{UserID: "007", Emails: "ja@pm.me;jakub@cu.th", Timestamp: 152469263742, IsHidden: true}
fmt.Printf("input %#v\n", input)
log.Infof("input %#v\n", input)
secretStrings := input.MarshalStrings()
fmt.Printf("secretStrings %#v %d\n", secretStrings, len(secretStrings))
log.Infof("secretStrings %#v %d\n", secretStrings, len(secretStrings))
secretGob := input.MarshalGob()
fmt.Printf("secretGob %#v %d\n", secretGob, len(secretGob))
log.Infof("secretGob %#v %d\n", secretGob, len(secretGob))
secretJSON := input.ToJSON()
fmt.Printf("secretJSON %#v %d\n", secretJSON, len(secretJSON))
log.Infof("secretJSON %#v %d\n", secretJSON, len(secretJSON))
secretFmt := input.MarshalFmt()
fmt.Printf("secretFmt %#v %d\n", secretFmt, len(secretFmt))
log.Infof("secretFmt %#v %d\n", secretFmt, len(secretFmt))
output := testCredentials{APIToken: "refresh"}
require.NoError(t, output.UnmarshalStrings(secretStrings))
fmt.Printf("strings out %#v \n", output)
log.Infof("strings out %#v \n", output)
require.True(t, input.IsSame(&output), "strings out not same")
output = testCredentials{APIToken: "refresh"}
require.NoError(t, output.UnmarshalGob(secretGob))
fmt.Printf("gob out %#v\n \n", output)
log.Infof("gob out %#v\n \n", output)
assert.Equal(t, input, output)
output = testCredentials{APIToken: "refresh"}
require.NoError(t, output.FromJSON(secretJSON))
fmt.Printf("json out %#v \n", output)
log.Infof("json out %#v \n", output)
require.True(t, input.IsSame(&output), "json out not same")
/*
// Simple Fscanf not working!
output = testCredentials{APIToken: "refresh"}
require.NoError(t, output.UnmarshalFmt(secretFmt))
fmt.Printf("fmt out %#v \n", output)
log.Infof("fmt out %#v \n", output)
require.True(t, input.IsSame(&output), "fmt out not same")
*/
}
@ -285,13 +285,13 @@ func TestMarshal(t *testing.T) {
IsHidden: true,
IsCombinedAddressMode: false,
}
fmt.Printf("input %#v\n", input)
log.Infof("input %#v\n", input)
secret := input.Marshal()
fmt.Printf("secret %#v %d\n", secret, len(secret))
log.Infof("secret %#v %d\n", secret, len(secret))
output := Credentials{APIToken: "refresh"}
require.NoError(t, output.Unmarshal(secret))
fmt.Printf("output %#v\n", output)
log.Infof("output %#v\n", output)
assert.Equal(t, input, output)
}