File: util.go

package info (click to toggle)
golang-github-powerman-check 1.8.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 276 kB
  • sloc: sh: 15; makefile: 2
file content (64 lines) | stat: -rw-r--r-- 1,395 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
56
57
58
59
60
61
62
63
64
package check

import (
	"fmt"
	"math"
	"path/filepath"
	"reflect"
	"runtime"
	"strings"
)

func callerTestFileLines() (file string, line int, funcLine int) {
	pc, file, line, ok := runtime.Caller(0)
	myfile := file
	for stack := 1; ok && samePackage(myfile, file); stack++ {
		pc, file, line, ok = runtime.Caller(stack)
	}
	if f := runtime.FuncForPC(pc); f != nil {
		_, funcLine = f.FileLine(f.Entry())
	}
	return file, line, funcLine
}

func samePackage(basefile, file string) bool {
	return filepath.Dir(basefile) == filepath.Dir(file) && !strings.HasSuffix(file, "_test.go")
}

func callerFuncName(stack int) string {
	pc, _, _, _ := runtime.Caller(stack + 1)
	return strings.TrimPrefix(funcNameAt(pc), "(*C).")
}

func funcName(f any) string {
	return funcNameAt(reflect.ValueOf(f).Pointer())
}

func funcNameAt(pc uintptr) string {
	name := "<unknown>"
	if f := runtime.FuncForPC(pc); f != nil {
		name = f.Name()
		if i := strings.LastIndex(name, "/"); i != -1 {
			name = name[i+1:]
		}
		if i := strings.Index(name, "."); i != -1 {
			name = name[i+1:]
		}
	}
	return name
}

func format(msg ...any) string {
	if len(msg) > 1 {
		return fmt.Sprintf(msg[0].(string), msg[1:]...)
	}
	return fmt.Sprint(msg...)
}

// digits return amount of decimal digits in number.
func digits(number int) int {
	if number == 0 {
		return 1
	}
	return int(math.Floor(math.Log10(float64(number)) + 1))
}