doutang7383 2015-07-22 15:35
浏览 56
已采纳

如何在运行时的给定调用中找到包名称?

For logging purpose I want to write a function which will print a package name. I can do it for a directory name:

// file is the full file name
// 4 - how many calls we want to go up in a stack trace.
_, file, line, ok := runtime.Caller(4) 

... but can't find a way for package name (package name can be different from directory name).

  • 写回答

1条回答 默认 最新

  • dongshuo6503 2015-07-25 12:35
    关注

    I came across a similar problem - from a package path how do you get the package name. The best solution I found is to exec the "go list" command. Not ideal but I came up blank elsewhere.

    In my case I also had a problem that sometimes the package is an empty directory. With no source files, "go list" throws an error, so I added a function to create a sensible package name from the path.

    Here's the code:

    func getPackageName(path string) string {
        output, err := exec.Command("go", "list", "-f", "{{.Name}}", path).CombinedOutput()
        if err != nil {
            return guessPackageName(path)
        }
        return strings.TrimSpace(string(output))
    }
    
    func guessPackageName(path string) string {
        preferred := path
        if strings.HasSuffix(preferred, "/") {
            // training slashes are usually tolerated, so we can get rid of one if it exists
            preferred = preferred[:len(preferred)-1]
        }
        if strings.Contains(preferred, "/") {
            // if the path contains a "/", use the last part
            preferred = preferred[strings.LastIndex(preferred, "/")+1:]
        }
        if strings.Contains(preferred, "-") {
            // the name usually follows a hyphen - e.g. github.com/foo/go-bar
            // if the package name contains a "-", use the last part
            preferred = preferred[strings.LastIndex(preferred, "-")+1:]
        }
        if strings.Contains(preferred, ".") {
            // dot is commonly usually used as a version - e.g. github.com/foo/bar.v1
            // if the package name contains a ".", use the first part
            preferred = preferred[:strings.LastIndex(preferred, ".")]
        }
        return preferred
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何实验stm32主通道和互补通道独立输出
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题