Files
HackBrowserData/internal/export/reflect.go
T
Roger 0ed920f846 docs: trim code comments to the why (#676)
Comments that restated names or narrated the code are gone, and multi-line ones are cut to a line of why.
Only comments change: each edited Go file has the same token stream as before. winapi and abe come later.
2026-11-02 00:03:03 +08:00

83 lines
1.5 KiB
Go

package export
import (
"fmt"
"reflect"
"strconv"
"strings"
"time"
)
var timeType = reflect.TypeOf(time.Time{})
func structCSVHeader(v any) []string {
t := reflect.Indirect(reflect.ValueOf(v)).Type()
headers := make([]string, 0, t.NumField())
for i := 0; i < t.NumField(); i++ {
name := tagName(t.Field(i), "csv")
if name == "" {
continue
}
headers = append(headers, name)
}
return headers
}
func structCSVRow(v any) []string {
val := reflect.Indirect(reflect.ValueOf(v))
t := val.Type()
row := make([]string, 0, t.NumField())
for i := 0; i < t.NumField(); i++ {
if tagName(t.Field(i), "csv") == "" {
continue
}
row = append(row, fieldToString(val.Field(i)))
}
return row
}
func tagName(f reflect.StructField, key string) string {
tag, ok := f.Tag.Lookup(key)
if !ok || tag == "-" {
return ""
}
if idx := strings.IndexByte(tag, ','); idx != -1 {
tag = tag[:idx]
}
if tag == "" {
return ""
}
return tag
}
func fieldToString(v reflect.Value) string {
if v.Type() == timeType {
t, _ := v.Interface().(time.Time)
return formatTime(t)
}
switch v.Kind() {
case reflect.String:
return v.String()
case reflect.Bool:
return formatBool(v.Bool())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.FormatInt(v.Int(), 10)
default:
return fmt.Sprintf("%v", v.Interface())
}
}
func formatTime(t time.Time) string {
if t.IsZero() {
return ""
}
return t.Format(time.RFC3339)
}
func formatBool(b bool) string {
if b {
return "true"
}
return "false"
}