File: example_test.go

package info (click to toggle)
golang-github-intel-tfortools 0.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 660 kB
  • sloc: makefile: 4
file content (604 lines) | stat: -rw-r--r-- 15,939 bytes parent folder | download | duplicates (2)
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
// Copyright (c) 2017 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package tfortools

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
	"strings"
)

func ExampleGenerateUsageDecorated() {
	cfg := NewConfig(OptCols)
	help := GenerateUsageDecorated("-f", []struct{ X, Y int }{}, cfg)
	fmt.Println(help)
	// output:
	// The template passed to the --f option operates on a
	//
	// []struct {
	//	X int
	//	Y int
	// }
	//
	// Some new functions have been added to Go's template language
	//
	// - 'cols' can be used to extract certain columns from a table consisting of a
	//   slice or array of structs.  It returns a new slice of structs which contain
	//   only the fields requested by the caller.   For example, given a slice of structs
	//
	//   {{cols . "Name" "Address"}}
	//
	//   returns a new slice of structs, each element of which is a structure with only
	//   two fields, 'Name' and 'Address'.
}

func ExampleGenerateUsageUndecorated() {
	i := struct {
		X       int    `tfortools:"This is an int"`
		Y       string `json:"omitempty" tfortools:"This is a string"`
		hidden  float64
		Invalid chan int
	}{}
	help := GenerateUsageUndecorated(i)
	fmt.Println(help)
	// output:
	// struct {
	// 	X int    // This is an int
	// 	Y string `json:"omitempty"` // This is a string
	// }
}

func ExampleTemplateFunctionNames() {
	cfg := NewConfig(OptCols, OptRows)
	err := cfg.AddCustomFn(strings.TrimSpace, "trim",
		"- trim trims leading and trailing whitespace from string")
	if err != nil {
		panic(err)
	}
	for _, fn := range TemplateFunctionNames(cfg) {
		fmt.Println(fn)
	}
	// output:
	// cols
	// rows
	// trim
}

func ExampleTemplateFunctionHelpSingle() {
	cfg := NewConfig(OptCols, OptRows)
	err := cfg.AddCustomFn(strings.TrimSpace, "trim",
		"- trim trims leading and trailing whitespace from string")
	if err != nil {
		panic(err)
	}
	help, err := TemplateFunctionHelpSingle("cols", cfg)
	if err != nil {
		panic(err)
	}
	fmt.Println(help)

	help, err = TemplateFunctionHelpSingle("trim", cfg)
	if err != nil {
		panic(err)
	}
	fmt.Println(help)
	// output:
	// - 'cols' can be used to extract certain columns from a table consisting of a
	//   slice or array of structs.  It returns a new slice of structs which contain
	//   only the fields requested by the caller.   For example, given a slice of structs
	//
	//   {{cols . "Name" "Address"}}
	//
	//   returns a new slice of structs, each element of which is a structure with only
	//   two fields, 'Name' and 'Address'.
	//
	// - trim trims leading and trailing whitespace from string
}

func ExampleOutputToTemplate() {
	data := []struct{ FirstName, MiddleName, Surname string }{
		{"Marcus", "Tullius", "Cicero"},
		{"Gaius", "Julius", "Caesar"},
		{"Marcus", "Licinius", "Crassus"},
	}

	// print the surname of the person whose middlename is lexographically smallest.
	script := `{{select (head (sort . "MiddleName")) "Surname"}}`
	if err := OutputToTemplate(os.Stdout, "names", script, data, nil); err != nil {
		panic(err)
	}
	// output:
	// Caesar
}

func ExampleOptFilter() {
	data := []struct{ FirstName, MiddleName, Surname string }{
		{"Marcus", "Tullius", "Cicero"},
		{"Gaius", "Julius", "Caesar"},
		{"Marcus", "Licinius", "Crassus"},
	}

	// Print the surname of all people whose first name is Marcus
	script := `{{range (filter . "FirstName" "Marcus")}}{{println .Surname}}{{end}}`
	if err := OutputToTemplate(os.Stdout, "names", script, data, nil); err != nil {
		panic(err)
	}
	// output:
	// Cicero
	// Crassus
}

func ExampleOptFilterContains() {
	data := []struct{ FirstName, MiddleName, Surname string }{
		{"Marcus", "Tullius", "Cicero"},
		{"Gaius", "Julius", "Caesar"},
		{"Marcus", "Licinius", "Crassus"},
	}

	// Count the number of people whose middle name contains a 'ul'
	script := `{{len (filterContains . "MiddleName" "ul")}}`
	if err := OutputToTemplate(os.Stdout, "names", script, data, nil); err != nil {
		panic(err)
	}
	// output:
	// 2
}

