From f266e2d1eb419960fab0f73c7cc39a35b9dfb30f Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Wed, 19 Feb 2020 11:22:12 -0800 Subject: [PATCH] version: add CmdName func for future use by logpolicy Signed-off-by: Brad Fitzpatrick Change-Id: I02a7c907844f71242ef06ed097f2a92ece7ae091 --- go.mod | 1 + go.sum | 2 ++ version/cmdname.go | 41 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+) create mode 100644 version/cmdname.go diff --git a/go.mod b/go.mod index a00e0892f..40eddb31d 100644 --- a/go.mod +++ b/go.mod @@ -22,4 +22,5 @@ require ( golang.org/x/sys v0.0.0-20200217220822-9197077df867 gortc.io/stun v1.22.1 honnef.co/go/tools v0.0.1-2019.2.3 // indirect + rsc.io/goversion v1.2.0 ) diff --git a/go.sum b/go.sum index f61395cb7..96d305e83 100644 --- a/go.sum +++ b/go.sum @@ -114,3 +114,5 @@ gortc.io/stun v1.22.1 h1:96mOdDATYRqhYB+TZdenWBg4CzL2Ye5kPyBXQ8KAB+8= gortc.io/stun v1.22.1/go.mod h1:XD5lpONVyjvV3BgOyJFNo0iv6R2oZB4L+weMqxts+zg= honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +rsc.io/goversion v1.2.0 h1:SPn+NLTiAG7w30IRK/DKp1BjvpWabYgxlLp/+kx5J8w= +rsc.io/goversion v1.2.0/go.mod h1:Eih9y/uIBS3ulggl7KNJ09xGSLcuNaLgmvvqa07sgfo= diff --git a/version/cmdname.go b/version/cmdname.go new file mode 100644 index 000000000..450a9e4a2 --- /dev/null +++ b/version/cmdname.go @@ -0,0 +1,41 @@ +// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package version + +import ( + "os" + "path" + "strings" + + "rsc.io/goversion/version" +) + +// CmdName returns either the base name of the current binary +// using os.Executable. If os.Executable fails (it sholdn't), then +// "cmd" is returned. +func CmdName() string { + e, err := os.Executable() + if err != nil { + return "cmd" + } + var ret string + v, err := version.ReadExe(e) + if err != nil { + ret = strings.TrimSuffix(strings.ToLower(e), ".exe") + } else { + // v is like: + // "path\ttailscale.com/cmd/tailscale\nmod\ttailscale.com\t(devel)\t\ndep\tgithub.com/apenwarr/fixconsole\tv0.0.0-20191012055117-5a9f6489cc29\th1:muXWUcay7DDy1/hEQWrYlBy+g0EuwT70sBHg65SeUc4=\ndep\tgithub.... + for _, line := range strings.Split(v.ModuleInfo, "\n") { + if strings.HasPrefix(line, "path\t") { + ret = path.Base(strings.TrimPrefix(line, "path\t")) + break + } + } + } + if ret == "" { + return "cmd" + } + return ret +}