Codebase list golang-github-intel-tfortools / 909b30b4-6b8a-4667-a9c9-5105bd72e749/upstream funcs.go
909b30b4-6b8a-4667-a9c9-5105bd72e749/upstream

Tree @909b30b4-6b8a-4667-a9c9-5105bd72e749/upstream (Download .tar.gz)

funcs.go @909b30b4-6b8a-4667-a9c9-5105bd72e749/upstreamraw · history · blame

  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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
//
// 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 (
	"bytes"
	"encoding/csv"
	"encoding/json"
	"fmt"
	"reflect"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"text/tabwriter"
	"text/template"
	"unicode"
	"unicode/utf8"
)

type tableHeading struct {
	name  string
	index int
}

var sortAscMap = map[reflect.Kind]func(interface{}, interface{}) bool{
	reflect.Int: func(v1, v2 interface{}) bool {
		return v1.(int) < v2.(int)
	},
	reflect.Int8: func(v1, v2 interface{}) bool {
		return v1.(int8) < v2.(int8)
	},
	reflect.Int16: func(v1, v2 interface{}) bool {
		return v1.(int16) < v2.(int16)
	},
	reflect.Int32: func(v1, v2 interface{}) bool {
		return v1.(int32) < v2.(int32)
	},
	reflect.Int64: func(v1, v2 interface{}) bool {
		return v1.(int64) < v2.(int64)
	},
	reflect.Uint: func(v1, v2 interface{}) bool {
		return v1.(uint) < v2.(uint)
	},
	reflect.Uint8: func(v1, v2 interface{}) bool {
		return v1.(uint8) < v2.(uint8)
	},
	reflect.Uint16: func(v1, v2 interface{}) bool {
		return v1.(uint16) < v2.(uint16)
	},
	reflect.Uint32: func(v1, v2 interface{}) bool {
		return v1.(uint32) < v2.(uint32)
	},
	reflect.Uint64: func(v1, v2 interface{}) bool {
		return v1.(uint64) < v2.(uint64)
	},
	reflect.Float64: func(v1, v2 interface{}) bool {
		return v1.(float64) < v2.(float64)
	},
	reflect.Float32: func(v1, v2 interface{}) bool {
		return v1.(float32) < v2.(float32)
	},
	reflect.String: func(v1, v2 interface{}) bool {
		return v1.(string) < v2.(string)
	},
}

var sortDscMap = map[reflect.Kind]func(interface{}, interface{}) bool{
	reflect.Int: func(v1, v2 interface{}) bool {
		return v2.(int) < v1.(int)
	},
	reflect.Int8: func(v1, v2 interface{}) bool {
		return v2.(int8) < v1.(int8)
	},
	reflect.Int16: func(v1, v2 interface{}) bool {
		return v2.(int16) < v1.(int16)
	},
	reflect.Int32: func(v1, v2 interface{}) bool {
		return v2.(int32) < v1.(int32)
	},
	reflect.Int64: func(v1, v2 interface{}) bool {
		return v2.(int64) < v1.(int64)
	},
	reflect.Uint: func(v1, v2 interface{}) bool {
		return v2.(uint) < v1.(uint)
	},
	reflect.Uint8: func(v1, v2 interface{}) bool {
		return v2.(uint8) < v1.(uint8)
	},
	reflect.Uint16: func(v1, v2 interface{}) bool {
		return v2.(uint16) < v1.(uint16)
	},
	reflect.Uint32: func(v1, v2 interface{}) bool {
		return v2.(uint32) < v1.(uint32)
	},
	reflect.Uint64: func(v1, v2 interface{}) bool {
		return v2.(uint64) < v1.(uint64)
	},
	reflect.Float64: func(v1, v2 interface{}) bool {
		return v2.(float64) < v1.(float64)
	},
	reflect.Float32: func(v1, v2 interface{}) bool {
		return v2.(float32) < v1.(float32)
	},
	reflect.String: func(v1, v2 interface{}) bool {
		return v2.(string) < v1.(string)
	},
}

type valueSorter struct {
	val   reflect.Value
	field int
	less  func(v1, v2 interface{}) bool
}