func ExampleOptFilterHasPrefix() {
	data := []struct{ FirstName, MiddleName, Surname string }{
		{"Marcus", "Tullius", "Cicero"},
		{"Gaius", "Julius", "Caesar"},
		{"Marcus", "Licinius", "Crassus"},
	}

	// Print all the surnames that start with 'Ci'
	script := `{{select (filterHasPrefix . "Surname" "Ci") "Surname"}}`
	if err := OutputToTemplate(os.Stdout, "names", script, data, nil); err != nil {
		panic(err)
	}
	// output:
	// Cicero
}

func ExampleOptFilterHasSuffix() {
	data := []struct{ FirstName, MiddleName, Surname string }{
		{"Marcus", "Tullius", "Cicero"},
		{"Gaius", "Julius", "Caesar"},
		{"Marcus", "Licinius", "Crassus"},
	}

	// Print all the surnames that end with 'us'
	script := `{{select (filterHasSuffix . "Surname" "us") "Surname"}}`
	if err := OutputToTemplate(os.Stdout, "names", script, data, nil); err != nil {
		panic(err)
	}
	// output:
	// Crassus
}

func ExampleOptFilterFolded() {
	data := []struct{ FirstName, MiddleName, Surname string }{
		{"Marcus", "Tullius", "Cicero"},
		{"Gaius", "Julius", "Caesar"},
		{"Marcus", "Licinius", "Crassus"},
	}

	// Output the first and surnames of all people whose first name is marcus
	script := `{{range (filterFolded . "FirstName" "marcus")}}{{println .FirstName .Surname}}{{end}}`
	if err := OutputToTemplate(os.Stdout, "names", script, data, nil); err != nil {
		panic(err)
	}
	// output:
	// Marcus Cicero
	// Marcus Crassus
}

func ExampleOptFilterRegexp() {
	data := []struct{ FirstName, MiddleName, Surname string }{
		{"Marcus", "Tullius", "Cicero"},
		{"Gaius", "Julius", "Caesar"},
		{"Marcus", "Licinius", "Crassus"},
	}

	// Output the first and last names of all people whose middle name ends in 'ius' and whose
	// second letter is 'u'
	script := `{{range (filterRegexp . "MiddleName" "^.u.*ius$")}}{{println .FirstName .Surname}}{{end}}`
	if err := OutputToTemplate(os.Stdout, "names", script, data, nil); err != nil {
		panic(err)
	}
	// output:
	// Marcus Cicero
	// Gaius Caesar
}

func ExampleOptToJSON() {
	data := []struct {
		Name       string
		AgeAtDeath int
		Battles    []string
	}{
		{"Caesar", 55, []string{"Battle of Alesia", "Battle of Dyrrhachium", "Battle of the Nile"}},
		{"Alexander", 32, []string{"Battle of Issus", "Battle of Gaugamela", "Battle of the Hydaspes"}},
	}

	script := `{{tojson .}}`
	if err := OutputToTemplate(os.Stdout, "names", script, data, nil); err != nil {
		panic(err)
	}
	// output:
	// [
	// 	{
	//		"Name": "Caesar",
	//		"AgeAtDeath": 55,
	//		"Battles": [
	//			"Battle of Alesia",
	//			"Battle of Dyrrhachium",
	//			"Battle of the Nile"
	//		]
	//	},
	//	{
	//		"Name": "Alexander",
	//		"AgeAtDeath": 32,
	//		"Battles": [
	//			"Battle of Issus",
	//			"Battle of Gaugamela",
	//			"Battle of the Hydaspes"
	//		]
	//	}
	// ]
}

func ExampleOptTableX() {
	data := []struct{ FirstName, MiddleName, Surname string }{
		{"Marcus", "Tullius", "Cicero"},
		{"Gaius", "Julius", "Caesar"},
		{"Marcus", "Licinius", "Crassus"},
	}

	// Output the names of people in a nicely formatted table
	script := `{{tablex . 12 8 0}}`
	var b bytes.Buffer
	if err := OutputToTemplate(&b, "names", script, data, nil); err != nil {
		panic(err)
	}

	// Normally you would pass os.Stdout directly into OutputToTemplate.  Here
	// we're outputting the result of the running the script to a buffer.  We need
	// to do this so we can remove the whitespace at the end of each line of the
	// table.  The test fails with the newline present as go tests implementation
	// of output: for examples, trims spaces.

	scanner := bufio.NewScanner(&b)
	for scanner.Scan() {
		fmt.Println(strings.TrimSpace(scanner.Text()))
	}
	// output:
	// FirstName   MiddleName  Surname
	// Marcus      Tullius     Cicero
	// Gaius       Julius      Caesar
	// Marcus      Licinius    Crassus
}

