Skip to content

Latest commit

 

History

History
1940 lines (1204 loc) · 46.2 KB

README.md

File metadata and controls

1940 lines (1204 loc) · 46.2 KB

Goplater Logo

Goplater

Go templates with superpowers

Read files, call APIs, parse JSON, YAML and Markdown and write your own template functions

See it in action

example terminal output of Goplater

TEMPLATE.md

+{{- $app := jsonDecode (readRaw "./package.json") -}}

# +{{ upper (index $app "name") }}

Version: +{{ index $app "version" }}

+{{ read "./install.md" }}
goplater template TEMPLATE.md -o README.md

README.md

# MY-APP

Version: 1.2.3

## Install

Run `npm install my-app`

This very README is generated with Goplater.

Contents

Need help? Come join our Matrix Server!

Why Goplater?

  • Familiar. It is Go's text/template syntax. If you know it, you already know Goplater.
  • Easy debugging. See what's wrong and where, with clear errors and helpful context.
  • Batteries included. Read and write files, fetch URLs, work with JSON, YAML, HTML and Markdown, run regex and string operations. See the Standard Library.
  • Write your own functions, inside the template. Define them with define, call them with call. Arguments and return values included.
  • Share and import functions. Put your functions in a file, import them from disk or from a URL and reuse them everywhere.
  • Not just a CLI. The engine behind it, gplt, is a separate library you can embed in your own Go program.
  • Modular. The library is split into independent modules. Load only what you need. Or let the CLI load them all.
  • Automated. Use the GitHub Action and Bot to render templates and automate pull requests. See Automation.

Getting Started

Install with Go:

go install github.com/codeshelldev/goplater@latest

Or download the latest binary from the Releases page, make it executable with chmod +x goplater and run it.

Template your first file:

goplater template examples/app-readme/template.md -o README.md

This creates README.md in your current working directory.

Usage

Templating files

Goplater uses Go's built-in templating library, with actions written as +{{ ... }}. Files that already contain plain {{ }} (Helm charts, GitHub Actions, Mustache) pass through untouched.

File Content: +{{ read "./myfile.txt" }}

Whole folders

Point Goplater at a directory and it mirrors the structure into the output:

goplater template ./examples -o ./out -r

Useful flags:

Flag What it does
-o Output file or directory
-s Source directory for ~/ paths
-r Walk directories
--match Only template files matching a regex
--flatten Drop the directory structure
--root Choose the root that output paths are relative to
--allowed-inputs Limit from where templates may read
--allowed-outputs Limit where templates may write
--trim-max-blank-lines Experimental: Remove blank lines left behind by non-output actions
--dry-run Show what would be written, change nothing
--ignore-errors Continue processing when errors occur

Your own functions

Define a function in the template and call it:

+{{ define "greet(name, surname?)" }}
    +{{ $name := .name }}
    +{{ if .surname }}
        +{{ $name = concat .name " " .surname }}
    +{{ end }}
    +{{ return (printf "Hello, %s!" $name) }}
+{{ end }}

+{{ call "greet" "Gopher" }}
+{{ call "greet" "John" "Doe" }}

Output:

Hello, Gopher!
Hello, John Doe!

The define name is the function signature. Parameters are available as .name inside the function:

  • name is required
  • name? is optional (nil if not given)
  • ...name collects all remaining arguments into a slice

Optional and variadic parameters must come last. A define without a signature (e.g. define "test") is a plain template and can't be called with call.

Prefer Go? Register custom Go functions as well.

Share functions

Keep your functions in one file and import them from the filesystem or from a URL:

+{{ import "funcs" "https://raw.githubusercontent.com/CodeShellDev/goplater/refs/heads/main/examples/funcs" }}
+{{ call "funcs.greet" "John" }}

Pin remote imports to a tag or a commit and treat them like any other dependency: imported functions run inside your template.

Reading errors

When a template fails, Goplater shows what went wrong and where.

example terminal output of an error

Every error comes with:

Part What it shows
Location File, line and column where it happened
Context The failing line and the lines around it
Pointer ^ under the exact expression that failed
Message What went wrong, like an undefined variable or a bad type

