1
0
Fork 0
Browse Source

Add format package

main
Daniele Tricoli 7 years ago
parent
commit
61b4c31ecb
  1. 30
      format/formatter.go
  2. 54
      format/text.go
  3. 15
      utils.go

30
format/formatter.go

@ -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

@ -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
}

15
utils.go

@ -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
}

Loading…
Cancel
Save