func ExampleOptTableXAlt() {
	data := []struct {
		FirstName string
		Mask      uint32
	}{
		{"Marcus", 255},
		{"Gaius", 10},
		{"Marcus", 6},
	}

	script := `{{tablexalt . 12 8 0}}`
	var b bytes.Buffer
	if err := OutputToTemplate(&b, "names", script, data, nil); err != nil {
		panic(err)
	}

	scanner := bufio.NewScanner(&b)
	for scanner.Scan() {
		fmt.Println(strings.TrimSpace(scanner.Text()))
	}
	// output:
	// FirstName   Mask
	// "Marcus"    0xff
	// "Gaius"     0xa
	// "Marcus"    0x6
}

func ExampleOptHTableX() {
	data := []struct{ FirstName, MiddleName, Surname string }{
		{"Marcus", "Tullius", "Cicero"},
		{"Gaius", "Julius", "Caesar"},
		{"Marcus", "Licinius", "Crassus"},
	}

	// Output the names of people in a series of nicely formatted tables
	script := `{{htablex . 12 8 0}}`
	var b bytes.Buffer
	if err := OutputToTemplate(&b, "names", script, data, nil); err != nil {
		panic(err)
	}

	scanner := bufio.NewScanner(&b)
	for scanner.Scan() {
		fmt.Println(strings.TrimSpace(scanner.Text()))
	}
	// output:
	// FirstName:  Marcus
	// MiddleName: Tullius
	// Surname:    Cicero
	//
	// FirstName:  Gaius
	// MiddleName: Julius
	// Surname:    Caesar
	//
	// FirstName:  Marcus
	// MiddleName: Licinius
	// Surname:    Crassus
}

func ExampleOptHTableXAlt() {
	data := []struct {
		FirstName string
		Mask      uint32
	}{
		{"Marcus", 255},
		{"Gaius", 10},
		{"Marcus", 6},
	}

	script := `{{htablexalt . 12 8 0}}`
	var b bytes.Buffer
	if err := OutputToTemplate(&b, "names", script, data, nil); err != nil {
		panic(err)
	}

	scanner := bufio.NewScanner(&b)
	for scanner.Scan() {
		fmt.Println(strings.TrimSpace(scanner.Text()))
	}

	// output:
	// FirstName:  "Marcus"
	// Mask:       0xff
	//
	// FirstName:  "Gaius"
	// Mask:       0xa
	//
	// FirstName:  "Marcus"
	// Mask:       0x6
}

func ExampleOptCols() {
	data := []struct{ FirstName, MiddleName, Surname string }{
		{"Marcus", "Tullius", "Cicero"},
		{"Gaius", "Julius", "Caesar"},
		{"Marcus", "Licinius", "Crassus"},
	}

	// Output the first and last names of people in a nicely formatted table
	script := `{{tablex (cols . "FirstName" "Surname") 12 8 0}}`
	var b bytes.Buffer
	if err := OutputToTemplate(&b, "names", script, data, nil); err != nil {
		panic(err)
	}

	// Normally you would pass os.Stdout directly into OutputToTemplate.  Here
	// we're outputting the result of the running the script to a buffer.  We need
	// to do this so we can remove the whitespace at the end of each line of the
	// table.  The test fails with the newline present as go tests implementation
	// of output: for examples, trims spaces.

	scanner := bufio.NewScanner(&b)
	for scanner.Scan() {
		fmt.Println(strings.TrimSpace(scanner.Text()))
	}
	// output:
	// FirstName   Surname
	// Marcus      Cicero
	// Gaius       Caesar
	// Marcus      Crassus
}

func ExampleOptSort() {
	data := []struct{ FirstName, MiddleName, Surname string }{
		{"Marcus", "Tullius", "Cicero"},
		{"Gaius", "Julius", "Caesar"},
		{"Marcus", "Licinius", "Crassus"},
	}

	// Output the names of people sorted by their Surnames
	script := `{{tablex (sort . "Surname") 12 8 0}}`
	var b bytes.Buffer
	if err := OutputToTemplate(&b, "names", script, data, nil); err != nil {
		panic(err)
	}

	// Normally you would pass os.Stdout directly into OutputToTemplate.  Here
	// we're outputting the result of the running the script to a buffer.  We need
	// to do this so we can remove the whitespace at the end of each line of the
	// table.  The test fails with the newline present as go tests implementation
	// of output: for examples, trims spaces.

	scanner := bufio.NewScanner(&b)
	for scanner.Scan() {
		fmt.Println(strings.TrimSpace(scanner.Text()))
	}
	// output:
	// FirstName   MiddleName  Surname
	// Gaius       Julius      Caesar
	// Marcus      Tullius     Cicero
	// Marcus      Licinius    Crassus
}