Errors in imported files or called functions point to the file that holds the failing code.

Goplater stops at the first error. Use --ignore-errors to report it and keep going with the remaining files.

Use the engine instead

gplt, Goplater's underlying templating engine, is not tied to the CLI. Load the modules you want and embed templating in your own Go application. Browse the packages on pkg.go.dev.

Automate with GitHub Actions

Use Goplater in your CI/CD workflows to generate files automatically.

  • Goplater GitHub Action: render templates directly in your GitHub Actions workflows.
  • Goplater Bot: automate file generation in a repository and have the results submitted as a pull request or pushed as a commit.

We use Goplater Bot as well, check him out PR #20!

Standard Library

The gplt engine includes a large and growing selection of built-in functions for use in your templates. Every module is independent, load all of them or only the ones you need.

Goplater ships with all implemented modules in addition to fs-specific and cli dependent functions.

Module Use it for
fs Reading, writing and walking files and directories
outputto Choosing the output path from inside a template
strings, regex Trimming, splitting, replacing, matching
json, yaml Decoding and encoding structured data
html, markdown Querying and editing documents
http Fetching remote resources
math Operators and number helpers
container Maps and slices
base64, conversion Encoding and type conversion
import, return, globals Sharing functions and passing values around
debug Printing while you develop

Need something that is not there? Add your own with a custom module or your own Goplater function file and share it.

read(path string) (string, throws error)

Reads and templates file.

Examples

Example:

+{{ read "/path/to/file" }}

readRaw(path string) (string, throws error)

Reads file (without templating).

Examples

Example:

+{{ readRaw "/path/to/file" }}

readArgs(path string, args any) (string, throws error)

Reads file and passes arguments to it. Arguments are available as .arg in the file being read.

Examples

Example:

+{{ readArgs "/path/to/file" (list "my" "args") }}

write(path string, content string) throws error

Writes to a file path.

Examples

Example:

+{{ write "/path/to/file" "Hello" }}

mkdir(path string) throws error

Creates directory at path.

Examples

Example:

+{{ mkdir "/path/to/somewhere/" }}

appendFile(path string, content string) throws error

Appends to an existing file.

Examples

Example:

+{{ appendFile "/path/to/somewhere/" "Goodbye" }}

fsExists(path string) bool

Returns if a file or folder exists at a given path.

Examples

Example:

+{{ if (fsExists "/path/to/somewhere") }}
Path exists!
+{{ end }}

isFile(path string) bool

Returns if a file exists at a given path.

Examples

Example:

+{{ if (isFile "/path/to/file") }}
Path is a file!
+{{ end }}

isDir(path string) bool

Returns if a folder exists at a given path.

Examples

Example:

+{{ if (isDir "/path/to/somewhere") }}
Path is a folder!
+{{ end }}

listDir(path string) ([]string, throws error)

Returns all files and folders inside of a given directory.

Examples

Example:

+{{ join ", " (listDir "/path/to") }}

Output:

/path/to/file1.txt, /path/to/file2.txt, /path/to/folder

walkDir(path string) ([]string, throws error)

Returns all files and folders recursively under a given directory.

Examples

Example:

+{{ join ", " (walkDir "/path/to") }}

Output:

/path/to/file1.txt, /path/to/file2.txt, /path/to/folder, /path/to/folder/file3.txt

fsRemove(path string) throws error

Removes a file or folder at a given path.

Examples

Example:

+{{ fsRemove "/path/to/file/or/folder" }}

joinPath(paths []string) string

Joins paths together.

basePath(path string) string

Returns the last element of a path.

pathDir(path string) string

Returns all but the last element of a path.

fileExt(path string) string

Returns the file name extension of a file path.

absPath(path string) (string, throws error)

Returns an absolute representation of a given path. If the path is not absolute it will be joined with the current working directory to turn it into an absolute path.

relPath(basePath string, targetPath string) (string, throws error)

Returns a relative path that is lexically equivalent to targetPath when joined to basePath with an intervening separator. The returned path will always be relative to basePath, even if basePath and targetPath share no elements.

outputTo(path string) throws error

Changes the output path for the current file. Errors if path is not allowed.

