forked from brianvoe/gofakeit
/
template.go
385 lines (321 loc) · 11.3 KB
/
template.go
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
package gofakeit
import (
"bytes"
"fmt"
"strconv"
"time"
"math/rand"
"reflect"
"strings"
"text/template"
)
// TemplateOptions defines values needed for template document generation
type TemplateOptions struct {
Funcs template.FuncMap `fake:"-"`
Data any `json:"data" xml:"data" fake:"-"`
}
// Template generates an document based on the the supplied template
func Template(template string, co *TemplateOptions) (string, error) {
if co == nil {
co = &TemplateOptions{}
globalFaker.Struct(co)
}
return templateFunc(template, templateFuncMap(globalFaker.Rand, &co.Funcs), co)
}
// Template generates an document based on the the supplied template
func (f *Faker) Template(template string, co *TemplateOptions) (string, error) {
if co == nil {
co = &TemplateOptions{}
f.Struct(co)
}
return templateFunc(template, templateFuncMap(f.Rand, &co.Funcs), co)
}
// MarkdownOptions defines values needed for markdown document generation
type MarkdownOptions struct {
SectionsCount int `json:"sections" xml:"sections" fake:"{number:1,10}"`
}
// Template for Markdown
const templateMarkdown = `
{{$repo := Gamertag}}
{{$language := RandomString (SliceString "go" "python" "javascript")}}
{{$username := Gamertag}}
{{$weightedSlice := SliceAny "github.com" "gitlab.com" "bitbucket.org"}}
{{$weightedWeights := SliceF32 5 1 1}}
{{$domain := Weighted $weightedSlice $weightedWeights}}
{{$action := RandomString (SliceString "process" "run" "execute" "perform" "handle")}}
{{$usage := RandomString (SliceString "whimsical story" "quirky message" "playful alert" "funny request" "lighthearted command")}}
{{$result := RandomString (SliceString "success" "error" "unknown" "completed" "failed" "finished" "in progress" "terminated")}}
# {{$repo}}
*Author: {{FirstName}} {{LastName}}*
{{Paragraph 2 5 7 "\n\n"}}
## Table of Contents
- [Installation](#installation)
- [Usage](#usage)
- [License](#license)
## Installation
{{if eq $language "go"}}'''go
go get {{$domain}}/{{$username}}/{{$repo}}
'''{{else if eq $language "python"}}'''bash
pip install {{$repo}}
'''{{else if eq $language "javascript"}}'''js
npm install {{$repo}}
'''{{end}}
## Usage
{{if eq $language "go"}}'''go
result := {{$repo}}.{{$action}}("{{ToLower $usage}}")
fmt.Println("{{ToLower $repo}} result:", "{{ToLower $result}}")
'''{{else if eq $language "python"}}'''python
result = {{ToLower $repo}}.{{$action}}("{{ToLower $usage}}")
print("{{ToLower $repo}} result:", "{{ToLower $result}}")
'''{{else if eq $language "javascript"}}'''javascript
const result = {{ToLower $repo}}.{{$action}}("{{ToLower $usage}}");
console.log("{{ToLower $repo}} result:", "{{ToLower $result}}");
'''{{end}}
## License
{{RandomString (SliceString "MIT" "Apache 2.0" "GPL-3.0" "BSD-3-Clause" "ISC")}}
`
// Markdown will return a single random Markdown template document
func Markdown(co *MarkdownOptions) (string, error) {
if co == nil {
co = &MarkdownOptions{}
globalFaker.Struct(co)
}
return templateFunc(templateMarkdown, templateFuncMap(globalFaker.Rand, nil), co)
}
// Markdown will return a single random Markdown template document
func (f *Faker) Markdown(co *MarkdownOptions) (string, error) {
if co == nil {
co = &MarkdownOptions{}
f.Struct(co)
}
return templateFunc(templateMarkdown, templateFuncMap(f.Rand, nil), co)
}
// EmailOptions defines values needed for email document generation
type EmailOptions struct {
SectionsCount int `json:"sections" xml:"sections" fake:"{number:1,10}"`
}
// Template for email text
const templateEmail = `
Subject: {{RandomString (SliceString "Greetings" "Hello" "Hi")}} from {{FirstName}}!
Dear {{LastName}},
{{RandomString (SliceString "Greetings!" "Hello there!" "Hi, how are you?")}} {{RandomString (SliceString "How's everything going?" "I hope your day is going well." "Sending positive vibes your way.")}}
{{RandomString (SliceString "I trust this email finds you well." "I hope you're doing great." "Hoping this message reaches you in good spirits.")}} {{RandomString (SliceString "Wishing you a fantastic day!" "May your week be filled with joy." "Sending good vibes your way.")}}
{{Paragraph 3 5 10 "\n\n"}}
{{RandomString (SliceString "I would appreciate your thoughts on" "I'm eager to hear your feedback on" "I'm curious to know what you think about")}} it. If you have a moment, please feel free to check out the project on {{RandomString (SliceString "GitHub" "GitLab" "Bitbucket")}}
{{RandomString (SliceString "Your insights would be invaluable." "I'm eager to hear what you think." "Feel free to share your opinions with me.")}} {{RandomString (SliceString "Looking forward to your feedback!" "Your perspective is highly valued." "Your thoughts matter to me.")}}
{{RandomString (SliceString "Thank you for your consideration!" "I appreciate your attention to this matter." "Your support means a lot to me.")}} {{RandomString (SliceString "Wishing you a wonderful day!" "Thanks in advance for your time." "Your feedback is greatly appreciated.")}}
{{RandomString (SliceString "Warm regards" "Best wishes" "Kind regards" "Sincerely" "With gratitude")}}
{{FirstName}} {{LastName}}
{{Email}}
{{PhoneFormatted}}
`
// EmailText will return a single random text email template document
func EmailText(co *EmailOptions) (string, error) {
if co == nil {
co = &EmailOptions{}
globalFaker.Struct(co)
}
return templateFunc(templateEmail, templateFuncMap(globalFaker.Rand, nil), co)
}
// EmailText will return a single random text email template document
func (f *Faker) EmailText(co *EmailOptions) (string, error) {
if co == nil {
co = &EmailOptions{}
f.Struct(co)
}
return templateFunc(templateEmail, templateFuncMap(f.Rand, nil), co)
}
// functions that wont work with template engine
var templateExclusion = []string{
"RandomMapKey",
"SQL",
"Template",
}
// Build the template.FuncMap for the template engine
func templateFuncMap(r *rand.Rand, fm *template.FuncMap) *template.FuncMap {
// create a new function map
funcMap := template.FuncMap{}
// build the function map from a faker using their rand
f := &Faker{Rand: r}
v := reflect.ValueOf(f)
// loop through the methods
for i := 0; i < v.NumMethod(); i++ {
// check if the method is in the exclusion list
if stringInSlice(v.Type().Method(i).Name, templateExclusion) {
continue
}
// Check if method has return values
// If not don't add to function map
if v.Type().Method(i).Type.NumOut() == 0 {
continue
}
// add the method to the function map
funcMap[v.Type().Method(i).Name] = v.Method(i).Interface()
}
// make string upper case
funcMap["ToUpper"] = strings.ToUpper
// make string lower case
funcMap["ToLower"] = strings.ToLower
// make string title case
funcMap["IntRange"] = func(start, end int) []int {
n := end - start + 1
result := make([]int, n)
for i := 0; i < n; i++ {
result[i] = start + i
}
return result
}
// enable passing any type to return a string
funcMap["ToInt"] = func(args any) int {
switch v := args.(type) {
case string:
i, err := strconv.Atoi(v)
if err != nil {
return 0
}
return i
case float64:
return int(v)
case float32:
return int(v)
case int:
return v
// Anything else return 0
default:
return 0
}
}
// ensable passing any type to return a string
funcMap["ToString"] = func(args any) string {
switch v := args.(type) {
case string:
return v
case float64:
return strconv.FormatFloat(v, 'f', -1, 64)
case float32:
return strconv.FormatFloat(float64(v), 'f', -1, 32)
case int:
return strconv.Itoa(v)
// Anything else return empty string
default:
return ""
}
}
// function to convert string to date time
funcMap["ToDate"] = func(dateString string) time.Time {
date, err := time.Parse("2006-01-02", dateString)
if err != nil {
return time.Now()
}
return date
}
// enable passing slice of interface to functions
funcMap["SliceAny"] = func(args ...any) []any {
return args
}
// enable passing slice of string to functions
funcMap["SliceString"] = func(args ...string) []string {
return args
}
// enable passing slice of uint to functions
funcMap["SliceUInt"] = func(args ...uint) []uint {
return args
}
// enable passing slice of int to functions
funcMap["SliceInt"] = func(args ...int) []int {
return args
}
// enable passing slice of int to functions
funcMap["SliceF32"] = func(args ...float32) []float32 {
return args
}
return &funcMap
}
// function to build the function map for the template engine from the global faker
func templateFunc(temp string, funcs *template.FuncMap, data any) (string, error) {
if temp == "" {
return "", fmt.Errorf("template parameter is empty")
}
// Create a new template and parse
template_gen, err := template.New("CodeRun").Funcs(*funcs).Parse(temp)
if err != nil {
return "", err
}
b := &bytes.Buffer{}
err = template_gen.Execute(b, data)
if err != nil {
return "", err
}
// Return the result
return strings.ReplaceAll(b.String(), "\\n", "\n"), nil
}
// addTemplateLookup will add the template functions to the global lookup
func addTemplateLookup() {
AddFuncLookup("template", Info{
Display: "Template",
Category: "template",
Description: "Generates document from template",
Example: `
{{Firstname}} {{Lastname}}
// output
Markus Moen
`,
Output: "string",
ContentType: "text/plain",
Params: []Param{
{Field: "template", Display: "Template", Type: "string", Description: "Golang template to generate the document from"},
{Field: "data", Display: "Custom Data", Type: "string", Default: "", Optional: true, Description: "Custom data to pass to the template"},
},
Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) {
tpl, err := info.GetString(m, "template")
if err != nil {
return nil, err
}
data, err := info.GetAny(m, "data")
if err != nil {
return nil, err
}
templateOut, err := templateFunc(tpl, templateFuncMap(r, nil), &TemplateOptions{Data: data})
if err != nil {
return nil, err
}
return templateOut, nil
},
})
AddFuncLookup("markdown", Info{
Display: "Random markdown document",
Category: "template",
Description: "Generates random markdown document",
Example: "",
Output: "string",
Params: []Param{
{Field: "sections_count", Display: "Body Sections", Type: "int", Default: "1", Optional: true, Description: "Number of content sections to generate"},
},
Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) {
sections, err := info.GetInt(m, "sections_count")
if err != nil {
sections = 1
}
template_result, err := templateFunc(templateMarkdown, templateFuncMap(r, nil), &MarkdownOptions{SectionsCount: sections})
return string(template_result), err
},
})
AddFuncLookup("email_text", Info{
Display: "Random text email Document",
Category: "template",
Description: "Generates random email document.",
Example: "",
Output: "string",
Params: []Param{
{Field: "sections_count", Display: "Body Sections", Type: "int", Default: "1", Optional: true, Description: "Number of content sections to generate"},
},
Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) {
sections, err := info.GetInt(m, "sections_count")
if err != nil {
sections = 1
}
template_result, err := templateFunc(templateEmail, templateFuncMap(r, nil), &EmailOptions{SectionsCount: sections})
return string(template_result), err
},
})
}