~bigbes/sr-ht-ecore

ref: 17411599089544c82bc6c0a7c073276b9f90c275 sr-ht-ecore/chrome/funcs.go -rw-r--r-- 1.2 KiB
17411599 — Eugene Blikh bearer: split the grant check out of validation 10 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package chrome

import (
	"fmt"
	"html/template"
)

// Funcs returns the template helpers every service was carrying its own copy
// of. Merge into a service's FuncMap before its own helpers, so a service can
// still shadow a name deliberately.
func Funcs() template.FuncMap {
	return template.FuncMap{
		"dict":     Dict,
		"shortsha": ShortSHA,
	}
}

// Dict builds a map from alternating key/value arguments, so a partial that
// needs several fields can be invoked with an inline context:
// {{template "x" (dict "A" .A "B" .B)}}. An odd argument count or a non-string
// key is a template authoring error and surfaces as a render error.
func Dict(kv ...any) (map[string]any, error) {
	if len(kv)%2 != 0 {
		return nil, fmt.Errorf("dict: expected an even number of arguments, got %d", len(kv))
	}
	m := make(map[string]any, len(kv)/2)
	for i := 0; i < len(kv); i += 2 {
		k, ok := kv[i].(string)
		if !ok {
			return nil, fmt.Errorf("dict: key %d is not a string", i)
		}
		m[k] = kv[i+1]
	}
	return m, nil
}

// ShortSHA abbreviates an object id to its first 8 characters (or returns it
// unchanged if shorter), the convention used everywhere commits are listed.
func ShortSHA(s string) string {
	if len(s) > 8 {
		return s[:8]
	}
	return s
}