blob: eac95e26301bc2316a404d88439f83da72b26ead [file] [log] [blame]
Abhay Kumara2ae5992025-11-10 14:02:24 +00001// Copied from https://github.com/etcd-io/etcd/blob/main/client/pkg/verify/verify.go
2package common
3
4import (
5 "fmt"
6 "os"
7 "strings"
8)
9
10const ENV_VERIFY = "BBOLT_VERIFY"
11
12type VerificationType string
13
14const (
15 ENV_VERIFY_VALUE_ALL VerificationType = "all"
16 ENV_VERIFY_VALUE_ASSERT VerificationType = "assert"
17)
18
19func getEnvVerify() string {
20 return strings.ToLower(os.Getenv(ENV_VERIFY))
21}
22
23func IsVerificationEnabled(verification VerificationType) bool {
24 env := getEnvVerify()
25 return env == string(ENV_VERIFY_VALUE_ALL) || env == strings.ToLower(string(verification))
26}
27
28// EnableVerifications sets `ENV_VERIFY` and returns a function that
29// can be used to bring the original settings.
30func EnableVerifications(verification VerificationType) func() {
31 previousEnv := getEnvVerify()
32 os.Setenv(ENV_VERIFY, string(verification))
33 return func() {
34 os.Setenv(ENV_VERIFY, previousEnv)
35 }
36}
37
38// EnableAllVerifications enables verification and returns a function
39// that can be used to bring the original settings.
40func EnableAllVerifications() func() {
41 return EnableVerifications(ENV_VERIFY_VALUE_ALL)
42}
43
44// DisableVerifications unsets `ENV_VERIFY` and returns a function that
45// can be used to bring the original settings.
46func DisableVerifications() func() {
47 previousEnv := getEnvVerify()
48 os.Unsetenv(ENV_VERIFY)
49 return func() {
50 os.Setenv(ENV_VERIFY, previousEnv)
51 }
52}
53
54// Verify performs verification if the assertions are enabled.
55// In the default setup running in tests and skipped in the production code.
56func Verify(f func()) {
57 if IsVerificationEnabled(ENV_VERIFY_VALUE_ASSERT) {
58 f()
59 }
60}
61
62// Assert will panic with a given formatted message if the given condition is false.
63func Assert(condition bool, msg string, v ...any) {
64 if !condition {
65 panic(fmt.Sprintf("assertion failed: "+msg, v...))
66 }
67}