-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: move templating functions to another file
- Loading branch information
Tomasz Gągor
committed
Dec 19, 2024
1 parent
aa4581c
commit b9239e6
Showing
2 changed files
with
42 additions
and
34 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
package parser | ||
|
||
import ( | ||
"bytes" | ||
"os" | ||
"path/filepath" | ||
"text/template" | ||
|
||
"github.com/Masterminds/sprig/v3" | ||
"github.com/rs/zerolog/log" | ||
) | ||
|
||
func templateString(pattern string, args map[string]interface{}) (string, error) { | ||
var output bytes.Buffer | ||
t := template.Must(template.New(pattern).Funcs(sprig.TxtFuncMap()).Parse(pattern)) | ||
if err := t.Execute(&output, args); err != nil { | ||
return "", err | ||
} | ||
|
||
return output.String(), nil | ||
} | ||
|
||
func templateFile(templateFile string, destinationFile string, args map[string]interface{}) error { | ||
t := template.Must( | ||
template.New(filepath.Base(templateFile)).Funcs(sprig.TxtFuncMap()).ParseFiles(templateFile), | ||
) | ||
|
||
f, err := os.Create(destinationFile) | ||
if err != nil { | ||
log.Error().Err(err).Str("file", templateFile).Msg("Failed to create") | ||
return err | ||
} | ||
defer f.Close() | ||
|
||
// Render templates using variables | ||
if err := t.Execute(f, args); err != nil { | ||
log.Error().Err(err).Str("file", templateFile).Msg("Failed to template") | ||
return err | ||
} | ||
|
||
return nil | ||
} |