-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.go.template
More file actions
90 lines (73 loc) · 2.09 KB
/
script.go.template
File metadata and controls
90 lines (73 loc) · 2.09 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// vim: ft=go
// script_template.go
// This file is used as a template for inline scripts.
package main
import (
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
)
// ---- helpers ----
// die prints err to stderr and exits 1. No-op if err is nil.
func die(err error) {
if err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
// must unwraps a (value, error) pair, calling die on error.
//
// n, err := strconv.Atoi(s) → n := must(strconv.Atoi(s))
func must[T any](v T, err error) T {
die(err)
return v
}
// atoi parses s as an int. Exits on failure.
func atoi(s string) int { return must(strconv.Atoi(strings.TrimSpace(s))) }
// atof parses s as a float64. Exits on failure.
func atof(s string) float64 { return must(strconv.ParseFloat(strings.TrimSpace(s), 64)) }
// pp returns v formatted as indented JSON (falls back to %+v on error).
// Used with auto-print: pp(myMap) prints the JSON automatically.
func pp(v any) string {
b, err := json.MarshalIndent(v, "", " ")
if err != nil {
return fmt.Sprintf("%+v", v)
}
return string(b)
}
// trim returns strings.TrimSpace(s).
func trim(s string) string { return strings.TrimSpace(s) }
// splitlines splits a multi-line string into a slice, dropping the trailing newline.
func splitlines(s string) []string { return strings.Split(strings.TrimRight(s, "\n"), "\n") }
var _reCache sync.Map
func _reCached(pat string) *regexp.Regexp {
if v, ok := _reCache.Load(pat); ok {
return v.(*regexp.Regexp)
}
r := regexp.MustCompile(pat)
_reCache.Store(pat, r)
return r
}
// match returns submatches: [0]=full match, [1+]=capture groups. nil if no match.
func match(pat, s string) []string { return _reCached(pat).FindStringSubmatch(s) }
// named returns named capture groups as a map. nil if no match.
func named(pat, s string) map[string]string {
r := _reCached(pat)
m := r.FindStringSubmatch(s)
if m == nil {
return nil
}
result := map[string]string{}
for i, name := range r.SubexpNames() {
if name != "" && i < len(m) {
result[name] = m[i]
}
}
return result
}
// ---- end helpers ----
func main() {
// {{INLINE_BODY}}
}