shithub: hell

ref: bc18dbd45d3daed41e2f0c177efc9a7d0ebdc025
dir: /templater.go/

View raw version
package main

import (
	"fmt"
	"os"
)

// Holds a stringer and its template key
type templateDefs struct {
	stringer fmt.Stringer
	key      string
}

// Renders line templates by turning keys into mapped stringers
type templateRenderer struct {
	tempdefs []*templateDefs
}

// returns a new template renderer loaded with standard format keys
func newStatusTemplateRenderer(sf *StatusFormatter) *templateRenderer {
	template := &templateRenderer{
		tempdefs: []*templateDefs{
			{key: "content", stringer: &statusContent{sf}},
			{key: "media_descriptions", stringer: &mediaDescriptions{sf}},
			{key: "detail_line", stringer: &detailLine{sf}},
			{key: "username", stringer: &username{sf}},
			{key: "boostuser", stringer: &boostedusername{sf}},
			{key: "boostcontent", stringer: &boostContent{sf}},
			{key: "boosted_media_descriptions", stringer: &boostMediaDescriptions{sf}},
		},
	}
	// macro templates
	template.tempdefs = append(template.tempdefs, []*templateDefs{
		{key: "standard_status", stringer: &standardStatus{template}},
	}...)
	return template
}

// Render a template into a string, hyphenated for user display
func (tr *templateRenderer) render(template string) (string, error) {
	template, _ = tr.renderRaw(template)
	template, long := hyphenate(template)
	if long {
		return template + "\n\n", nil
	}
	return template + "\n", nil
}

// Render a template string with no hyphenation
func (tr *templateRenderer) renderRaw(template string) (string, error) {
	expandMap := func(key string) string {
		for item := range tr.tempdefs {
			if key == tr.tempdefs[item].key {
				return tr.tempdefs[item].stringer.String()
			}
		}
		return fmt.Sprintf("[%%KEY_NOT_FOUND:%s]", key)
	}
	return os.Expand(template, expandMap), nil
}

// Renders a status line with username + content + media descriptions
type standardStatus struct {
	*templateRenderer
}

func (ss *standardStatus) String() string {
	line, _ := ss.renderRaw("$username $content $media_descriptions")
	return line
}