Skip to content

Commit caf7824

Browse files
author
Lorenzo Delgado
authored
fix: fixed multiple bare except warnings
1 parent 7c229ec commit caf7824

File tree

15 files changed

+140
-140
lines changed

15 files changed

+140
-140
lines changed

apps/wakubridge/wakubridge.nim

+1-1
Original file line numberDiff line numberDiff line change
@@ -339,7 +339,7 @@ when isMainModule:
339339

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

344344
logging.setupLogLevel(conf.logLevel)
345345
logging.setupLogFormat(conf.logFormat, color)

apps/wakunode2/config.nim

+4-4
Original file line numberDiff line numberDiff line change
@@ -451,7 +451,7 @@ proc parseCmdArg*(T: type crypto.PrivateKey, p: string): T =
451451
try:
452452
let key = SkPrivateKey.init(utils.fromHex(p)).tryGet()
453453
crypto.PrivateKey(scheme: Secp256k1, skkey: key)
454-
except:
454+
except CatchableError:
455455
raise newException(ConfigurationError, "Invalid private key")
456456

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

467467
proc completeCmdArg*(T: type ValidIpAddress, val: string): seq[string] =
@@ -476,7 +476,7 @@ proc defaultListenAddress*(): ValidIpAddress =
476476
proc parseCmdArg*(T: type Port, p: string): T =
477477
try:
478478
Port(parseInt(p))
479-
except:
479+
except CatchableError:
480480
raise newException(ConfigurationError, "Invalid Port number")
481481

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

491491
## Configuration validation

apps/wakunode2/wakunode2.nim

+1-1
Original file line numberDiff line numberDiff line change
@@ -608,7 +608,7 @@ when isMainModule:
608608

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

613613
logging.setupLogLevel(conf.logLevel)
614614
logging.setupLogFormat(conf.logFormat, color)

tests/v2/waku_rln_relay/test_rln_group_manager_onchain.nim

+3-3
Original file line numberDiff line numberDiff line change
@@ -133,11 +133,11 @@ proc runGanache(): Process =
133133
ganacheStartLog.add(cmdline)
134134
if cmdline.contains("Listening on 127.0.0.1:8540"):
135135
break
136-
except:
136+
except CatchableError:
137137
break
138138
debug "Ganache daemon is running and ready", pid=ganachePID, startLog=ganacheStartLog
139139
return runGanache
140-
except:
140+
except: # TODO: Fix "BareExcept" warning
141141
error "Ganache daemon run failed"
142142

143143

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

159159
proc setup(signer = true): Future[OnchainGroupManager] {.async.} =

tools/networkmonitor/networkmonitor.nim

