etcd学习笔记1

今天看etcd代码时发现打印版本信息的代码,追踪发现其中的GitSHA是通过编译传进来的值。

 26 var (
 27     // MinClusterVersion is the min cluster version this etcd binary is compatible with.
 28     MinClusterVersion = "3.0.0"
 29     Version           = "3.5.0-pre"
 30     APIVersion        = "unknown"
 31
 32     // Git SHA Value will be set during build
 33     GitSHA = "Not provided (use ./build instead of go build)"
 34 )

执行结果如下所示:

(ENV) 🍺 /Users/xsky/go/src/github.com/etcd-io/etcd ☞ git:(test) ✗ ./bin/etcd --version
etcd Version: 3.5.0-pre
Git SHA: 9b6c3e337
Go Version: go1.14.3
Go OS/Arch: darwin/amd64

在编译时使用参数-ldflags -X importpath.name=value

-X importpath.name=value
Set the value of the string variable in importpath named name to value.
This is only effective if the variable is declared in the source code either uninitialized
or initialized to a constant string expression. -X will not work if the initializer makes
a function call or refers to other variables.
Note that before Go 1.5 this option took two separate arguments.

使用如下:

  7 GIT_SHA=$(git rev-parse --short HEAD || echo "GitNotFound")
  8 if [[ -n "$FAILPOINTS" ]]; then
  9     GIT_SHA="$GIT_SHA"-FAILPOINTS
 10 fi
 11
 12 # Set GO_LDFLAGS="-s" for building without symbols for debugging.
 13 GO_LDFLAGS="$GO_LDFLAGS -X ${REPO_PATH}/version.GitSHA=${GIT_SHA}"
.....
 78     for tool in ${tools_path}
 79     do
 80         echo "Building" "'${tool}'"...
 81         # shellcheck disable=SC2086
 82         CGO_ENABLED=0 go build ${GO_BUILD_FLAGS} \
 83           -installsuffix cgo \
 84           -ldflags "${GO_LDFLAGS}" \
 85           -o "${out}/${tool}" "${REPO_PATH}/${tool}" || return
 86     done

顺便发现一个小bug:https://github.com/etcd-io/etcd/issues/11958

References


发表评论

电子邮件地址不会被公开。 必填项已用*标注