call(name string, args []any) (any, throws error)

Calls a func by name with args, optionally with a namespace handle. Fails if func is not accessible, undefined or has no signature.

Args are bound to the params of the func signature:

  • name: required, call fails if missing
  • name?: optional (end only), nil if not given
  • ...name: variadic (last only), a slice of all remaining args

Too many args fail unless the last param is variadic.

Result:

  • return not called (or called with no values): captured template output
  • return with one value: that value
  • return with multiple values: a slice of all values
Examples

Example:

+{{ define "greet(name)" }}
+{{ echo (printf "Hello %s!" .name) }}
+{{ end }}

Output:

Hello John!

Example:

+{{ define "greet(name)" }}
Hello +{{ .name }}!
+{{ end }}

Output:

Hello John!

Example:

+{{ define "greet(name)" }}
+{{ return (printf "Hello %s!" .name) }}
+{{ end }}

Output:

Hello John!

globalSet(key string, value any) throws error

Defines a global value with a key.

globalGet(key string) (any, throws error)

Tries to retrieve a global value with a key.

globalHas(key string) bool

Returns whether a given global variable exists.

import(alias string?, path string) throws error

Tries to import a template file with func definitions. Optionally supply an alias for easier access.

The fs resolver is only available as an internal module and does not ship with gplt.

Examples

Example:

+{{ import "https://domain.com/functions" }}

Output:

+{{ call "functions.greet" "John" }}

Example:

+{{ import "funcs" "https://domain.com/functions" }}

Output:

+{{ call "funcs.greet" "John" }}

importExact(alias string?, path string, hash string?) throws error

Same import, but only imports if content matches expected SHA-256 hash.

Examples

Example:

+{{ importExact "funcs" "https://domain.com/functions" "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" }}

Output:

+{{ call "funcs.greet" "John" }}

return(values []any?)

Sets output value(s).

Examples

Example:

+{{ return "a" "b" 1 2 }}
+{{ return (list "3" "4" "5") }}

getOutputs() []any

Returns current outputs.

typeOf(value any) (string, throws error)

Returns the type of a value as a string (using reflect.TypeOf).

isType(value any, typeName string) bool

Reports whether value is of type (using reflect.TypeOf).

htmlDecode(html string) (*goquery.Document, throws error)

Decodes html into a document.

htmlDocFindAll(doc *goquery.Document, selector string) ([]*goquery.Selection, throws error)

Finds elements in document by selector (using goquery.Find).

htmlDocFind(doc *goquery.Document, selector string) (*goquery.Selection, throws error)

Finds element in document by selector (using goquery.Find).

htmlFindAll(doc *goquery.Document, selector string) ([]*goquery.Selection, throws error)

Finds elements in element by selector (using goquery.Find).

htmlFind(doc *goquery.Document, selector string) (*goquery.Selection, throws error)

Finds element in element by selector (using goquery.Find).

htmlText(el *goquery.Selection) string

Returns the elements text content.

htmlAttr(el *goquery.Selection, attr string) string

Returns an elements attribute content.

htmlInner(el *goquery.Selection) string

Returns the elements inner html.

markdownDecode(md string) *Document

Decodes markdown into a document.

markdownEncode(doc *Document) string

Encodes a document into markdown.

markdownFindAll(target Searchable, selector string) []*Node

Finds elements in target by selector (using custom).

markdownFind(target Searchable, selector string) *Node

Finds element in target by selector (using custom).

markdownIs(node *Node, selector string) bool

Returns whether node matches selector (using custom).

markdownHTML(doc *Document) (string, throws error)

Returns html markdown representation.

markdownText(node *Node) string

Returns all raw markdown text in a node recursively.

markdownHeadings(doc *Document) []*Heading

Returns all markdown headings.

markdownLinks(doc *Document) []*Link

Returns all markdown links.

markdownLinkURL(link *Link) string

Returns the url of a markdown link node.

markdownLinkSetURL(link *Link, url string)

Sets a link node's url.

markdownLinkSetTitle(link *Link, title string)

Sets a link node's title.

markdownLinkText(link *Link) string

Returns the text of a markdown link node.

markdownImages(doc *Document) []*Image