func ExampleOptRows() {
	data := []struct{ FirstName, MiddleName, Surname string }{
		{"Marcus", "Tullius", "Cicero"},
		{"Gaius", "Julius", "Caesar"},
		{"Marcus", "Licinius", "Crassus"},
	}

	// Print the surname of the first and third people in the database
	script := `{{range (rows . 0 2)}}{{println .Surname}}{{end}}`
	if err := OutputToTemplate(os.Stdout, "names", script, data, nil); err != nil {
		panic(err)
	}
	// output:
	// Cicero
	// Crassus
}

func ExampleOptHead() {
	data := []struct{ FirstName, MiddleName, Surname string }{
		{"Marcus", "Tullius", "Cicero"},
		{"Gaius", "Julius", "Caesar"},
		{"Marcus", "Licinius", "Crassus"},
	}

	// Print the surname of the first person in the database
	script := `{{range (head .)}}{{println .Surname}}{{end}}`
	if err := OutputToTemplate(os.Stdout, "names", script, data, nil); err != nil {
		panic(err)
	}
	// output:
	// Cicero
}

func ExampleOptTail() {
	data := []struct{ FirstName, MiddleName, Surname string }{
		{"Marcus", "Tullius", "Cicero"},
		{"Gaius", "Julius", "Caesar"},
		{"Marcus", "Licinius", "Crassus"},
	}

	// Print the surname of the first person in the database
	script := `{{range (tail .)}}{{println .Surname}}{{end}}`
	if err := OutputToTemplate(os.Stdout, "names", script, data, nil); err != nil {
		panic(err)
	}
	// output:
	// Crassus
}

func ExampleOptDescribe() {
	data := []struct{ FirstName, MiddleName, Surname string }{}

	// Describe the type of data
	script := `{{describe .}}`
	if err := OutputToTemplate(os.Stdout, "names", script, data, nil); err != nil {
		panic(err)
	}
	// output:
	// []struct {
	// 	FirstName  string
	// 	MiddleName string
	//	Surname    string
	// }
}

func ExampleOptPromote() {
	type cred struct {
		Name     string
		Password string
	}

	type u struct {
		Credentials cred
	}

	data := []struct {
		Uninteresting int
		User          u
	}{
		{0, u{cred{"Marcus", "1234"}}},
		{0, u{cred{"Gaius", "0000"}}},
	}

	// Create a new []cred containing the credentials embedded within data,
	// iterate through this new slice printing out the names and passwords.
	// The cred instances rooted at "User.Credentials" in the data object
	// are promoted to the top level in the new slice.
	script := `{{range (promote . "User.Credentials")}}{{printf "%s %s\n" .Name .Password}}{{end}}`
	if err := OutputToTemplate(os.Stdout, "names", script, data, nil); err != nil {
		panic(err)
	}
	// output:
	// Marcus 1234
	// Gaius 0000
}

func ExampleOptSliceof() {
	script := `{{index (sliceof .) 0}}`
	if err := OutputToTemplate(os.Stdout, "names", script, 1, nil); err != nil {
		panic(err)
	}
	// output:
	// 1
}

func ExampleOptToTable() {
	data := [][]string{
		{"Message", "Code", "Occurrence"},
		{"Too many GOSUBs", "37", "0.1"},
		{"Too many REPEATs", "44", "0.15"},
	}
	script := `{{with (totable .)}}{{select . "Message"}}{{select . "Code"}}{{select . "Occurrence"}}{{end}}`
	if err := OutputToTemplate(os.Stdout, "errors", script, data, nil); err != nil {
		panic(err)
	}
	// output:
	// Too many GOSUBs
	// Too many REPEATs
	// 37
	// 44
	// 0.1
	// 0.15
}

func ExampleOptSelectAlt() {
	data := []struct{ Integer uint32 }{{255}}
	script := `{{selectalt . "Integer"}}`
	if err := OutputToTemplate(os.Stdout, "names", script, data, nil); err != nil {
		panic(err)
	}
	// output:
	// 0xff
}

func ExampleConfig_AddCustomFn() {
	nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	cfg := NewConfig(OptAllFns)
	err := cfg.AddCustomFn(func(n []int) int {
		sum := 0
		for _, num := range n {
			sum += num
		}
		return sum
	}, "sum", "- sum \"Returns\" the sum of a slice of integers")
	if err != nil {
		panic(err)
	}

	// Print the sum of a slice of numbers
	script := `{{println (sum .)}}`
	if err = OutputToTemplate(os.Stdout, "sums", script, nums, cfg); err != nil {
		panic(err)
	}
	// output:
	// 55
}