func (v *valueSorter) Len() int {
	return v.val.Len()
}

func (v *valueSorter) index(i int) reflect.Value {
	val := v.val.Index(i)
	if val.Kind() == reflect.Ptr {
		val = reflect.Indirect(val)
	}
	return val
}

func (v *valueSorter) Less(i, j int) bool {
	iVal := v.index(i)
	jVal := v.index(j)
	return v.less(iVal.Field(v.field).Interface(), jVal.Field(v.field).Interface())
}

func (v *valueSorter) Swap(i, j int) {
	iVal := v.index(i).Interface()
	jVal := v.index(j).Interface()
	v.index(i).Set(reflect.ValueOf(jVal))
	v.index(j).Set(reflect.ValueOf(iVal))
}

func getValue(obj interface{}) reflect.Value {
	val := reflect.ValueOf(obj)
	if val.Kind() == reflect.Ptr {
		val = reflect.Indirect(val)
	}
	return val
}

func fatalf(name, format string, args ...interface{}) {
	panic(template.ExecError{
		Name: name,
		Err:  fmt.Errorf(format, args...),
	})
}

func newValueSorter(obj interface{}, field string, ascending bool) *valueSorter {
	val := reflect.ValueOf(obj)
	typ := reflect.TypeOf(obj)
	sTyp := typ.Elem()
	if sTyp.Kind() == reflect.Ptr {
		sTyp = sTyp.Elem()
	}

	var index int
	var fTyp reflect.StructField
	for index = 0; index < sTyp.NumField(); index++ {
		fTyp = sTyp.Field(index)
		if fTyp.Name == field {
			break
		}
	}
	if index == sTyp.NumField() {
		fatalf("sort", "%s is not a valid field name", field)
	}
	fKind := fTyp.Type.Kind()

	var lessFn func(interface{}, interface{}) bool
	if ascending {
		lessFn = sortAscMap[fKind]
	} else {
		lessFn = sortDscMap[fKind]
	}
	if lessFn == nil {
		var stringer *fmt.Stringer
		if !fTyp.Type.Implements(reflect.TypeOf(stringer).Elem()) {
			fatalf("sort", "cannot sort fields of type %s", fKind)
		}
		lessFn = func(v1, v2 interface{}) bool {
			return v1.(fmt.Stringer).String() < v2.(fmt.Stringer).String()
		}
	}
	return &valueSorter{
		val:   val,
		field: index,
		less:  lessFn,
	}
}

func findField(fieldPath []string, v reflect.Value) reflect.Value {
	f := v
	for _, seg := range fieldPath {
		f = f.FieldByName(seg)
		if f.Kind() == reflect.Ptr {
			f = reflect.Indirect(f)
		}
	}
	return f
}

func findFieldType(fnName string, fieldPath []string, t reflect.Type) reflect.Type {
	f := t
	for _, seg := range fieldPath {
		sf, found := f.FieldByName(seg)
		if !found {
			fatalf(fnName, "Field %s not found", seg)
		}
		f = sf.Type
		if f.Kind() == reflect.Ptr {
			f = f.Elem()
		}
	}
	return f
}

func filterField(fnName string, obj interface{}, field, val string, cmp func(string, string) bool) interface{} {
	defer func() {
		err := recover()
		if err != nil {
			fatalf(fnName, "Invalid use of filter: %v", err)
		}
	}()

	list := getValue(obj)
	filtered := reflect.MakeSlice(list.Type(), 0, list.Len())

	fieldPath := strings.Split(field, ".")

	for i := 0; i < list.Len(); i++ {
		v := list.Index(i)
		if v.Kind() == reflect.Ptr {
			v = reflect.Indirect(v)
		}

		f := findField(fieldPath, v)

		strVal := fmt.Sprintf("%v", f.Interface())
		if cmp(strVal, val) {
			filtered = reflect.Append(filtered, list.Index(i))
		}
	}

	return filtered.Interface()
}

func filterByField(obj interface{}, field, val string) interface{} {
	return filterField("filter", obj, field, val, func(a, b string) bool {
		return a == b
	})
}

