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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
|
package lib
import (
"fmt"
"os"
"path"
"runtime"
)
// InternalCodingErrorIf is a lookalike for C's __FILE__ and __LINE__ printing,
// with exit 1 if the condition is true.
func InternalCodingErrorIf(condition bool) {
if !condition {
return
}
_, fileName, fileLine, ok := runtime.Caller(1)
if ok {
fmt.Fprintf(
os.Stderr,
"Internal coding error detected at file %s line %d\n",
// Full path preferred but breaks diffs on regression-test actual vs expected
// stderr comparison on expect-fail cases.
path.Base(fileName),
fileLine,
)
} else {
fmt.Fprintf(
os.Stderr,
"Internal coding error detected at file %s line %s\n",
"(unknown)",
"(unknown)",
)
}
// Use this and re-run if you want to get a stack trace to get the
// call-tree that led to the indicated file/line:
if os.Getenv("MLR_PANIC_ON_INTERNAL_ERROR") != "" {
panic("Here is the stack trace")
}
os.Exit(1)
}
// InternalCodingErrorWithMessageIf is a lookalike for C's __FILE__ and
// __LINE__ printing, with exit 1 if the condition is true.
func InternalCodingErrorWithMessageIf(condition bool, message string) {
if !condition {
return
}
_, fileName, fileLine, ok := runtime.Caller(1)
if ok {
fmt.Fprintf(
os.Stderr,
"Internal coding error detected at file %s line %d: %s\n",
path.Base(fileName),
fileLine,
message,
)
} else {
fmt.Fprintf(
os.Stderr,
"Internal coding error detected at file %s line %s: %s\n",
"(unknown)",
"(unknown)",
message,
)
}
// use this and re-run if you want to get a stack trace to get the
// call-tree that led to the indicated file/line:
if os.Getenv("MLR_PANIC_ON_INTERNAL_ERROR") != "" {
panic("Here is the stack trace")
}
os.Exit(1)
}
// InternalCodingErrorPanic is like InternalCodingErrorIf, expect that it
// panics the process (for stack trace, which is usually not desired), and that
// it requires the if-test to be at the caller.
func InternalCodingErrorPanic(message string) {
_, fileName, fileLine, ok := runtime.Caller(1)
if ok {
panic(
fmt.Sprintf(
"Internal coding error detected at file %s line %d: %s\n",
path.Base(fileName),
fileLine,
message,
),
)
} else {
panic(
fmt.Sprintf(
"Internal coding error detected at file %s line %s: %s\n",
"(unknown)",
"(unknown)",
message,
),
)
}
}
// WhereAreWe shows a stack trace from the current callsite.
func WhereAreWe() {
// Start at 1, not 0, since this function itself is not of interest.
for i := 1; i < 20; i++ {
_, fileName, fileLine, ok := runtime.Caller(i)
if !ok {
break
}
fmt.Printf(" %s %d\n", fileName, fileLine)
}
}
|