Returns all markdown images.

markdownImageURL(image *Image) string

Returns the url of a markdown image node.

markdownImageSetURL(image *Image, url string)

Sets a image node's url.

markdownImageSetAlt(image *Image, alt string)

Sets a image node's alt.

markdownParagraphs(doc *Document) []*Paragraph

Returns all markdown paragraphs.

markdownCodeBlocks(doc *Document) []*CodeBlock

Returns all markdown code blocks.

markdownBlockquotes(doc *Document) []*Blockquote

Returns all markdown block quotes.

markdownRemove(node *Node)

Removes a markdown node.

markdownAppend(doc *Document, str string)

Appends text to a markdown document.

markdownPrepend(doc *Document, str string)

Prepends text to a markdown document.

yamlEncode(obj any) (string, throws error)

Encodes an object into a yaml string.

yamlDecode(yaml string) (any, throws error)

Decodes a yaml string into an object.

delete(container map|slice, key any) (any, throws error)

Deletes a container entry with the given key (mutates maps, but must return modified slice).

Examples

Example:

+{{ $slice := list "Apple" "Banana" }}
+{{ $newSlice := delete $slice 0 }}
+{{ echo $newSlice }}

Output:

[Banana]

Example:

+{{ $map := dict "key1" "value1" "key2" "value2" }}
+{{ delete $map "key1" }}
+{{ echo $map }}

Output:

map[key2:value2]

set(container map|slice, key any, value any) throws error

Set a container entry value with the given key.

Examples

Example:

+{{ $slice := list "Apple" "Banana" }}
+{{ set $slice 0 "Strawberry" }}
+{{ echo $slice }}

Output:

[Strawberry Banana]

hasKey(container map|slice, key any) (bool, throws error)

Returns if an entry with the given key exists in container.

Examples

Example:

+{{ if (hasKey (list "version" "v1") "version") }}
Container has "version"!
+{{ end }}

includes(container map|slice, value any) (bool, throws error)

Returns if an entry with the given value exists in container.

Examples

Example:

+{{ if (includes (list "version" "v1") "v1") }}
Container includes "v1"!
+{{ end }}

append(container []any, value any) []any

Appends a value to a slice (returns a new copy).

Examples

Example:

+{{ $slice := list "Apple" "Banana" }}
+{{ $newSlice = append $slice "Strawberry" }}
+{{ echo $newSlice }}

Output:

[Apple Banana Strawberry]

list(values []any) []any

Creates a new slice, optionally with values.

Examples

Example:

+{{ $slice := list "Apple" "Banana" }}
+{{ echo $slice }}

Output:

[Apple Banana]

dict(entries []any) (map[string]any, errors)

Creates a new map, optionally with key value pairs.

Pairs are constructed one by one, a key followed by the given value.

Currently only supports string keys!

Examples

Example:

+{{ $map := dict "key1" "value1" "key2" "value2" }}
+{{ echo $map }}

Output:

map[key1:value1 key2:value2]

toString(value any) string

Returns a given value as string (using fmt.Sprint, bytes are handled separately).

toBytes(str string) []byte

Turns a string into bytes.

toInt(str string) (int, throws error)

Attempts to parse a string as int.

toFloat64(str string) (float64, throws error)

Attempts to parse a string as float64.

toFloat32(str string) (float32, throws error)

Attempts to parse a string as float32.

toBool(str string) (bool, throws error)

Attempts to parse a string as a bool (using strconv.ParseBool).

echo(data []any)

Outputs data to stdout.

base64Encode(str string) string

Encodes strings with base64.

base64Decode(str string) (string, throws error)

Decodes a base64 string.

hexEncode(str string) string

Encodes a string as hex.

hexDecode(str string) (string, throws error)

Decodes a string as hex.

hash(str string)

Hashes a given string with SHA-256.

sha1(str string)

Hashes a given string with SHA-1.

sha512(str string)

Hashes a given string with SHA-512.

md5(str string)

Hashes a given string with MD-5.

fetch(url string) (string, throws error)

Fetches a resource from a given url. Outputs errors as string.

jsonEncode(obj any) (string, throws error)

Encodes an object into a json string.

