2015-12-12 04:24:49 +01:00
|
|
|
// Copyright © 2015 Daniele Tricoli <eriol@mornie.org>.
|
|
|
|
// All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2015-11-12 02:08:37 +01:00
|
|
|
package format // import "eriol.xyz/piken/format"
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"reflect"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"eriol.xyz/piken/sql"
|
|
|
|
)
|
|
|
|
|
|
|
|
type TextFormatter struct {
|
|
|
|
baseFormatter
|
|
|
|
Separator string
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewTextFormatter(fields []string, separator string, glyph bool) *TextFormatter {
|
|
|
|
|
|
|
|
return &TextFormatter{
|
|
|
|
baseFormatter: baseFormatter{fields: fields, showGlyph: glyph},
|
|
|
|
Separator: separator}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *TextFormatter) Format(s *sql.UnicodeData) (string, error) {
|
|
|
|
|
|
|
|
var buffer []string
|
|
|
|
|
2015-11-21 19:08:39 +01:00
|
|
|
glyph, err := CodePointToGlyph(s.CodePoint)
|
2015-11-12 02:08:37 +01:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, field := range t.Fields() {
|
|
|
|
r := reflect.ValueOf(s)
|
|
|
|
f := reflect.Indirect(r).FieldByName(field)
|
|
|
|
buffer = append(buffer, f.String())
|
|
|
|
}
|
|
|
|
|
|
|
|
if t.ShowGlyph() {
|
|
|
|
buffer = append(buffer, glyph)
|
|
|
|
}
|
|
|
|
|
|
|
|
return strings.Join(buffer, t.Separator), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Convert an unicode codepoint into a string.
|
2015-11-21 19:08:39 +01:00
|
|
|
func CodePointToGlyph(codepoint string) (string, error) {
|
2015-11-12 02:08:37 +01:00
|
|
|
|
|
|
|
s, err := strconv.ParseInt(codepoint, 16, 32)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("%c", s), nil
|
|
|
|
}
|