1
0
Fork 0

Add format package

This commit is contained in:
Daniele Tricoli 2015-11-12 02:08:37 +01:00
parent fd442a3a2b
commit 61b4c31ecb
3 changed files with 84 additions and 15 deletions

30
format/formatter.go Normal file
View File

@ -0,0 +1,30 @@
package format // import "eriol.xyz/piken/format"
import "eriol.xyz/piken/sql"
type Formatter interface {
Format(*sql.UnicodeData) (string, error)
}
type baseFormatter struct {
fields []string
showGlyph bool
}
func (df *baseFormatter) SetFields(fields []string) {
for _, field := range fields {
df.fields = append(df.fields, field)
}
}
func (df baseFormatter) Fields() []string {
return df.fields
}
func (df *baseFormatter) SetShowGlyph(value bool) {
df.showGlyph = value
}
func (df baseFormatter) ShowGlyph() bool {
return df.showGlyph
}

54
format/text.go Normal file
View File

@ -0,0 +1,54 @@
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
glyph, err := codePointToGlyph(s.CodePoint)
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.
func codePointToGlyph(codepoint string) (string, error) {
s, err := strconv.ParseInt(codepoint, 16, 32)
if err != nil {
return "", err
}
return fmt.Sprintf("%c", s), nil
}

View File

@ -2,11 +2,9 @@ package main // import "eriol.xyz/piken"
import (
"encoding/csv"
"fmt"
"io"
"net/http"
"os"
"strconv"
"time"
"github.com/Sirupsen/logrus"
@ -53,7 +51,6 @@ func download(url, output string) error {
}
return nil
}
// Get user home directory or exit with a fatal error.
@ -84,16 +81,4 @@ func readCsvFile(filepath string) (records [][]string, err error) {
}
return records, nil
}
// Convert an unicode codepoint into a string.
func codePointToGlyph(codepoint string) (string, error) {
s, err := strconv.ParseInt(codepoint, 16, 32)
if err != nil {
return "", err
}
return fmt.Sprintf("%c", s), nil
}