func filterByContains(obj interface{}, field, val string) interface{} {
	return filterField("filterContains", obj, field, val, strings.Contains)
}

func filterByFolded(obj interface{}, field, val string) interface{} {
	return filterField("filterFolded", obj, field, val, strings.EqualFold)
}

func filterByHasPrefix(obj interface{}, field, val string) interface{} {
	return filterField("filterHasPrefix", obj, field, val, strings.HasPrefix)
}

func filterByHasSuffix(obj interface{}, field, val string) interface{} {
	return filterField("filterHasSuffix", obj, field, val, strings.HasSuffix)
}

func filterByRegexp(obj interface{}, field, val string) interface{} {
	return filterField("filterRegexp", obj, field, val, func(a, b string) bool {
		matched, err := regexp.MatchString(b, a)
		if err != nil {
			fatalf("filter", "Invalid regexp: %v", err)
		}
		return matched
	})
}

func selectFieldBase(obj interface{}, field, format string) string {
	defer func() {
		err := recover()
		if err != nil {
			fatalf("select", "Invalid use of select: %v", err)
		}
	}()

	var b bytes.Buffer
	list := getValue(obj)

	fieldPath := strings.Split(field, ".")

	for i := 0; i < list.Len(); i++ {
		v := list.Index(i)
		if v.Kind() == reflect.Ptr {
			v = reflect.Indirect(v)
		}

		f := findField(fieldPath, v)

		fmt.Fprintf(&b, format+"\n", f.Interface())
	}

	return string(b.Bytes())
}

func selectField(obj interface{}, field string) string {
	return selectFieldBase(obj, field, "%v")
}

func selectFieldAlt(obj interface{}, field string) string {
	return selectFieldBase(obj, field, "%#v")
}

func toJSON(obj interface{}) string {
	b, err := json.MarshalIndent(obj, "", "\t")
	if err != nil {
		return ""
	}
	return string(b)
}

func toCSV(obj interface{}, skipHeader ...bool) string {
	var data [][]string
	var buf bytes.Buffer

	data, ok := obj.([][]string)
	if ok {
		_ = csv.NewWriter(&buf).WriteAll(data)
		return buf.String()
	}

	assertCollectionOfStructs("toCSV", reflect.ValueOf(obj))
	v := reflect.ValueOf(obj)
	data = make([][]string, 0, v.Len()+1)
	if len(skipHeader) == 0 || !skipHeader[0] {
		styp := v.Type().Elem()
		if styp.Kind() == reflect.Ptr {
			styp = styp.Elem()
		}
		var row []string
		for i := 0; i < styp.NumField(); i++ {
			field := styp.Field(i)
			if field.PkgPath != "" {
				continue
			}
			row = append(row, field.Name)
		}
		data = append(data, row)
	}
	for i := 0; i < v.Len(); i++ {
		var row []string
		s := v.Index(i)
		if s.Kind() == reflect.Ptr {
			s = s.Elem()
		}
		for j := 0; j < s.NumField(); j++ {
			field := s.Field(j)
			if s.Type().Field(j).PkgPath != "" {
				continue
			}
			row = append(row, fmt.Sprintf("%v", field.Interface()))
		}
		data = append(data, row)
	}

	_ = csv.NewWriter(&buf).WriteAll(data)
	return buf.String()
}

func assertCollectionOfStructs(fnName string, v reflect.Value) {
	typ := v.Type()
	kind := typ.Kind()
	if kind != reflect.Slice && kind != reflect.Array {
		fatalf(fnName, "slice or an array of structs or pointers to structs expected")
	}
	styp := typ.Elem()
	if !(styp.Kind() == reflect.Struct ||
		(styp.Kind() == reflect.Ptr && styp.Elem().Kind() == reflect.Struct)) {
		fatalf(fnName, "slice or an array of structs or pointers to structs expected")
	}
}

