Skip to content

Commit

Permalink
fix: fixed multiple bare except warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
Lorenzo Delgado authored Apr 4, 2023
1 parent 7c229ec commit caf7824
Show file tree
Hide file tree
Showing 15 changed files with 140 additions and 140 deletions.
2 changes: 1 addition & 1 deletion apps/wakubridge/wakubridge.nim
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ when isMainModule:

# Adhere to NO_COLOR initiative: https://no-color.org/
let color = try: not parseBool(os.getEnv("NO_COLOR", "false"))
except: true
except CatchableError: true

logging.setupLogLevel(conf.logLevel)
logging.setupLogFormat(conf.logFormat, color)
Expand Down
8 changes: 4 additions & 4 deletions apps/wakunode2/config.nim
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ proc parseCmdArg*(T: type crypto.PrivateKey, p: string): T =
try:
let key = SkPrivateKey.init(utils.fromHex(p)).tryGet()
crypto.PrivateKey(scheme: Secp256k1, skkey: key)
except:
except CatchableError:
raise newException(ConfigurationError, "Invalid private key")

proc completeCmdArg*(T: type crypto.PrivateKey, val: string): seq[string] =
Expand All @@ -461,7 +461,7 @@ proc completeCmdArg*(T: type crypto.PrivateKey, val: string): seq[string] =
proc parseCmdArg*(T: type ValidIpAddress, p: string): T =
try:
ValidIpAddress.init(p)
except:
except CatchableError:
raise newException(ConfigurationError, "Invalid IP address")

proc completeCmdArg*(T: type ValidIpAddress, val: string): seq[string] =
Expand All @@ -476,7 +476,7 @@ proc defaultListenAddress*(): ValidIpAddress =
proc parseCmdArg*(T: type Port, p: string): T =
try:
Port(parseInt(p))
except:
except CatchableError:
raise newException(ConfigurationError, "Invalid Port number")

proc completeCmdArg*(T: type Port, val: string): seq[string] =
Expand All @@ -485,7 +485,7 @@ proc completeCmdArg*(T: type Port, val: string): seq[string] =
proc parseCmdArg*(T: type Option[int], p: string): T =
try:
some(parseInt(p))
except:
except CatchableError:
raise newException(ConfigurationError, "Invalid number")

## Configuration validation
Expand Down
2 changes: 1 addition & 1 deletion apps/wakunode2/wakunode2.nim
Original file line number Diff line number Diff line change
Expand Up @@ -608,7 +608,7 @@ when isMainModule:

# Adhere to NO_COLOR initiative: https://no-color.org/
let color = try: not parseBool(os.getEnv("NO_COLOR", "false"))
except: true
except CatchableError: true

logging.setupLogLevel(conf.logLevel)
logging.setupLogFormat(conf.logFormat, color)
Expand Down
6 changes: 3 additions & 3 deletions tests/v2/waku_rln_relay/test_rln_group_manager_onchain.nim
Original file line number Diff line number Diff line change
Expand Up @@ -133,11 +133,11 @@ proc runGanache(): Process =
ganacheStartLog.add(cmdline)
if cmdline.contains("Listening on 127.0.0.1:8540"):
break
except:
except CatchableError:
break
debug "Ganache daemon is running and ready", pid=ganachePID, startLog=ganacheStartLog
return runGanache
except:
except: # TODO: Fix "BareExcept" warning
error "Ganache daemon run failed"


Expand All @@ -153,7 +153,7 @@ proc stopGanache(runGanache: Process) {.used.} =
# ref: https://nim-lang.org/docs/osproc.html#waitForExit%2CProcess%2Cint
# debug "ganache logs", logs=runGanache.outputstream.readAll()
debug "Sent SIGTERM to Ganache", ganachePID=ganachePID
except:
except CatchableError:
error "Ganache daemon termination failed: ", err = getCurrentExceptionMsg()

