diff --git a/appservice/appservice.go b/appservice/appservice.go
index b4c36a27..8207d5ca 100644
--- a/appservice/appservice.go
+++ b/appservice/appservice.go
@@ -191,11 +191,12 @@ func (as *AppService) makeIntent(userID id.UserID) *IntentAPI {
localpart, homeserver, err := userID.Parse()
if err != nil || len(localpart) == 0 || homeserver != as.HomeserverDomain {
- if err != nil {
+ switch {
+ case err != nil:
as.Log.Fatalfln("Failed to parse user ID %s: %v", userID, err)
- } else if len(localpart) == 0 {
+ case len(localpart) == 0:
as.Log.Fatalfln("Failed to make intent for %s: localpart is empty", userID)
- } else if homeserver != as.HomeserverDomain {
+ case homeserver != as.HomeserverDomain:
as.Log.Fatalfln("Failed to make intent for %s: homeserver isn't %s", userID, as.HomeserverDomain)
}
return nil
diff --git a/appservice/http.go b/appservice/http.go
index 15c99345..94f588f4 100644
--- a/appservice/http.go
+++ b/appservice/http.go
@@ -182,13 +182,14 @@ func (as *AppService) handleDeviceLists(dl *mautrix.DeviceLists) {
func (as *AppService) handleEvents(evts []*event.Event, defaultTypeClass event.TypeClass) {
for _, evt := range evts {
- if len(evt.ToUserID) > 0 {
+ switch {
+ case len(evt.ToUserID) > 0:
evt.Type.Class = event.ToDeviceEventType
- } else if defaultTypeClass != event.UnknownEventType {
+ case defaultTypeClass != event.UnknownEventType:
evt.Type.Class = defaultTypeClass
- } else if evt.StateKey != nil {
+ case evt.StateKey != nil:
evt.Type.Class = event.StateEventType
- } else {
+ default:
evt.Type.Class = event.MessageEventType
}
err := evt.Content.ParseRaw(evt.Type)
diff --git a/appservice/sqlstatestore/statestore.go b/appservice/sqlstatestore/statestore.go
index 23377fd2..22e43fb3 100644
--- a/appservice/sqlstatestore/statestore.go
+++ b/appservice/sqlstatestore/statestore.go
@@ -11,7 +11,6 @@ import (
"embed"
"encoding/json"
"errors"
- "sync"
"maunium.net/go/mautrix/appservice"
"maunium.net/go/mautrix/event"
@@ -34,8 +33,7 @@ type SQLStateStore struct {
*dbutil.Database
*appservice.TypingStateStore
- Typing map[id.RoomID]map[id.UserID]int64
- typingLock sync.RWMutex
+ Typing map[id.RoomID]map[id.UserID]int64
}
var _ appservice.StateStore = (*SQLStateStore)(nil)
diff --git a/appservice/websocket.go b/appservice/websocket.go
index 1eca8878..bf3e6537 100644
--- a/appservice/websocket.go
+++ b/appservice/websocket.go
@@ -53,7 +53,7 @@ func (wsc *WebsocketCommand) MakeResponse(ok bool, data interface{}) *WebsocketR
var prefixMessage string
for unwrappedErr != nil {
errorData, jsonErr = json.Marshal(unwrappedErr)
- if errorData != nil && len(errorData) > 2 && jsonErr == nil {
+ if len(errorData) > 2 && jsonErr == nil {
prefixMessage = strings.Replace(err.Error(), unwrappedErr.Error(), "", 1)
prefixMessage = strings.TrimRight(prefixMessage, ": ")
break
@@ -216,24 +216,24 @@ func (as *AppService) RequestWebsocket(ctx context.Context, cmd *WebsocketReques
}
select {
case resp := <-respChan:
- if resp.Command == "__websocket_closed" {
+ switch {
+ case resp.Command == "__websocket_closed":
return ErrWebsocketClosed
- } else if resp.Command == "error" {
+ case resp.Command == "error":
var respErr ErrorResponse
err = json.Unmarshal(resp.Data, &respErr)
if err != nil {
return fmt.Errorf("failed to parse error JSON: %w", err)
}
return &respErr
- } else if response != nil {
+ case response != nil:
err = json.Unmarshal(resp.Data, &response)
if err != nil {
return fmt.Errorf("failed to parse response JSON: %w", err)
}
return nil
- } else {
- return nil
}
+ return nil
case <-ctx.Done():
return ctx.Err()
}
@@ -260,7 +260,8 @@ func (as *AppService) consumeWebsocket(stopFunc func(error), ws *websocket.Conn)
stopFunc(parseCloseError(err))
return
}
- if msg.Command == "" || msg.Command == "transaction" {
+ switch {
+ case msg.Command == "", msg.Command == "transaction":
if msg.TxnID == "" || !as.txnIDC.IsProcessed(msg.TxnID) {
as.handleTransaction(msg.TxnID, &msg.Transaction)
} else {
@@ -272,9 +273,9 @@ func (as *AppService) consumeWebsocket(stopFunc func(error), ws *websocket.Conn)
as.Log.Warnfln("Failed to send response to %s %d: %v", msg.Command, msg.ReqID, err)
}
}()
- } else if msg.Command == "connect" {
+ case msg.Command == "connect":
as.Log.Debugln("Websocket connect confirmation received")
- } else if msg.Command == "response" || msg.Command == "error" {
+ case msg.Command == "response", msg.Command == "error":
as.websocketRequestsLock.RLock()
respChan, ok := as.websocketRequests[msg.ReqID]
if ok {
@@ -287,7 +288,7 @@ func (as *AppService) consumeWebsocket(stopFunc func(error), ws *websocket.Conn)
as.Log.Warnfln("Dropping response to %d: unknown request ID", msg.ReqID)
}
as.websocketRequestsLock.RUnlock()
- } else {
+ default:
as.websocketHandlersLock.RLock()
handler, ok := as.websocketHandlers[msg.Command]
as.websocketHandlersLock.RUnlock()
@@ -297,11 +298,12 @@ func (as *AppService) consumeWebsocket(stopFunc func(error), ws *websocket.Conn)
go func() {
okResp, data := handler(msg.WebsocketCommand)
err = as.SendWebsocket(msg.MakeResponse(okResp, data))
- if err != nil {
+ switch {
+ case err != nil:
as.Log.Warnfln("Failed to send response to %s %d: %v", msg.Command, msg.ReqID, err)
- } else if okResp {
+ case okResp:
as.Log.Debugfln("Sent success response to %s %d", msg.Command, msg.ReqID)
- } else {
+ default:
as.Log.Debugfln("Sent error response to %s %d", msg.Command, msg.ReqID)
}
}()
@@ -327,12 +329,14 @@ func (as *AppService) StartWebsocket(baseURL string, onConnect func()) error {
"X-Mautrix-Process-ID": []string{as.ProcessID},
"X-Mautrix-Websocket-Version": []string{"3"},
})
- if resp != nil && resp.StatusCode >= 400 {
- var errResp Error
- err = json.NewDecoder(resp.Body).Decode(&errResp)
- if err != nil {
- return fmt.Errorf("websocket request returned HTTP %d with non-JSON body", resp.StatusCode)
- } else {
+ if resp != nil {
+ defer resp.Body.Close()
+ if resp.StatusCode >= 400 {
+ var errResp Error
+ err = json.NewDecoder(resp.Body).Decode(&errResp)
+ if err != nil {
+ return fmt.Errorf("websocket request returned HTTP %d with non-JSON body", resp.StatusCode)
+ }
return fmt.Errorf("websocket request returned %s (HTTP %d): %s", errResp.ErrorCode, resp.StatusCode, errResp.Message)
}
} else if err != nil {
diff --git a/client.go b/client.go
index a452bf2a..b633acbc 100644
--- a/client.go
+++ b/client.go
@@ -588,7 +588,7 @@ func (cli *Client) FullSyncRequest(req ReqSync) (resp *RespSync, err error) {
}
start := time.Now()
_, err = cli.MakeFullRequest(fullReq)
- duration := time.Now().Sub(start)
+ duration := time.Since(start)
timeout := time.Duration(req.Timeout) * time.Millisecond
buffer := 10 * time.Second
if req.Since == "" {
@@ -657,7 +657,7 @@ func (cli *Client) RegisterGuest(req *ReqRegister) (*RespRegister, *RespUserInte
// }
// token := res.AccessToken
func (cli *Client) RegisterDummy(req *ReqRegister) (*RespRegister, error) {
- res, uia, err := cli.Register(req)
+ _, uia, err := cli.Register(req)
if err != nil && uia == nil {
return nil, err
} else if uia == nil {
@@ -666,7 +666,7 @@ func (cli *Client) RegisterDummy(req *ReqRegister) (*RespRegister, error) {
return nil, errors.New("server does not support m.login.dummy")
}
req.Auth = BaseAuthData{Type: AuthTypeDummy, Session: uia.Session}
- res, _, err = cli.Register(req)
+ res, _, err := cli.Register(req)
if err != nil {
return nil, err
}
@@ -1094,7 +1094,7 @@ func parseRoomStateArray(_ *http.Request, res *http.Response, responseJSON inter
var evt *event.Event
err = dec.Decode(&evt)
if err != nil {
- return nil, fmt.Errorf("failed to parse state array item #%d: %v", i, err)
+ return nil, fmt.Errorf("failed to parse state array item #%d: %w", i, err)
}
_ = evt.Content.ParseRaw(evt.Type)
subMap, ok := response[evt.Type]
diff --git a/crypto/canonicaljson/json.go b/crypto/canonicaljson/json.go
index fd296e65..83cf3239 100644
--- a/crypto/canonicaljson/json.go
+++ b/crypto/canonicaljson/json.go
@@ -164,14 +164,15 @@ func CompactJSON(input, output []byte) []byte {
if c == '\\' {
escape := input[i]
i++
- if escape == 'u' {
+ switch escape {
+ case 'u':
// If this is a unicode escape then we need to handle it specially
output, i = compactUnicodeEscape(input, output, i)
- } else if escape == '/' {
+ case '/':
// JSON does not require escaping '/', but allows encoders to escape it as a special case.
// Since the escape isn't required we remove it.
output = append(output, escape)
- } else {
+ default:
// All other permitted escapes are single charater escapes that are already in their shortest form.
output = append(output, '\\', escape)
}
diff --git a/crypto/utils/utils.go b/crypto/utils/utils.go
index e320bca1..0544a0da 100644
--- a/crypto/utils/utils.go
+++ b/crypto/utils/utils.go
@@ -69,7 +69,7 @@ func GenA256CTRIV() (iv [AESCTRIVLength]byte) {
func DeriveKeysSHA256(key []byte, name string) ([AESCTRKeyLength]byte, [HMACKeyLength]byte) {
var zeroBytes [32]byte
- derivedHkdf := hkdf.New(sha256.New, key[:], zeroBytes[:], []byte(name))
+ derivedHkdf := hkdf.New(sha256.New, key, zeroBytes[:], []byte(name))
var aesKey [AESCTRKeyLength]byte
var hmacKey [HMACKeyLength]byte
@@ -104,7 +104,7 @@ func DecodeBase58RecoveryKey(recoveryKey string) []byte {
// EncodeBase58RecoveryKey recovers the secret storage from a recovery key.
func EncodeBase58RecoveryKey(key []byte) string {
var inputBytes [35]byte
- copy(inputBytes[2:34], key[:])
+ copy(inputBytes[2:34], key)
inputBytes[0] = 0x8B
inputBytes[1] = 1
diff --git a/crypto/utils/utils_test.go b/crypto/utils/utils_test.go
index eb700b2a..a2e14800 100644
--- a/crypto/utils/utils_test.go
+++ b/crypto/utils/utils_test.go
@@ -41,7 +41,7 @@ func TestPBKDF(t *testing.T) {
}
key := PBKDF2SHA512([]byte("Hello world"), salt, 1000, 256)
expected := "ffk9YdbVE1cgqOWgDaec0lH+rJzO+MuCcxpIn3Z6D0E="
- keyB64 := base64.StdEncoding.EncodeToString([]byte(key))
+ keyB64 := base64.StdEncoding.EncodeToString(key)
if keyB64 != expected {
t.Errorf("Expected base64 of generated key to be `%v`, got `%v`", expected, keyB64)
}
@@ -52,7 +52,7 @@ func TestDecodeSSSSKey(t *testing.T) {
decoded := DecodeBase58RecoveryKey(recoveryKey)
expected := "QCFDrXZYLEFnwf4NikVm62rYGJS2mNBEmAWLC3CgNPw="
- decodedB64 := base64.StdEncoding.EncodeToString(decoded[:])
+ decodedB64 := base64.StdEncoding.EncodeToString(decoded)
if expected != decodedB64 {
t.Errorf("Expected decoded recovery key b64 to be `%v`, got `%v`", expected, decodedB64)
}
@@ -66,7 +66,7 @@ func TestKeyDerivationAndHMAC(t *testing.T) {
recoveryKey := "EsUG Ddi6 e1Cm F4um g38u JN72 d37v Q2ry qCf2 rKgL E2MQ ZQz6"
decoded := DecodeBase58RecoveryKey(recoveryKey)
- aesKey, hmacKey := DeriveKeysSHA256(decoded[:], "m.cross_signing.master")
+ aesKey, hmacKey := DeriveKeysSHA256(decoded, "m.cross_signing.master")
ciphertextBytes, err := base64.StdEncoding.DecodeString("Fx16KlJ9vkd3Dd6CafIq5spaH5QmK5BALMzbtFbQznG2j1VARKK+klc4/Qo=")
if err != nil {
diff --git a/event/message.go b/event/message.go
index e07bc3dd..3f38e9b9 100644
--- a/event/message.go
+++ b/event/message.go
@@ -204,7 +204,7 @@ func (sfi *serializableFileInfo) CopyFrom(fileInfo *FileInfo) *serializableFileI
}
if fileInfo.Duration > 0 {
- sfi.Duration = json.Number(strconv.Itoa(int(fileInfo.Duration)))
+ sfi.Duration = json.Number(strconv.Itoa(fileInfo.Duration))
}
return sfi
}
diff --git a/format/htmlparser.go b/format/htmlparser.go
index 4571aa55..1e8a85d9 100644
--- a/format/htmlparser.go
+++ b/format/htmlparser.go
@@ -103,7 +103,7 @@ func (parser *HTMLParser) listToString(node *html.Node, stripLinebreak bool, ctx
indentLength = Digits(longestIndex)
}
indent := strings.Repeat(" ", indentLength+2)
- var children []string
+ children := make([]string, 0, len(taggedChildren))
for _, child := range taggedChildren {
if child.tag != "li" {
continue
@@ -164,11 +164,12 @@ func (parser *HTMLParser) spanToString(node *html.Node, stripLinebreak bool, ctx
if node.Data == "span" {
reason, isSpoiler := parser.maybeGetAttribute(node, "data-mx-spoiler")
if isSpoiler {
- if parser.SpoilerConverter != nil {
+ switch {
+ case parser.SpoilerConverter != nil:
str = parser.SpoilerConverter(str, reason, ctx)
- } else if len(reason) > 0 {
+ case len(reason) > 0:
str = fmt.Sprintf("||%s|%s||", reason, str)
- } else {
+ default:
str = fmt.Sprintf("||%s||", str)
}
}
@@ -270,7 +271,7 @@ func (parser *HTMLParser) singleNodeToString(node *html.Node, stripLinebreak boo
switch node.Type {
case html.TextNode:
if stripLinebreak {
- node.Data = strings.Replace(node.Data, "\n", "", -1)
+ node.Data = strings.ReplaceAll(node.Data, "\n", "")
}
if parser.TextConverter != nil {
node.Data = parser.TextConverter(node.Data, ctx)
@@ -330,7 +331,7 @@ func (parser *HTMLParser) nodeToString(node *html.Node, stripLinebreak bool, ctx
// Parse converts Matrix HTML into text using the settings in this parser.
func (parser *HTMLParser) Parse(htmlData string, ctx Context) string {
if parser.TabsToSpaces >= 0 {
- htmlData = strings.Replace(htmlData, "\t", strings.Repeat(" ", parser.TabsToSpaces), -1)
+ htmlData = strings.ReplaceAll(htmlData, "\t", strings.Repeat(" ", parser.TabsToSpaces))
}
node, _ := html.Parse(strings.NewReader(htmlData))
return parser.nodeToTagAwareString(node, true, ctx)
diff --git a/format/markdown.go b/format/markdown.go
index fa2a8e8a..d6d71716 100644
--- a/format/markdown.go
+++ b/format/markdown.go
@@ -67,20 +67,19 @@ func HTMLToContent(html string) event.MessageEventContent {
func RenderMarkdown(text string, allowMarkdown, allowHTML bool) event.MessageEventContent {
var htmlBody string
-
- if allowMarkdown {
+ switch {
+ case allowMarkdown:
rndr := withHTML
if !allowHTML {
rndr = noHTML
}
return RenderMarkdownCustom(text, rndr)
- } else if allowHTML {
- htmlBody = strings.Replace(text, "\n", "
", -1)
+ case allowHTML:
+ htmlBody = strings.ReplaceAll(text, "\n", "
")
return HTMLToContent(htmlBody)
- } else {
- return event.MessageEventContent{
- MsgType: event.MsgText,
- Body: text,
- }
+ }
+ return event.MessageEventContent{
+ MsgType: event.MsgText,
+ Body: text,
}
}
diff --git a/format/mdext/nohtml.go b/format/mdext/nohtml.go
index bee69828..49ebcd34 100644
--- a/format/mdext/nohtml.go
+++ b/format/mdext/nohtml.go
@@ -51,11 +51,9 @@ func (ehr *escapingHTMLRenderer) renderHTMLBlock(w util.BufWriter, source []byte
line := n.Lines().At(i)
html.DefaultWriter.RawWrite(w, line.Value(source))
}
- } else {
- if n.HasClosure() {
- closure := n.ClosureLine
- html.DefaultWriter.RawWrite(w, closure.Value(source))
- }
+ } else if n.HasClosure() {
+ closure := n.ClosureLine
+ html.DefaultWriter.RawWrite(w, closure.Value(source))
}
return ast.WalkContinue, nil
}
diff --git a/id/matrixuri.go b/id/matrixuri.go
index 1742d457..1be98104 100644
--- a/id/matrixuri.go
+++ b/id/matrixuri.go
@@ -150,9 +150,8 @@ func ParseMatrixURIOrMatrixToURL(uri string) (*MatrixURI, error) {
return ProcessMatrixURI(parsed)
} else if strings.HasSuffix(parsed.Hostname(), "matrix.to") {
return ProcessMatrixToURL(parsed)
- } else {
- return nil, ErrNotMatrixToOrMatrixURI
}
+ return nil, ErrNotMatrixToOrMatrixURI
}
// ParseMatrixURI implements the matrix: URI parsing algorithm.
diff --git a/id/userid.go b/id/userid.go
index b0e83638..5ae2e66b 100644
--- a/id/userid.go
+++ b/id/userid.go
@@ -189,7 +189,8 @@ func DecodeUserLocalpart(str string) (string, error) {
return "", fmt.Errorf("Byte pos %d: Invalid byte", i)
}
- if b == '_' { // next byte is a-z and should be upper-case or is another _ and should be a literal _
+ switch b {
+ case '_': // next byte is a-z and should be upper-case or is another _ and should be a literal _
if i+1 >= len(strBytes) {
return "", fmt.Errorf("Byte pos %d: expected _[a-z_] encoding but ran out of string", i)
}
@@ -202,7 +203,7 @@ func DecodeUserLocalpart(str string) (string, error) {
outputBuffer.WriteByte(strBytes[i+1] - 0x20) // ASCII shift a-z to A-Z
}
i++ // skip next byte since we just handled it
- } else if b == '=' { // next 2 bytes are hex and should be buffered ready to be read as utf8
+ case '=': // next 2 bytes are hex and should be buffered ready to be read as utf8
if i+2 >= len(strBytes) {
return "", fmt.Errorf("Byte pos: %d: expected quote-printable encoding but ran out of string", i)
}
@@ -213,7 +214,7 @@ func DecodeUserLocalpart(str string) (string, error) {
}
outputBuffer.WriteByte(dst[0])
i += 2 // skip next 2 bytes since we just handled it
- } else { // pass through
+ default: // pass through
outputBuffer.WriteByte(b)
}
}
diff --git a/pushrules/action.go b/pushrules/action.go
index 1f885e0d..490fc0e2 100644
--- a/pushrules/action.go
+++ b/pushrules/action.go
@@ -104,7 +104,7 @@ func (action *PushAction) UnmarshalJSON(raw []byte) error {
if ok {
action.Action = ActionSetTweak
action.Tweak = PushActionTweak(tweak)
- action.Value, _ = val["value"]
+ action.Value = val["value"]
}
}
return nil
diff --git a/pushrules/glob/glob.go b/pushrules/glob/glob.go
index c270dbc5..86ba7bfe 100644
--- a/pushrules/glob/glob.go
+++ b/pushrules/glob/glob.go
@@ -102,7 +102,6 @@ func globToRegex(glob string) (*regexp.Regexp, error) {
if hasGlobCharacters {
return regexp.Compile("^" + regex + "$")
- } else {
- return regexp.Compile(regex)
}
+ return regexp.Compile(regex)
}
diff --git a/requests.go b/requests.go
index 34d4e3c3..e7c28c2d 100644
--- a/requests.go
+++ b/requests.go
@@ -191,9 +191,8 @@ func (otk *OneTimeKey) UnmarshalJSON(data []byte) (err error) {
func (otk *OneTimeKey) MarshalJSON() ([]byte, error) {
if !otk.IsSigned {
return json.Marshal(otk.Key)
- } else {
- return json.Marshal((*serializableOTK)(otk))
}
+ return json.Marshal((*serializableOTK)(otk))
}
type ReqUploadKeys struct {
diff --git a/room.go b/room.go
index c3ddb7e6..b1dcbeb6 100644
--- a/room.go
+++ b/room.go
@@ -25,8 +25,8 @@ func (room Room) UpdateState(evt *event.Event) {
// GetStateEvent returns the state event for the given type/state_key combo, or nil.
func (room Room) GetStateEvent(eventType event.Type, stateKey string) *event.Event {
- stateEventMap, _ := room.State[eventType]
- evt, _ := stateEventMap[stateKey]
+ stateEventMap := room.State[eventType]
+ evt := stateEventMap[stateKey]
return evt
}
diff --git a/url.go b/url.go
index 8d3678e4..264caf03 100644
--- a/url.go
+++ b/url.go
@@ -23,7 +23,7 @@ func parseAndNormalizeBaseURL(homeserverURL string) (*url.URL, error) {
fixedURL := hsURL.String()
hsURL, err = url.Parse(fixedURL)
if err != nil {
- return nil, fmt.Errorf("failed to parse fixed URL '%s': %v", fixedURL, err)
+ return nil, fmt.Errorf("failed to parse fixed URL '%s': %w", fixedURL, err)
}
}
hsURL.RawPath = hsURL.EscapedPath()
@@ -96,10 +96,8 @@ func (cli *Client) BuildURLWithQuery(urlPath PrefixableURLPath, urlQuery map[str
if cli.AppServiceUserID != "" {
query.Set("user_id", string(cli.AppServiceUserID))
}
- if urlQuery != nil {
- for k, v := range urlQuery {
- query.Set(k, v)
- }
+ for k, v := range urlQuery {
+ query.Set(k, v)
}
hsURL.RawQuery = query.Encode()
return hsURL.String()
diff --git a/util/base58/base58check_test.go b/util/base58/base58check_test.go
index ae6c4d67..6c6908ae 100644
--- a/util/base58/base58check_test.go
+++ b/util/base58/base58check_test.go
@@ -5,6 +5,7 @@
package base58_test
import (
+ "errors"
"testing"
"maunium.net/go/mautrix/util/base58"
@@ -52,7 +53,7 @@ func TestBase58Check(t *testing.T) {
// test the two decoding failure cases
// case 1: checksum error
_, _, err := base58.CheckDecode("3MNQE1Y")
- if err != base58.ErrChecksum {
+ if !errors.Is(err, base58.ErrChecksum) {
t.Error("Checkdecode test failed, expected ErrChecksum")
}
// case 2: invalid formats (string lengths below 5 mean the version byte and/or the checksum
@@ -61,7 +62,7 @@ func TestBase58Check(t *testing.T) {
for len := 0; len < 4; len++ {
testString += "x"
_, _, err = base58.CheckDecode(testString)
- if err != base58.ErrInvalidFormat {
+ if !errors.Is(err, base58.ErrInvalidFormat) {
t.Error("Checkdecode test failed, expected ErrInvalidFormat")
}
}
diff --git a/util/dbutil/upgrades.go b/util/dbutil/upgrades.go
index f766fdcd..9349fc28 100644
--- a/util/dbutil/upgrades.go
+++ b/util/dbutil/upgrades.go
@@ -27,8 +27,6 @@ type Upgrader struct {
*sql.DB
Log log.Logger
Dialect Dialect
-
- upgrades []upgrade
}
var ErrUnsupportedDatabaseVersion = fmt.Errorf("unsupported database schema version")
@@ -80,17 +78,24 @@ func (db *Database) checkDatabaseOwner() error {
if db.Owner == "" {
return nil
}
- if _, err := db.Exec(createOwnerTable); err != nil {
+
+ _, err := db.Exec(createOwnerTable)
+ if err != nil {
return fmt.Errorf("failed to ensure database owner table exists: %w", err)
- } else if err = db.QueryRow("SELECT owner FROM database_owner WHERE key=0").Scan(&owner); errors.Is(err, sql.ErrNoRows) {
+ }
+
+ err = db.QueryRow("SELECT owner FROM database_owner WHERE key=0").Scan(&owner)
+ switch {
+ case errors.Is(err, sql.ErrNoRows):
_, err = db.Exec("INSERT INTO database_owner (owner) VALUES ($1)", db.Owner)
if err != nil {
return fmt.Errorf("failed to insert database owner: %w", err)
}
- } else if err != nil {
+ case err != nil:
return fmt.Errorf("failed to check database owner: %w", err)
- } else if owner != db.Owner {
+ case owner != db.Owner:
return fmt.Errorf("%w %s", ErrNotOwned, owner)
+
}
return nil
}
diff --git a/util/dbutil/upgradetable.go b/util/dbutil/upgradetable.go
index 0dc3298f..9b2e1229 100644
--- a/util/dbutil/upgradetable.go
+++ b/util/dbutil/upgradetable.go
@@ -36,12 +36,13 @@ func (ut *UpgradeTable) Register(from, to int, message string, fn upgradeFunc) {
panic("invalid from value in UpgradeTable.Register() call")
}
upg := upgrade{message: message, fn: fn, upgradesTo: to}
- if len(*ut) == from {
+ switch {
+ case len(*ut) == from:
*ut = append(*ut, upg)
return
- } else if len(*ut) < from {
+ case len(*ut) < from:
ut.extend(from + 1)
- } else if (*ut)[from].fn != nil {
+ case (*ut)[from].fn != nil:
panic(fmt.Errorf("tried to override upgrade at %d ('%s') with '%s'", from, (*ut)[from].message, upg.message))
}
(*ut)[from] = upg
@@ -97,13 +98,12 @@ func (db *Database) parseDialectFilter(line []byte) (int, error) {
} else if dialect != db.Dialect {
if len(match[2]) == 0 {
return 1, nil
- } else {
- lineCount, err := strconv.Atoi(string(match[2]))
- if err != nil {
- return 0, fmt.Errorf("invalid line count '%s': %w", match[2], err)
- }
- return lineCount, nil
}
+ lineCount, err := strconv.Atoi(string(match[2]))
+ if err != nil {
+ return 0, fmt.Errorf("invalid line count '%s': %w", match[2], err)
+ }
+ return lineCount, nil
}
}
return 0, nil
@@ -113,11 +113,12 @@ func (db *Database) mutateSQLUpgrade(lines [][]byte) (string, error) {
output := lines[:0]
for i := 0; i < len(lines); i++ {
skipLines, err := db.parseDialectFilter(lines[i])
- if err != nil {
+ switch {
+ case err != nil:
return "", err
- } else if skipLines > 0 {
+ case skipLines > 0:
i += skipLines
- } else {
+ default:
output = append(output, lines[i])
}
}
diff --git a/util/ffmpeg/convert.go b/util/ffmpeg/convert.go
index fab8fb19..5cfd2a05 100644
--- a/util/ffmpeg/convert.go
+++ b/util/ffmpeg/convert.go
@@ -46,7 +46,7 @@ func ConvertPath(inputFile string, outputExtension string, inputArgs []string, o
cmd.Stderr = vcLog
err := cmd.Run()
if err != nil {
- return "", fmt.Errorf("ffmpeg error: %+v", err)
+ return "", fmt.Errorf("ffmpeg error: %+w", err)
}
if removeInput {