From 2ea79134e6c14099af7481ba22a6be5f5b5835c8 Mon Sep 17 00:00:00 2001 From: wangzhngyang <> Date: Fri, 3 Jan 2020 16:45:49 +0800 Subject: [PATCH] =?UTF-8?q?1=E5=88=A0=E9=99=A4vendor=E6=B7=BB=E5=8A=A0go?= =?UTF-8?q?=20mod=202=E9=85=8D=E7=BD=AE=E6=96=87=E4=BB=B6=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E7=8E=AF=E5=A2=83=E5=8F=98=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 10 ++++++++++ go.mod | 17 +++++++++++++++++ hook/hook.go | 29 ++++++++++++++++++++++++++++- 3 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 go.mod diff --git a/README.md b/README.md index 23f00f4..7f8aa78 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,16 @@ Our `hooks.json` file will now look like this: } ] ``` +添加对环境变量的支持 +```json +[ + { + "id": "redeploy-webhook", + "execute-command": "${PATH}/redeploy.sh", + "command-working-directory": "/var/webhook" + } +] +``` You can now run [webhook][w] using ```bash diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..dafae82 --- /dev/null +++ b/go.mod @@ -0,0 +1,17 @@ +module github.com/adnanh/webhook + +go 1.13 + +require ( + github.com/codegangsta/negroni v0.2.1-0.20171009163950-5bc66cf1ad89 + github.com/fsnotify/fsnotify v1.4.7 // indirect + github.com/ghodss/yaml v1.0.0 + github.com/gorilla/context v1.1.1 // indirect + github.com/gorilla/mux v1.5.1-0.20171008214913-bdd5a5a1b0b4 + github.com/kr/pretty v0.2.0 // indirect + github.com/satori/go.uuid v1.1.1-0.20170321230731-5bf94b69c6b6 + golang.org/x/sys v0.0.0-20200102141924-c96a22e43c9c // indirect + gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect + gopkg.in/fsnotify.v1 v1.4.2 + gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7 // indirect +) diff --git a/hook/hook.go b/hook/hook.go index 72acb01..e9f8562 100644 --- a/hook/hook.go +++ b/hook/hook.go @@ -648,10 +648,37 @@ func (h *Hooks) LoadFromFile(path string, asTemplate bool) error { file = buf.Bytes() } - e = yaml.Unmarshal(file, h) + f, err := h.ReplaceEnv(string(file)) + if err != nil { + return err + } + + e = yaml.Unmarshal([]byte(f), h) return e } +// ReplaceEnv replace env +func (h *Hooks) ReplaceEnv(str string) (string, error) { + expr := `\${[A-Za-z_]*}` + r, err := regexp.Compile(expr) + if err != nil { + return "", fmt.Errorf("regexp.Compile error: %w", err) + } + if r == nil { + return "", fmt.Errorf("r is nil") + } + all := r.FindAll([]byte(str), -1) + for _, v := range all { + envStr := string(v) + env := os.Getenv(envStr[2 : len(envStr)-1]) + if env == "" { + return "", errors.New("get env failed:" + envStr) + } + str = strings.ReplaceAll(str, envStr, env) + } + return str, nil +} + // Append appends hooks unless the new hooks contain a hook with an ID that already exists func (h *Hooks) Append(other *Hooks) error { for _, hook := range *other {