extract funcname helper, and add test
diff --git a/stack.go b/stack.go
index c6f46b9..89c5784 100644
--- a/stack.go
+++ b/stack.go
@@ -8,7 +8,7 @@
"strings"
)
-// Frame represents an activation record.
+// Frame represents a program counter inside a stack frame.
type Frame uintptr
// pc returns the program counter for this frame;
@@ -68,10 +68,7 @@
fmt.Fprintf(s, "%d", f.line())
case 'n':
name := runtime.FuncForPC(f.pc()).Name()
- i := strings.LastIndex(name, "/")
- name = name[i+1:]
- i = strings.Index(name, ".")
- io.WriteString(s, name[i+1:])
+ io.WriteString(s, funcname(name))
case 'v':
f.Format(s, 's')
io.WriteString(s, ":")
@@ -107,6 +104,14 @@
return &st
}
+// funcname removes the path prefix component of a function's name reported by func.Name().
+func funcname(name string) string {
+ i := strings.LastIndex(name, "/")
+ name = name[i+1:]
+ i = strings.Index(name, ".")
+ return name[i+1:]
+}
+
func trimGOPATH(name, file string) string {
// Here we want to get the source file path relative to the compile time
// GOPATH. As of Go 1.6.x there is no direct way to know the compiled
diff --git a/stack_test.go b/stack_test.go
index c9a4d4c..d01b55d 100644
--- a/stack_test.go
+++ b/stack_test.go
@@ -141,6 +141,27 @@
}
}
+func TestFuncname(t *testing.T) {
+ tests := []struct {
+ name, want string
+ }{
+ {"", ""},
+ {"runtime.main", "main"},
+ {"github.com/pkg/errors.funcname", "funcname"},
+ {"funcname", "funcname"},
+ {"io.copyBuffer", "copyBuffer"},
+ {"main.(*R).Write", "(*R).Write"},
+ }
+
+ for _, tt := range tests {
+ got := funcname(tt.name)
+ want := tt.want
+ if got != want {
+ t.Errorf("funcname(%q): want: %q, got %q", tt.name, want, got)
+ }
+ }
+}
+
func TestTrimGOPATH(t *testing.T) {
var tests = []struct {
Frame