caller.go 887 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gettext
  5. import (
  6. "regexp"
  7. "runtime"
  8. )
  9. var (
  10. reInit = regexp.MustCompile(`init·\d+$`) // main.init·1
  11. reClosure = regexp.MustCompile(`func·\d+$`) // main.func·001
  12. )
  13. // caller types:
  14. // runtime.goexit
  15. // runtime.main
  16. // main.init
  17. // main.main
  18. // main.init·1 -> main.init
  19. // main.func·001 -> main.func
  20. // code.google.com/p/gettext-go/gettext.TestCallerName
  21. // ...
  22. func callerName(skip int) string {
  23. pc, _, _, ok := runtime.Caller(skip)
  24. if !ok {
  25. return ""
  26. }
  27. name := runtime.FuncForPC(pc).Name()
  28. if reInit.MatchString(name) {
  29. return reInit.ReplaceAllString(name, "init")
  30. }
  31. if reClosure.MatchString(name) {
  32. return reClosure.ReplaceAllString(name, "func")
  33. }
  34. return name
  35. }