code_location.go 839 B

123456789101112131415161718192021222324252627282930313233
  1. package codelocation
  2. import (
  3. "regexp"
  4. "runtime"
  5. "runtime/debug"
  6. "strings"
  7. "github.com/onsi/ginkgo/types"
  8. )
  9. func New(skip int) types.CodeLocation {
  10. _, file, line, _ := runtime.Caller(skip + 1)
  11. stackTrace := PruneStack(string(debug.Stack()), skip)
  12. return types.CodeLocation{FileName: file, LineNumber: line, FullStackTrace: stackTrace}
  13. }
  14. func PruneStack(fullStackTrace string, skip int) string {
  15. stack := strings.Split(fullStackTrace, "\n")
  16. if len(stack) > 2*(skip+1) {
  17. stack = stack[2*(skip+1):]
  18. }
  19. prunedStack := []string{}
  20. re := regexp.MustCompile(`\/ginkgo\/|\/pkg\/testing\/|\/pkg\/runtime\/`)
  21. for i := 0; i < len(stack)/2; i++ {
  22. if !re.Match([]byte(stack[i*2])) {
  23. prunedStack = append(prunedStack, stack[i*2])
  24. prunedStack = append(prunedStack, stack[i*2+1])
  25. }
  26. }
  27. return strings.Join(prunedStack, "\n")
  28. }