Skip to content
This repository was archived by the owner on Dec 1, 2021. It is now read-only.

Commit e23d6ed

Browse files
committed
extract funcname helper, and add test
1 parent f22595b commit e23d6ed

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

stack.go

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import (
88
"strings"
99
)
1010

11-
// Frame represents an activation record.
11+
// Frame represents a program counter inside a stack frame.
1212
type Frame uintptr
1313

1414
// pc returns the program counter for this frame;
@@ -68,10 +68,7 @@ func (f Frame) Format(s fmt.State, verb rune) {
6868
fmt.Fprintf(s, "%d", f.line())
6969
case 'n':
7070
name := runtime.FuncForPC(f.pc()).Name()
71-
i := strings.LastIndex(name, "/")
72-
name = name[i+1:]
73-
i = strings.Index(name, ".")
74-
io.WriteString(s, name[i+1:])
71+
io.WriteString(s, funcname(name))
7572
case 'v':
7673
f.Format(s, 's')
7774
io.WriteString(s, ":")
@@ -107,6 +104,14 @@ func callers() *stack {
107104
return &st
108105
}
109106

107+
// funcname removes the path prefix component of a function's name reported by func.Name().
108+
func funcname(name string) string {
109+
i := strings.LastIndex(name, "/")
110+
name = name[i+1:]
111+
i = strings.Index(name, ".")
112+
return name[i+1:]
113+
}
114+
110115
func trimGOPATH(name, file string) string {
111116
// Here we want to get the source file path relative to the compile time
112117
// GOPATH. As of Go 1.6.x there is no direct way to know the compiled

stack_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,27 @@ func TestFrameFormat(t *testing.T) {
141141
}
142142
}
143143

144+
func TestFuncname(t *testing.T) {
145+
tests := []struct {
146+
name, want string
147+
}{
148+
{"", ""},
149+
{"runtime.main", "main"},
150+
{"github.com/pkg/errors.funcname", "funcname"},
151+
{"funcname", "funcname"},
152+
{"io.copyBuffer", "copyBuffer"},
153+
{"main.(*R).Write", "(*R).Write"},
154+
}
155+
156+
for _, tt := range tests {
157+
got := funcname(tt.name)
158+
want := tt.want
159+
if got != want {
160+
t.Errorf("funcname(%q): want: %q, got %q", tt.name, want, got)
161+
}
162+
}
163+
}
164+
144165
func TestTrimGOPATH(t *testing.T) {
145166
var tests = []struct {
146167
Frame

0 commit comments

Comments
 (0)