func getTableHeadings(fnName string, v reflect.Value) []tableHeading {
	assertCollectionOfStructs(fnName, v)

	typ := v.Type()
	styp := typ.Elem()
	if styp.Kind() == reflect.Ptr {
		styp = styp.Elem()
	}

	var headings []tableHeading
	for i := 0; i < styp.NumField(); i++ {
		field := styp.Field(i)
		if field.PkgPath != "" || ignoreKind(field.Type.Kind()) {
			continue
		}
		headings = append(headings, tableHeading{name: field.Name, index: i})
	}

	if len(headings) == 0 {
		fatalf(fnName, "structures must contain at least one exported non-channel field")
	}
	return headings
}

func createTable(v reflect.Value, minWidth, tabWidth, padding int,
	format string, headings []tableHeading) string {
	var b bytes.Buffer
	w := tabwriter.NewWriter(&b, minWidth, tabWidth, padding, ' ', 0)
	for _, h := range headings {
		fmt.Fprintf(w, "%s\t", h.name)
	}
	fmt.Fprintln(w)

	for i := 0; i < v.Len(); i++ {
		el := v.Index(i)
		if el.Kind() == reflect.Ptr {
			el = el.Elem()
		}
		for _, h := range headings {
			fmt.Fprintf(w, format+"\t", el.Field(h.index).Interface())
		}
		fmt.Fprintln(w)
	}
	_ = w.Flush()

	return b.String()
}

func createHTable(v reflect.Value, minWidth, tabWidth, padding int,
	format string, headings []tableHeading) string {
	var b bytes.Buffer
	w := tabwriter.NewWriter(&b, minWidth, tabWidth, padding, ' ', 0)
	for i := 0; i < v.Len(); i++ {
		if i > 0 {
			fmt.Fprintln(w)
		}
		for _, h := range headings {
			fmt.Fprintf(w, "%s:\t", h.name)
			el := v.Index(i)
			if el.Kind() == reflect.Ptr {
				el = el.Elem()
			}
			fmt.Fprintf(w, format+"\t", el.Field(h.index).Interface())
			fmt.Fprintln(w)
		}
	}
	_ = w.Flush()

	return b.String()
}

func table(obj interface{}) string {
	val := getValue(obj)
	return createTable(val, 8, 8, 1, "%v", getTableHeadings("table", val))
}

func tableAlt(obj interface{}) string {
	val := getValue(obj)
	return createTable(val, 8, 8, 1, "%#v", getTableHeadings("table", val))
}

func xHeadings(fnName string, val reflect.Value, userHeadings []string) []tableHeading {
	headings := getTableHeadings(fnName, val)
	if len(headings) < len(userHeadings) {
		fatalf(fnName, "Too many headings specified.  Max permitted %d got %d",
			len(headings), len(userHeadings))
	}
	for i := range userHeadings {
		headings[i].name = userHeadings[i]
	}
	return headings
}

func tablex(obj interface{}, minWidth, tabWidth, padding int, userHeadings ...string) string {
	val := getValue(obj)
	headings := xHeadings("tablex", val, userHeadings)
	return createTable(val, minWidth, tabWidth, padding, "%v", headings)
}

func tablexAlt(obj interface{}, minWidth, tabWidth, padding int, userHeadings ...string) string {
	val := getValue(obj)
	headings := xHeadings("tablexalt", val, userHeadings)
	return createTable(val, minWidth, tabWidth, padding, "%#v", headings)
}

func htable(obj interface{}) string {
	val := getValue(obj)
	return createHTable(val, 8, 8, 1, "%v", getTableHeadings("htable", val))
}

func htableAlt(obj interface{}) string {
	val := getValue(obj)
	return createHTable(val, 8, 8, 1, "%#v", getTableHeadings("htablealt", val))
}

func htablex(obj interface{}, minWidth, tabWidth, padding int, userHeadings ...string) string {
	val := getValue(obj)
	headings := xHeadings("htablex", val, userHeadings)
	return createHTable(val, minWidth, tabWidth, padding, "%v", headings)
}

func htablexAlt(obj interface{}, minWidth, tabWidth, padding int, userHeadings ...string) string {
	val := getValue(obj)
	headings := xHeadings("htablexalt", val, userHeadings)
	return createHTable(val, minWidth, tabWidth, padding, "%#v", headings)
}