jsonDecode(json string) (any, throws error)

Decodes a json string into an object.

abs(numbers int|float64) (int|float64, throws error)

Returns the abs value of a number.

min(a int|float64, b int|float64) (int|float64, throws error)

Returns the smaller value of two numbers.

max(a int|float64, b int|float64) (int|float64, throws error)

Returns the bigger value of two numbers.

clamp(value int|float64, min int|float64, max int|float64) (int|float64, throws error)

Clamps a value between a minimum and maximum value.

pow(base int|float64, exponent int|float64) (float64, throws error)

Performs pow on base with exponent.

sqrt(number int|float64) (float64, throws error)

Returns the square root of a number.

round(number int|float64, digits int?) (int, throws error)

Rounds a number to the specified number of decimal digits (default: 0).

floor(number int|float64) (int, throws error)

Returns the greatest integer value less than or equal to number.

ceil(number int|float64) (int, throws error)

Returns the least integer value greater than or equal to number.

add(numbers [](int|float64)) (int|float64, throws error)

Adds numbers together.

sub(numbers [](int|float64)) (int|float64, throws error)

Subtracts numbers from each other.

mul(numbers [](int|float64)) (int|float64, throws error)

Multiplies numbers together.

div(numbers [](int|float64)) (int|float64, throws error)

Divides numbers from each other.

mod(numbers [](int|float64)) (int|float64, throws error)

Performs modulo on numbers.

regexMatch(regex string, str string) (bool, throws error)

Returns whether a string matches the given regex pattern.

regexFindAll(regex string, str string, n int?) ([]string, throws error)

Returns all (optionally up to n) matches against the given regex pattern in a string.

regexFindGroups(regex string, str string) ([][]string, throws error)

Returns all matches and submatches from the given regex pattern in a string.

regexFindGroupsIndex(regex string, str string) ([][]int, throws error)

Returns all match and submatch positions from the given regex pattern in a string.

regexReplaceAll(str string, regex string, new string) (string, throws error)

Replaces all matches from the given regex pattern in a string with new (which for allows using '$1', etc.).

trimSpace(str string) string

Trims space from a string (leading and trailing).

trim(str string, cutset string) string

Trims all chars defined in the cutset param from a string (leading and trailing).

upper(str string) string

Uppercases a string.

lower(str string) string

Lowercases a string.

contains(str string, sub string) bool

Returns whether a string contains the given substring.

count(str string, sub string) int

Counts all occurences of a substring in the given string.

hasPrefix(str string, prefix string) bool

Returns whether a string starts with the given prefix.

hasSuffix(str string, suffix string) bool

Returns whether a string ends with the given suffix.

isEmpty(str string) bool

Returns whether the given string is empty.

replace(str string, old string, new string) string

Replaces all occurences of old with new.

split(str string, sep string) []string

Split a string by the given seperator.

after(str string, sub string) string

Returns the string after the given substring in a string.

afterLast(str string, sub string) string

Returns the string after the last occurrence of the given substring.

before(str string, sub string) string

Returns the string before the given substring in a string.

beforeLast(str string, sub string) string

Returns the string before the last occurrence of the given substring.

between(str string, startSub string, endSub string) string

Returns the substring between the start and end substring.

trimPrefix(str string, sub string) string

Removes a substring at the start of the given string.

trimSuffix(str string, sub string) string

Removes a substring at the end of the given string.

substr(str string, start int, end int) string

Slices a string based on start and end index.

join(sep string, strs []string) string

Joins multiple strings together by the given separator.

repeat(str string, count int) string

Repeat a string n times.

concat(strs []string) string

Concat strings together (join without sep).

emit(label string?, value any) throws error

Records a value, optionally with a label.

Not bundled with goplater, used internally for unit and integration tests.

Contributing

Found a bug or just want to change or add something? Feel free to open up an issue or a PR!

Support

Like this Project? Or just want to help? Why not ⭐️ this Repo? :)

License

This Project is licensed under the MIT License.

Legal

Logo designed by @CodeShellDev. All rights reserved for original design contributions.

Go gopher mascot originally created by Renée French, used and adapted under the CC BY 4.0 license.