2021-09-18 17:21:41 +00:00
|
|
|
// Copyright (c) 2018, Drone.IO Inc
|
|
|
|
// Copyright (c) 2021, Robert Kaussow <mail@thegeeklab.de>
|
|
|
|
|
|
|
|
// Use of this source code is governed by an Apache 2.0 license that can be
|
|
|
|
// found in the LICENSE file.
|
2018-03-29 23:04:58 +00:00
|
|
|
|
|
|
|
package template
|
|
|
|
|
|
|
|
import (
|
2020-09-18 17:46:00 +00:00
|
|
|
"fmt"
|
2022-08-05 11:18:35 +00:00
|
|
|
"io"
|
2018-03-29 23:04:58 +00:00
|
|
|
"net/http"
|
|
|
|
"net/url"
|
2022-08-05 11:18:35 +00:00
|
|
|
"os"
|
2018-03-29 23:04:58 +00:00
|
|
|
"strings"
|
|
|
|
|
2021-09-18 15:14:54 +00:00
|
|
|
"github.com/flowchartsman/handlebars/v3"
|
2018-03-29 23:04:58 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Render parses and executes a template, returning the results in string
|
|
|
|
// format. Trailing or leading spaces or new-lines are not getting truncated. It
|
|
|
|
// is able to read templates from remote paths, local files or directly from the
|
|
|
|
// string.
|
|
|
|
func Render(template string, payload interface{}) (s string, err error) {
|
|
|
|
u, err := url.Parse(template)
|
|
|
|
|
|
|
|
if err == nil {
|
|
|
|
switch u.Scheme {
|
|
|
|
case "http", "https":
|
|
|
|
res, err := http.Get(template)
|
|
|
|
if err != nil {
|
2020-09-18 17:46:00 +00:00
|
|
|
return s, fmt.Errorf("failed to fetch: %w", err)
|
2018-03-29 23:04:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
defer res.Body.Close()
|
|
|
|
|
2022-08-05 11:18:35 +00:00
|
|
|
out, err := io.ReadAll(res.Body)
|
2018-03-29 23:04:58 +00:00
|
|
|
if err != nil {
|
2020-09-18 17:46:00 +00:00
|
|
|
return s, fmt.Errorf("failed to read: %w", err)
|
2018-03-29 23:04:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
template = string(out)
|
|
|
|
case "file":
|
2022-08-05 11:18:35 +00:00
|
|
|
out, err := os.ReadFile(u.Path)
|
2018-03-29 23:04:58 +00:00
|
|
|
if err != nil {
|
2020-09-18 17:46:00 +00:00
|
|
|
return s, fmt.Errorf("failed to read: %w", err)
|
2018-03-29 23:04:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
template = string(out)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-18 15:14:54 +00:00
|
|
|
return handlebars.Render(template, payload)
|
2018-03-29 23:04:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// RenderTrim parses and executes a template, returning the results in string
|
|
|
|
// format. The result is trimmed to remove left and right padding and newlines
|
|
|
|
// that may be added unintentially in the template markup.
|
|
|
|
func RenderTrim(template string, playload interface{}) (string, error) {
|
|
|
|
out, err := Render(template, playload)
|
|
|
|
return strings.Trim(out, " \n"), err
|
|
|
|
}
|