| Abhay Kumar | a2ae599 | 2025-11-10 14:02:24 +0000 | [diff] [blame^] | 1 | // Copied from https://github.com/etcd-io/etcd/blob/main/client/pkg/verify/verify.go |
| 2 | package common |
| 3 | |
| 4 | import ( |
| 5 | "fmt" |
| 6 | "os" |
| 7 | "strings" |
| 8 | ) |
| 9 | |
| 10 | const ENV_VERIFY = "BBOLT_VERIFY" |
| 11 | |
| 12 | type VerificationType string |
| 13 | |
| 14 | const ( |
| 15 | ENV_VERIFY_VALUE_ALL VerificationType = "all" |
| 16 | ENV_VERIFY_VALUE_ASSERT VerificationType = "assert" |
| 17 | ) |
| 18 | |
| 19 | func getEnvVerify() string { |
| 20 | return strings.ToLower(os.Getenv(ENV_VERIFY)) |
| 21 | } |
| 22 | |
| 23 | func 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. |
| 30 | func 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. |
| 40 | func 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. |
| 46 | func 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. |
| 56 | func 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. |
| 63 | func Assert(condition bool, msg string, v ...any) { |
| 64 | if !condition { |
| 65 | panic(fmt.Sprintf("assertion failed: "+msg, v...)) |
| 66 | } |
| 67 | } |