+4-4
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ proc populateInfoFromIp(allPeersRef: CustomPeersTableRef,
151151
await sleepAsync(1400)
152152
let response = await restClient.ipToLocation(allPeersRef[peer].ip)
153153
location = response.data
154-
except:
154+
except CatchableError:
155155
warn "could not get location", ip=allPeersRef[peer].ip
156156
continue
157157
allPeersRef[peer].country = location.country
@@ -214,7 +214,7 @@ proc getBootstrapFromDiscDns(conf: NetworkMonitorConf): Result[seq[enr.Record],
214214
if tenrRes.isOk() and (tenrRes.get().udp.isSome() or tenrRes.get().udp6.isSome()):
215215
discv5BootstrapEnrs.add(enr)
216216
return ok(discv5BootstrapEnrs)
217-
except:
217+
except CatchableError:
218218
error("failed discovering peers from DNS")
219219

220220
proc initAndStartNode(conf: NetworkMonitorConf): Result[WakuNode, string] =
@@ -249,7 +249,7 @@ proc initAndStartNode(conf: NetworkMonitorConf): Result[WakuNode, string] =
249249

250250
node.wakuDiscv5.protocol.open()
251251
return ok(node)
252-
except:
252+
except CatchableError:
253253
error("could not start node")
254254

255255
proc startRestApiServer(conf: NetworkMonitorConf,
@@ -266,7 +266,7 @@ proc startRestApiServer(conf: NetworkMonitorConf,
266266
var sres = RestServerRef.new(router, serverAddress)
267267
let restServer = sres.get()
268268
restServer.start()
269-
except:
269+
except CatchableError:
270270
error("could not start rest api server")
271271
ok()
272272

tools/networkmonitor/networkmonitor_utils.nim

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ when (NimMajor, NimMinor) < (1, 4):
22
{.push raises: [Defect].}
33
else:
44
{.push raises: [].}
5-
5+
66
import
77
std/json,
88
stew/results,
@@ -44,7 +44,7 @@ proc decodeBytes*(t: typedesc[NodeLocation], value: openArray[byte],
4444
long: $jsonContent["lon"].getFloat(),
4545
isp: jsonContent["isp"].getStr()
4646
))
47-
except:
47+
except CatchableError:
4848
return err("failed to get the location: " & getCurrentExceptionMsg())
4949

5050
proc encodeString*(value: string): RestResult[string] =

waku/common/logging.nim

+2-2
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ converter toChroniclesLogLevel(level: LogLevel): chronicles.LogLevel =
2424
## Map logging log levels to the corresponding nim-chronicles' log level
2525
try:
2626
parseEnum[chronicles.LogLevel]($level)
27-
except:
27+
except CatchableError:
2828
chronicles.LogLevel.NONE
2929

3030

@@ -71,7 +71,7 @@ proc writeAndFlush(f: File, s: LogOutputStr) =
7171
try:
7272
f.write(s)
7373
f.flushFile()
74-
except:
74+
except CatchableError:
7575
logLoggingFailure(cstring(s), getCurrentException())
7676

7777

waku/v2/node/rest/relay/types.nim

+1-1
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ proc readValue*(reader: var JsonReader[RestJson], value: var RelayWakuMessage)
8888
# Check for reapeated keys
8989
if keys.containsOrIncl(fieldName):
9090
let err = try: fmt"Multiple `{fieldName}` fields found"
91-
except: "Multiple fields with the same name found"
91+
except CatchableError: "Multiple fields with the same name found"
9292
reader.raiseUnexpectedField(err, "RelayWakuMessage")
9393

9494
case fieldName

waku/v2/protocol/waku_archive/driver/queue_driver/queue_driver.nim

+2-2
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ method getMessages*(
255255
): ArchiveDriverResult[seq[ArchiveRow]] =
256256
let cursor = cursor.map(toIndex)
257257

258-
let matchesQuery: QueryFilterMatcher = proc(row: IndexedWakuMessage): bool =
258+
let matchesQuery: QueryFilterMatcher = func(row: IndexedWakuMessage): bool =
259259
if pubsubTopic.isSome() and row.pubsubTopic != pubsubTopic.get():
260260
return false
261261

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

279279
if pageRes.isErr():

waku/v2/protocol/waku_filter/client.nim

+2-2
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ proc clear(m: var SubscriptionManager) =
4747
proc registerSubscription(m: SubscriptionManager, pubsubTopic: PubsubTopic, contentTopic: ContentTopic, handler: FilterPushHandler) =
4848
try:
4949
m.subscriptions[(pubsubTopic, contentTopic)]= handler
50-
except:
50+
except: # TODO: Fix "BareExcept" warning
5151
error "failed to register filter subscription", error=getCurrentExceptionMsg()
5252

5353
proc removeSubscription(m: SubscriptionManager, pubsubTopic: PubsubTopic, contentTopic: ContentTopic) =
@@ -60,7 +60,7 @@ proc notifySubscriptionHandler(m: SubscriptionManager, pubsubTopic: PubsubTopic,
6060
try:
6161
let handler = m.subscriptions[(pubsubTopic, contentTopic)]
6262
handler(pubsubTopic, message)
63-
except:
63+
except: # TODO: Fix "BareExcept" warning
6464
discard
6565

6666
proc getSubscriptionsCount(m: SubscriptionManager): int =

waku/v2/protocol/waku_keystore/keystore.nim

+16-16
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ when (NimMajor, NimMinor) < (1, 4):
33
else:
44
{.push raises: [].}
55

6-
import
6+
import
77
options, json, strutils,
88
std/[algorithm, os, sequtils, sets]
99

@@ -42,7 +42,7 @@ proc createAppKeystore*(path: string,
4242
finally:
4343
f.close()
4444

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

83-
# We check if parsed json contains the relevant keystore credentials fields and if these are set to the passed parameters
83+
# We check if parsed json contains the relevant keystore credentials fields and if these are set to the passed parameters
8484
# (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)
8585
if data.hasKeys(["application", "appIdentifier", "credentials", "version"]) and
86-
data["application"].getStr() == appInfo.application and
87-
data["appIdentifier"].getStr() == appInfo.appIdentifier and
86+
data["application"].getStr() == appInfo.application and
87+
data["appIdentifier"].getStr() == appInfo.appIdentifier and
8888
data["version"].getStr() == appInfo.version:
8989
# We return the first json keystore that matches the passed app parameters
9090
# We assume a unique kesytore with such parameters is present in the file
@@ -106,7 +106,7 @@ proc loadAppKeystore*(path: string,
106106
return ok(matchingAppKeystore)
107107

108108

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

144144
# we parse the json decrypted keystoreCredential
145145
let decodedCredentialRes = decode(decodedKeyfileRes.get())
146-
146+
147147
if decodedCredentialRes.isOk():
148148
let keyfileMembershipCredential = decodedCredentialRes.get()
149149

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

167167
# we update the original credential field in keystoreCredentials
168168
keystoreCredential = updatedCredentialKeyfileRes.get()
169-
169+
170170
found = true
171171

172172
# We stop decrypting other credentials in the keystore
173173
break
174174

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

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

186-
except:
186+
except CatchableError:
187187
return err(KeystoreJsonError)
188188

189189
# We save to disk the (updated) keystore.
190190
if save(jsonKeystore, path, separator).isErr():
191191
return err(KeystoreOsError)
192-
192+
193193
return ok()
194194

195195
# Returns the membership credentials in the keystore matching the application, appIdentifier and version filters, further filtered by the input
@@ -226,16 +226,16 @@ proc getMembershipCredentials*(path: string,
226226
if decodedKeyfileRes.isOk():
227227
# we parse the json decrypted keystoreCredential
228228
let decodedCredentialRes = decode(decodedKeyfileRes.get())
229-
229+
230230
if decodedCredentialRes.isOk():
231231
let keyfileMembershipCredential = decodedCredentialRes.get()
232-
232+
233233
let filteredCredentialOpt = filterCredential(keyfileMembershipCredential, filterIdentityCredentials, filterMembershipContracts)
234-
234+
235235
if filteredCredentialOpt.isSome():
236236
outputMembershipCredentials.add(filteredCredentialOpt.get())
237237

238-
except:
238+
except CatchableError:
239239
return err(KeystoreJsonError)
240240

241-
return ok(outputMembershipCredentials)
241+
return ok(outputMembershipCredentials)

waku/v2/protocol/waku_keystore/utils.nim

+12-12
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ when (NimMajor, NimMinor) < (1, 4):
33
else:
44
{.push raises: [].}
55

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

20-
# Safely saves a Keystore's JsonNode to disk.
21-
# 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
20+
# Safely saves a Keystore's JsonNode to disk.
21+
# 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
2222
proc save*(json: JsonNode, path: string, separator: string): KeystoreResult[void] =
2323

2424
# We first backup the current keystore
2525
if fileExists(path):
2626
try:
2727
moveFile(path, path & ".bkp")
28-
except:
28+
except: # TODO: Fix "BareExcept" warning
2929
return err(KeystoreOsError)
30-
30+
3131
# We save the updated json
3232
var f: File
3333
if not f.open(path, fmAppend):
@@ -45,7 +45,7 @@ proc save*(json: JsonNode, path: string, separator: string): KeystoreResult[void
4545
f.close()
4646
removeFile(path)
4747
moveFile(path & ".bkp", path)
48-
except:
48+
except: # TODO: Fix "BareExcept" warning
4949
# Unlucky, we just fail
5050
return err(KeystoreOsError)
5151
return err(KeystoreOsError)
@@ -56,7 +56,7 @@ proc save*(json: JsonNode, path: string, separator: string): KeystoreResult[void
5656
if fileExists(path & ".bkp"):
5757
try:
5858
removeFile(path & ".bkp")
59-
except:
59+
except CatchableError:
6060
return err(KeystoreOsError)
6161

6262
return ok()
@@ -65,7 +65,7 @@ proc save*(json: JsonNode, path: string, separator: string): KeystoreResult[void
6565
proc filterCredential*(credential: MembershipCredentials,
6666
filterIdentityCredentials: seq[IdentityCredential],
6767
filterMembershipContracts: seq[MembershipContract]): Option[MembershipCredentials] =
68-
68+
6969
# We filter by identity credentials
7070
if filterIdentityCredentials.len() != 0:
7171
if (credential.identityCredential in filterIdentityCredentials) == false:
@@ -74,7 +74,7 @@ proc filterCredential*(credential: MembershipCredentials,
7474
# We filter by membership groups credentials
7575
if filterMembershipContracts.len() != 0:
7676
# Here we keep only groups that match a contract in the filter
77-
var membershipGroupsIntersection: seq[MembershipGroup] = @[]
77+
var membershipGroupsIntersection: seq[MembershipGroup] = @[]
7878
# We check if we have a group in the input credential matching any contract in the filter
7979
for membershipGroup in credential.membershipGroups:
8080
if membershipGroup.membershipContract in filterMembershipContracts:
@@ -87,9 +87,9 @@ proc filterCredential*(credential: MembershipCredentials,
8787

8888
else:
8989
return none(MembershipCredentials)
90-
91-
# We hit this return only if
90+
91+
# We hit this return only if
9292
# - filterIdentityCredentials.len() == 0 and filterMembershipContracts.len() == 0 (no filter)
9393
# - filterIdentityCredentials.len() != 0 and filterMembershipContracts.len() == 0 (filter only on identity credential)
9494
# Indeed, filterMembershipContracts.len() != 0 will have its exclusive return based on all values of membershipGroupsIntersection.len()
95-
return some(credential)
95+
return some(credential)

0 commit comments

Comments
 (0)