func cols(obj interface{}, fields ...string) interface{} {
	val := getValue(obj)
	assertCollectionOfStructs("cols", val)
	if len(fields) == 0 {
		fatalf("cols", "at least one column name must be specified")
	}

	var newFields []reflect.StructField
	var indicies []int
	styp := val.Type().Elem()
	if styp.Kind() == reflect.Ptr {
		styp = styp.Elem()
	}
	for i := 0; i < styp.NumField(); i++ {
		field := styp.Field(i)
		if field.PkgPath != "" || ignoreKind(field.Type.Kind()) {
			continue
		}

		var j int
		for j = 0; j < len(fields); j++ {
			if fields[j] == field.Name {
				break
			}
		}
		if j == len(fields) {
			continue
		}

		indicies = append(indicies, i)
		newFields = append(newFields, field)
	}

	if len(indicies) != len(fields) {
		fatalf("cols", "not all column names are valid")
	}

	newStyp := reflect.StructOf(newFields)
	newVal := reflect.MakeSlice(reflect.SliceOf(newStyp), val.Len(), val.Len())
	for i := 0; i < val.Len(); i++ {
		sval := val.Index(i)
		if sval.Kind() == reflect.Ptr {
			sval = sval.Elem()
		}
		newSval := reflect.New(newStyp).Elem()
		for j, origIndex := range indicies {
			newSval.Field(j).Set(sval.Field(origIndex))
		}
		newVal.Index(i).Set(newSval)
	}

	return newVal.Interface()
}

func sortSlice(obj interface{}, field string, direction ...string) interface{} {
	ascending := true
	if len(direction) > 1 {
		fatalf("sort", "Too many parameters passed to sort")
	} else if len(direction) == 1 {
		if direction[0] == "dsc" {
			ascending = false
		} else if direction[0] != "asc" {
			fatalf("sort", "direction parameter must be \"asc\" or \"dsc\"")
		}
	}

	val := getValue(obj)
	assertCollectionOfStructs("sort", val)

	copy := reflect.MakeSlice(reflect.SliceOf(val.Type().Elem()), 0, val.Len())
	for i := 0; i < val.Len(); i++ {
		copy = reflect.Append(copy, val.Index(i))
	}

	newobj := copy.Interface()
	vs := newValueSorter(newobj, field, ascending)
	sort.Sort(vs)
	return newobj
}

func rows(obj interface{}, rows ...int) interface{} {
	val := getValue(obj)
	typ := val.Type()
	kind := typ.Kind()
	if kind != reflect.Slice && kind != reflect.Array {
		fatalf("rows", "slice or an array of expected")
	}

	if len(rows) == 0 {
		fatalf("rows", "at least one row index must be specified")
	}

	copy := reflect.MakeSlice(reflect.SliceOf(val.Type().Elem()), 0, len(rows))
	for _, row := range rows {
		if row < val.Len() {
			copy = reflect.Append(copy, val.Index(row))
		}
	}

	return copy.Interface()
}

func assertSliceAndRetrieveCount(fnName string, obj interface{}, count ...int) (reflect.Value, int) {
	val := getValue(obj)
	typ := val.Type()
	kind := typ.Kind()
	if kind != reflect.Slice && kind != reflect.Array {
		fatalf(fnName, "slice or an array of expected")
	}

	rows := 1
	if len(count) == 1 {
		rows = count[0]
	} else if len(count) > 1 {
		fatalf(fnName, "accepts a maximum of two arguments expected")
	}

	return val, rows
}

func head(obj interface{}, count ...int) interface{} {
	val, rows := assertSliceAndRetrieveCount("head", obj, count...)
	copy := reflect.MakeSlice(reflect.SliceOf(val.Type().Elem()), 0, rows)
	for i := 0; i < rows && i < val.Len(); i++ {
		copy = reflect.Append(copy, val.Index(i))
	}

	return copy.Interface()
}

