File: caller.go

package info (click to toggle)
golang-github-chai2010-gettext-go 0.0~git20191225.6b9f4b1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 3,256 kB
  • sloc: makefile: 23
file content (55 lines) | stat: -rw-r--r-- 1,432 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Copyright 2013 ChaiShushan <chaishushan{AT}gmail.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package gettext

import (
	"regexp"
	"runtime"
)

var (
	reInit1 = regexp.MustCompile(`init·\d+$`)  // main.init·1
	reInit2 = regexp.MustCompile(`init\.\d+$`) // main.init.1

	reClosure1 = regexp.MustCompile(`func·\d+$`)                // main.func·001
	reClosure2 = regexp.MustCompile(`glob\.\.func\d+(\.\d+)*$`) // main.glob..func1
	reClosure3 = regexp.MustCompile(`\w+\.func\d+(\.\d+)*$`)    // main.FuncName.func1
)

// caller types:
// runtime.goexit
// runtime.main
// main.init
// main.main
// main.init·1 -> main.init
// main.func·001 -> main.func
// code.google.com/p/gettext-go/gettext.TestCallerName
// ...
func callerName(skip int) string {
	pc, _, _, ok := runtime.Caller(skip)
	if !ok {
		return ""
	}
	name := runtime.FuncForPC(pc).Name()

	if reInit1.MatchString(name) {
		return reInit1.ReplaceAllString(name, "init")
	}
	if reInit2.MatchString(name) {
		return reInit2.ReplaceAllString(name, "init")
	}

	if reClosure1.MatchString(name) {
		return reClosure1.ReplaceAllString(name, "func")
	}
	if reClosure2.MatchString(name) {
		return reClosure2.ReplaceAllString(name, "func")
	}
	if reClosure3.MatchString(name) {
		return regexp.MustCompile(`func\d+(\.\d+)?$`).ReplaceAllString(name, "func") //+ "##"
	}

	return name
}