my-log/models/entry.go

180 lines
3.4 KiB
Go

package models
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"regexp"
"strings"
"sync"
"time"
)
const DateFormat = "January 02, 2006 at 03:04:05PM -0700"
type Entry struct {
Title string
Date time.Time
Fields []Meta
}
type metaRes struct {
out []byte
err error
}
func (e Entry) getFieldMarshalChan() chan metaRes {
size := len(e.Fields)
ch := make(chan metaRes, size)
var wg sync.WaitGroup
// @todo figure out a way to handle json field
for i := 0; i < size; i++ {
wg.Add(1)
go func(m Meta) {
defer wg.Done()
o, er := m.MarshalText()
ch <- metaRes{o, er}
}(e.Fields[i])
}
go func() {
wg.Wait()
close(ch)
}()
return ch
}
func (e Entry) MarshalText() ([]byte, error) {
e.Title = strings.TrimSpace(e.Title)
if e.Title == "" {
return []byte{}, ErrorMissingTitle
}
if e.Date == (time.Time{}) {
return []byte{}, ErrorMissingDate
}
ch := e.getFieldMarshalChan()
buff := &bytes.Buffer{}
buff.WriteString("@begin ")
buff.WriteString(e.Date.Format(DateFormat))
buff.WriteString(" - ")
buff.WriteString(e.Title)
for res := range ch {
if res.err == nil && len(res.out) > 0 {
buff.WriteString("\n")
buff.Write(res.out)
}
}
buff.WriteString(" @end")
return buff.Bytes(), nil
}
func (m *Entry) UnmarshalText(in []byte) error {
re := regexp.MustCompile("(?s)^@begin (.+) - (.+?)[ \n]@")
match := re.FindSubmatch(in)
if len(match) == 0 {
return newParsingError(errors.New("Failed to find title and date"))
}
ch := m.getFieldUnarshalChan(in)
title := bytes.TrimSpace(match[2])
if len(title) == 0 {
return ErrorMissingTitle
}
m.Title = string(title)
date := string(bytes.TrimSpace(match[1]))
if date == "" {
return ErrorMissingDate
}
d, e := time.Parse(time.RFC3339, date)
if e != nil {
d, e = time.Parse(DateFormat, date)
if e != nil {
return newParsingError(e)
}
}
m.Date = d
for meta := range ch {
m.Fields = append(m.Fields, meta)
}
return nil
}
func scanEntry(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.Index(data, []byte{10, 64}); i > 0 {
return i + 1, data[0:i], nil
}
if atEOF {
end := []byte{32, 64, 101, 110, 100}
token = data
if i := bytes.Index(data, end); i >= 0 {
token = data[0:i]
}
return len(data), token, nil
}
// Request more data.
return 0, nil, nil
}
func (e *Entry) getFieldUnarshalChan(in []byte) chan Meta {
size := len(in) / 3 // rough estimation
ch := make(chan Meta, size)
var wg sync.WaitGroup
read := bytes.NewReader(in)
scan := bufio.NewScanner(read)
scan.Split(scanEntry)
scan.Scan() // throw out first line
// @todo figure out a way to handle json field
for scan.Scan() {
wg.Add(1)
go func(field []byte) {
defer wg.Done()
m := new(Meta)
err := m.UnmarshalText(field)
if err == nil {
ch <- *m
}
}(scan.Bytes())
}
go func() {
wg.Wait()
close(ch)
}()
return ch
}
func (e Entry) MarshalJSON() ([]byte, error) {
if e.Title == "" {
return []byte{}, ErrorMissingTitle
}
if e.Date == (time.Time{}) {
return []byte{}, ErrorMissingDate
}
out := map[string]any{}
out["title"] = e.Title
out["date"] = e.Date.Format(time.RFC3339)
for _, f := range e.Fields {
if _, ok := out[f.Key]; !ok {
out[f.Key] = f.Value
if vt, ok := f.Value.(time.Time); ok {
out[f.Key] = vt.Format(time.RFC3339)
}
}
}
return json.Marshal(out)
}