Skip to content

Commit

Permalink
extract funcname helper, and add test
Browse files Browse the repository at this point in the history
  • Loading branch information
davecheney committed Jun 8, 2016
1 parent f22595b commit e23d6ed
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
15 changes: 10 additions & 5 deletions stack.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"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;
Expand Down Expand Up @@ -68,10 +68,7 @@ func (f Frame) Format(s fmt.State, verb rune) {
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, ":")
Expand Down Expand Up @@ -107,6 +104,14 @@ func callers() *stack {
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
Expand Down
21 changes: 21 additions & 0 deletions stack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,27 @@ func TestFrameFormat(t *testing.T) {
}
}

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
Expand Down

0 comments on commit e23d6ed

Please sign in to comment.