Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add two template functions #712

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 31 additions & 3 deletions internal/hook/hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ import (
"errors"
"fmt"
"hash"
"io/ioutil"
"log"
"math"
"net"
"net/textproto"
"os"
"path"
"reflect"
"regexp"
"strconv"
Expand Down Expand Up @@ -750,14 +750,18 @@ func (h *Hooks) LoadFromFile(path string, asTemplate bool) error {
}

// parse hook file for hooks
file, e := ioutil.ReadFile(path)
file, e := os.ReadFile(path)

if e != nil {
return e
}

if asTemplate {
funcMap := template.FuncMap{"getenv": getenv}
funcMap := template.FuncMap{
"cat": cat,
"credential": credential,
"getenv": getenv,
}

tmpl, err := template.New("hooks").Funcs(funcMap).Parse(string(file))
if err != nil {
Expand Down Expand Up @@ -956,3 +960,27 @@ func compare(a, b string) bool {
func getenv(s string) string {
return os.Getenv(s)
}

// cat provides a template function to retrieve content of files
// Similarly to getenv, if no file is found, it returns the empty string
func cat(s string) string {
data, e := os.ReadFile(s)

if e != nil {
return ""
}

return string(data)
}

// credential provides a template function to retreive secrets using systemd's LoadCredential mechanism
func credential(s string) string {
dir := getenv("CREDENTIALS_DIRECTORY")

// If no credential directory is found, fallback to the env variable
if dir == "" {
return getenv(s)
}

return cat(path.Join(dir, s))
}