File: assert.go

package info (click to toggle)
golang-github-c-bata-go-prompt 0.2.5-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 396 kB
  • sloc: makefile: 37; python: 13; sh: 9
file content (55 lines) | stat: -rw-r--r-- 815 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package debug

import (
	"fmt"
	"os"
)

const (
	envAssertPanic = "GO_PROMPT_ENABLE_ASSERT"
)

var (
	enableAssert bool
)

func init() {
	if e := os.Getenv(envAssertPanic); e == "true" || e == "1" {
		enableAssert = true
	}
}

// Assert ensures expected condition.
func Assert(cond bool, msg interface{}) {
	if cond {
		return
	}
	if enableAssert {
		panic(msg)
	}
	writeWithSync(2, "[ASSERT] "+toString(msg))
}

func toString(v interface{}) string {
	switch a := v.(type) {
	case func() string:
		return a()
	case string:
		return a
	case fmt.Stringer:
		return a.String()
	default:
		return fmt.Sprintf("unexpected type, %t", v)
	}
}

// AssertNoError ensures err is nil.
func AssertNoError(err error) {
	if err == nil {
		return
	}
	if enableAssert {
		panic(err)
	}
	writeWithSync(2, "[ASSERT] "+err.Error())
}