Debian Codegraph @

internal/debug/assert.go

raw
1 package debug
2
3 import (
4 "fmt"
5 "os"
6 )
7
8 const (
9 envAssertPanic = "GO_PROMPT_ENABLE_ASSERT"
10 )
11
12 var (
13 enableAssert bool
14 )
15
16 func init() {
17 if e := os.Getenv(envAssertPanic); e == "true" || e == "1" {
18 enableAssert = true
19 }
20 }
21
22 // Assert ensures expected condition.
23 func Assert(cond bool, msg interface{}) {
24 if cond {
25 return
26 }
27 if enableAssert {
28 panic(msg)
29 }
30 writeWithSync(2, "[ASSERT] "+toString(msg))
31 }
32
33 func toString(v interface{}) string {
34 switch a := v.(type) {
35 case func() string:
36 return a()
37 case string:
38 return a
39 case fmt.Stringer:
40 return a.String()
41 default:
42 return fmt.Sprintf("unexpected type, %t", v)
43 }
44 }
45
46 // AssertNoError ensures err is nil.
47 func AssertNoError(err error) {
48 if err == nil {
49 return
50 }
51 if enableAssert {
52 panic(err)
53 }
54 writeWithSync(2, "[ASSERT] "+err.Error())
55 }