proc setup(signer = true): Future[OnchainGroupManager] {.async.} =
Expand Down
8 changes: 4 additions & 4 deletions tools/networkmonitor/networkmonitor.nim
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ proc populateInfoFromIp(allPeersRef: CustomPeersTableRef,
await sleepAsync(1400)
let response = await restClient.ipToLocation(allPeersRef[peer].ip)
location = response.data
except:
except CatchableError:
warn "could not get location", ip=allPeersRef[peer].ip
continue
allPeersRef[peer].country = location.country
Expand Down Expand Up @@ -214,7 +214,7 @@ proc getBootstrapFromDiscDns(conf: NetworkMonitorConf): Result[seq[enr.Record],
if tenrRes.isOk() and (tenrRes.get().udp.isSome() or tenrRes.get().udp6.isSome()):
discv5BootstrapEnrs.add(enr)
return ok(discv5BootstrapEnrs)
except:
except CatchableError:
error("failed discovering peers from DNS")

proc initAndStartNode(conf: NetworkMonitorConf): Result[WakuNode, string] =
Expand Down Expand Up @@ -249,7 +249,7 @@ proc initAndStartNode(conf: NetworkMonitorConf): Result[WakuNode, string] =

node.wakuDiscv5.protocol.open()
return ok(node)
except:
except CatchableError:
error("could not start node")

proc startRestApiServer(conf: NetworkMonitorConf,
Expand All @@ -266,7 +266,7 @@ proc startRestApiServer(conf: NetworkMonitorConf,
var sres = RestServerRef.new(router, serverAddress)
let restServer = sres.get()
restServer.start()
except:
except CatchableError:
error("could not start rest api server")
ok()

Expand Down
4 changes: 2 additions & 2 deletions tools/networkmonitor/networkmonitor_utils.nim
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ when (NimMajor, NimMinor) < (1, 4):
{.push raises: [Defect].}
else:
{.push raises: [].}

import
std/json,
stew/results,
Expand Down Expand Up @@ -44,7 +44,7 @@ proc decodeBytes*(t: typedesc[NodeLocation], value: openArray[byte],
long: $jsonContent["lon"].getFloat(),
isp: jsonContent["isp"].getStr()
))
except:
except CatchableError:
return err("failed to get the location: " & getCurrentExceptionMsg())

proc encodeString*(value: string): RestResult[string] =
Expand Down
4 changes: 2 additions & 2 deletions waku/common/logging.nim
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ converter toChroniclesLogLevel(level: LogLevel): chronicles.LogLevel =
## Map logging log levels to the corresponding nim-chronicles' log level
try:
parseEnum[chronicles.LogLevel]($level)
except:
except CatchableError:
chronicles.LogLevel.NONE


Expand Down Expand Up @@ -71,7 +71,7 @@ proc writeAndFlush(f: File, s: LogOutputStr) =
try:
f.write(s)
f.flushFile()
except:
except CatchableError:
logLoggingFailure(cstring(s), getCurrentException())


Expand Down
2 changes: 1 addition & 1 deletion waku/v2/node/rest/relay/types.nim
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ proc readValue*(reader: var JsonReader[RestJson], value: var RelayWakuMessage)
# Check for reapeated keys
if keys.containsOrIncl(fieldName):
let err = try: fmt"Multiple `{fieldName}` fields found"
except: "Multiple fields with the same name found"
except CatchableError: "Multiple fields with the same name found"
reader.raiseUnexpectedField(err, "RelayWakuMessage")

case fieldName
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ method getMessages*(
): ArchiveDriverResult[seq[ArchiveRow]] =
let cursor = cursor.map(toIndex)

let matchesQuery: QueryFilterMatcher = proc(row: IndexedWakuMessage): bool =
let matchesQuery: QueryFilterMatcher = func(row: IndexedWakuMessage): bool =
if pubsubTopic.isSome() and row.pubsubTopic != pubsubTopic.get():
return false

Expand All @@ -273,7 +273,7 @@ method getMessages*(
var pageRes: QueueDriverGetPageResult
try:
pageRes = driver.getPage(maxPageSize, ascendingOrder, cursor, matchesQuery)
except:
except: # TODO: Fix "BareExcept" warning
return err(getCurrentExceptionMsg())

if pageRes.isErr():
Expand Down
4 changes: 2 additions & 2 deletions waku/v2/protocol/waku_filter/client.nim
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ proc clear(m: var SubscriptionManager) =
proc registerSubscription(m: SubscriptionManager, pubsubTopic: PubsubTopic, contentTopic: ContentTopic, handler: FilterPushHandler) =
try:
m.subscriptions[(pubsubTopic, contentTopic)]= handler
except:
except: # TODO: Fix "BareExcept" warning
error "failed to register filter subscription", error=getCurrentExceptionMsg()

proc removeSubscription(m: SubscriptionManager, pubsubTopic: PubsubTopic, contentTopic: ContentTopic) =
Expand All @@ -60,7 +60,7 @@ proc notifySubscriptionHandler(m: SubscriptionManager, pubsubTopic: PubsubTopic,
try:
let handler = m.subscriptions[(pubsubTopic, contentTopic)]
handler(pubsubTopic, message)
except:
except: # TODO: Fix "BareExcept" warning
discard

proc getSubscriptionsCount(m: SubscriptionManager): int =
Expand Down
32 changes: 16 additions & 16 deletions waku/v2/protocol/waku_keystore/keystore.nim
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ when (NimMajor, NimMinor) < (1, 4):
else:
{.push raises: [].}

import
import
options, json, strutils,
std/[algorithm, os, sequtils, sets]

Expand Down Expand Up @@ -42,7 +42,7 @@ proc createAppKeystore*(path: string,
finally:
f.close()

# This proc load a keystore based on the application, appIdentifier and version filters.
# This proc load a keystore based on the application, appIdentifier and version filters.
# If none is found, it automatically creates an empty keystore for the passed parameters
proc loadAppKeystore*(path: string,
appInfo: AppInfo,
Expand Down Expand Up @@ -80,11 +80,11 @@ proc loadAppKeystore*(path: string,
# We parse the json
data = json.parseJson(keystore)

# We check if parsed json contains the relevant keystore credentials fields and if these are set to the passed parameters
# We check if parsed json contains the relevant keystore credentials fields and if these are set to the passed parameters
# (note that "if" is lazy, so if one of the .contains() fails, the json fields contents will not be checked and no ResultDefect will be raised due to accessing unavailable fields)
if data.hasKeys(["application", "appIdentifier", "credentials", "version"]) and
data["application"].getStr() == appInfo.application and
data["appIdentifier"].getStr() == appInfo.appIdentifier and
data["application"].getStr() == appInfo.application and
data["appIdentifier"].getStr() == appInfo.appIdentifier and
data["version"].getStr() == appInfo.version:
# We return the first json keystore that matches the passed app parameters
# We assume a unique kesytore with such parameters is present in the file
Expand All @@ -106,7 +106,7 @@ proc loadAppKeystore*(path: string,
return ok(matchingAppKeystore)


# Adds a sequence of membership credential to the keystore matching the application, appIdentifier and version filters.
# Adds a sequence of membership credential to the keystore matching the application, appIdentifier and version filters.
proc addMembershipCredentials*(path: string,
credentials: seq[MembershipCredentials],
password: string,
Expand Down Expand Up @@ -143,7 +143,7 @@ proc addMembershipCredentials*(path: string,

# we parse the json decrypted keystoreCredential
let decodedCredentialRes = decode(decodedKeyfileRes.get())

if decodedCredentialRes.isOk():
let keyfileMembershipCredential = decodedCredentialRes.get()

Expand All @@ -166,13 +166,13 @@ proc addMembershipCredentials*(path: string,

# we update the original credential field in keystoreCredentials
keystoreCredential = updatedCredentialKeyfileRes.get()

found = true

# We stop decrypting other credentials in the keystore
break

# If no credential in keystore with same input identityCredential value is found, we add it
# If no credential in keystore with same input identityCredential value is found, we add it
if found == false:

let encodedMembershipCredential = membershipCredential.encode()
Expand All @@ -183,13 +183,13 @@ proc addMembershipCredentials*(path: string,
# We add it to the credentials field of the keystore
jsonKeystore["credentials"].add(keyfileRes.get())

except:
except CatchableError:
return err(KeystoreJsonError)

# We save to disk the (updated) keystore.
if save(jsonKeystore, path, separator).isErr():
return err(KeystoreOsError)

return ok()

# Returns the membership credentials in the keystore matching the application, appIdentifier and version filters, further filtered by the input
Expand Down Expand Up @@ -226,16 +226,16 @@ proc getMembershipCredentials*(path: string,
if decodedKeyfileRes.isOk():
# we parse the json decrypted keystoreCredential
let decodedCredentialRes = decode(decodedKeyfileRes.get())

if decodedCredentialRes.isOk():
let keyfileMembershipCredential = decodedCredentialRes.get()

let filteredCredentialOpt = filterCredential(keyfileMembershipCredential, filterIdentityCredentials, filterMembershipContracts)

if filteredCredentialOpt.isSome():
outputMembershipCredentials.add(filteredCredentialOpt.get())

except:
except CatchableError:
return err(KeystoreJsonError)

return ok(outputMembershipCredentials)
return ok(outputMembershipCredentials)
24 changes: 12 additions & 12 deletions waku/v2/protocol/waku_keystore/utils.nim
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ when (NimMajor, NimMinor) < (1, 4):
else:
{.push raises: [].}

import
import
json,
std/[options, os, sequtils],
./keyfile,
Expand All @@ -17,17 +17,17 @@ proc hasKeys*(data: JsonNode, keys: openArray[string]): bool =
proc sortMembershipGroup*(a,b: MembershipGroup): int =
return cmp(a.membershipContract.address, b.membershipContract.address)

# Safely saves a Keystore's JsonNode to disk.
# If exists, the destination file is renamed with extension .bkp; the file is written at its destination and the .bkp file is removed if write is successful, otherwise is restored
# Safely saves a Keystore's JsonNode to disk.
# If exists, the destination file is renamed with extension .bkp; the file is written at its destination and the .bkp file is removed if write is successful, otherwise is restored
proc save*(json: JsonNode, path: string, separator: string): KeystoreResult[void] =

# We first backup the current keystore
if fileExists(path):
try:
moveFile(path, path & ".bkp")
except:
except: # TODO: Fix "BareExcept" warning
return err(KeystoreOsError)

# We save the updated json
var f: File
if not f.open(path, fmAppend):
Expand All @@ -45,7 +45,7 @@ proc save*(json: JsonNode, path: string, separator: string): KeystoreResult[void
f.close()
removeFile(path)
moveFile(path & ".bkp", path)
except:
except: # TODO: Fix "BareExcept" warning
# Unlucky, we just fail
return err(KeystoreOsError)
return err(KeystoreOsError)
Expand All @@ -56,7 +56,7 @@ proc save*(json: JsonNode, path: string, separator: string): KeystoreResult[void
if fileExists(path & ".bkp"):
try:
removeFile(path & ".bkp")
except:
except CatchableError:
return err(KeystoreOsError)

return ok()
Expand All @@ -65,7 +65,7 @@ proc save*(json: JsonNode, path: string, separator: string): KeystoreResult[void
proc filterCredential*(credential: MembershipCredentials,
filterIdentityCredentials: seq[IdentityCredential],
filterMembershipContracts: seq[MembershipContract]): Option[MembershipCredentials] =

# We filter by identity credentials
if filterIdentityCredentials.len() != 0:
if (credential.identityCredential in filterIdentityCredentials) == false:
Expand All @@ -74,7 +74,7 @@ proc filterCredential*(credential: MembershipCredentials,
# We filter by membership groups credentials
if filterMembershipContracts.len() != 0:
# Here we keep only groups that match a contract in the filter
var membershipGroupsIntersection: seq[MembershipGroup] = @[]
var membershipGroupsIntersection: seq[MembershipGroup] = @[]
# We check if we have a group in the input credential matching any contract in the filter
for membershipGroup in credential.membershipGroups:
if membershipGroup.membershipContract in filterMembershipContracts:
Expand All @@ -87,9 +87,9 @@ proc filterCredential*(credential: MembershipCredentials,

else:
return none(MembershipCredentials)
# We hit this return only if

# We hit this return only if
# - filterIdentityCredentials.len() == 0 and filterMembershipContracts.len() == 0 (no filter)
# - filterIdentityCredentials.len() != 0 and filterMembershipContracts.len() == 0 (filter only on identity credential)
# Indeed, filterMembershipContracts.len() != 0 will have its exclusive return based on all values of membershipGroupsIntersection.len()
return some(credential)
return some(credential)
Loading

0 comments on commit caf7824

Please sign in to comment.