func tail(obj interface{}, count ...int) interface{} {
	val, rows := assertSliceAndRetrieveCount("tail", obj, count...)
	copy := reflect.MakeSlice(reflect.SliceOf(val.Type().Elem()), 0, rows)
	start := val.Len() - rows
	if start < 0 {
		start = 0
	}
	for i := start; i < val.Len(); i++ {
		copy = reflect.Append(copy, val.Index(i))
	}

	return copy.Interface()
}

func promote(obj interface{}, field string) interface{} {
	defer func() {
		err := recover()
		if err != nil {
			fatalf("promote", "Invalid use of promote: %v", err)
		}
	}()

	if len(strings.TrimSpace(field)) == 0 {
		fatalf("promote", "Empty field specifier given")
	}

	fieldPath := strings.Split(field, ".")

	val := getValue(obj)
	assertCollectionOfStructs("promote", val)

	ftype := val.Type().Elem()
	if ftype.Kind() == reflect.Ptr {
		ftype = ftype.Elem()
	}
	ftype = findFieldType("promote", fieldPath, ftype)

	rows := val.Len()
	copy := reflect.MakeSlice(reflect.SliceOf(ftype), 0, rows)
	for i := 0; i < rows; i++ {
		el := val.Index(i)
		if el.Kind() == reflect.Ptr {
			el = reflect.Indirect(el)
		}
		el = findField(fieldPath, el)
		copy = reflect.Append(copy, el)
	}

	return copy.Interface()
}

func sliceof(obj interface{}) interface{} {
	val := reflect.ValueOf(obj)
	sl := reflect.MakeSlice(reflect.SliceOf(val.Type()), 0, 1)
	sl = reflect.Append(sl, val)
	return sl.Interface()
}

func describe(obj interface{}) string {
	var buf bytes.Buffer
	generateIndentedUsage(&buf, obj)
	return buf.String()
}

func sanitizeName(name string) string {
	var buf bytes.Buffer

	name = strings.TrimSpace(name)
	if name == "" {
		return name
	}

	rune, len := utf8.DecodeRuneInString(name)
	if !unicode.IsLetter(rune) {
		_, _ = buf.WriteRune('X')
	} else {
		_, _ = buf.WriteRune(unicode.ToTitle(rune))
		name = name[len:]
	}

	for _, rune := range name {
		if !unicode.IsLetter(rune) && !unicode.IsDigit(rune) {
			rune = '_'
		}
		_, _ = buf.WriteRune(rune)
	}

	return buf.String()
}

func guessType(v string) reflect.Type {
	if p, err := strconv.Atoi(v); err == nil {
		return reflect.TypeOf(p)
	}
	if p, err := strconv.ParseFloat(v, 64); err == nil {
		return reflect.TypeOf(p)
	}
	return reflect.TypeOf("")
}

func toTable(data [][]string) interface{} {
	defer func() {
		err := recover()
		if err != nil {
			fatalf("promote", "Invalid use of toTable: %v", err)
		}
	}()

	if len(data) < 2 {
		panic("Expected at least two rows")
	}

	var fields []reflect.StructField
	for _, f := range data[0] {
		fields = append(fields, reflect.StructField{
			Name: sanitizeName(f),
		})
	}

	for i, v := range data[1] {
		fields[i].Type = guessType(v)
	}

	sTyp := reflect.StructOf(fields)
	newVal := reflect.MakeSlice(reflect.SliceOf(sTyp), len(data)-1, len(data)-1)
	for i, row := range data[1:] {
		sVal := reflect.New(sTyp)
		for j, v := range row {
			f := sVal.Elem().Field(j)
			switch f.Kind() {
			case reflect.Int:
				num, err := strconv.Atoi(v)
				if err != nil {
					panic(fmt.Sprintf("integer expected found %s at (%d, %d)", v, j, i))
				}
				f.Set(reflect.ValueOf(num))
			case reflect.Float64:
				num, err := strconv.ParseFloat(v, 64)
				if err != nil {
					panic(fmt.Sprintf("float expected found %s at (%d, %d)", v, j, i))
				}
				f.Set(reflect.ValueOf(num))
			default:
				f.Set(reflect.ValueOf(v))
			}
		}
		newVal.Index(i).Set(sVal.Elem())
	}

	return newVal.Interface()
}