~m15o/htmlj

c36dda5901f78f745935dd90c87858c33fda3b6a — m15o 2 years ago 8dda81d master
Better support for dates
2 files changed, 29 insertions(+), 11 deletions(-)

M htmlj.go
M htmlj_test.go
M htmlj.go => htmlj.go +13 -11
@@ 6,6 6,7 @@ import (
	"io"
	"regexp"
	"strings"
	"time"
)

type ValidationError struct {


@@ 19,7 20,7 @@ func (e ValidationError) Error() string {
var re = regexp.MustCompile(`\d\d\d\d-\d\d-\d\d`)

type Entry struct {
	Published string
	Published time.Time
	Title     string
	Content   string
}


@@ 27,8 28,8 @@ type Entry struct {
type Journal struct {
	Title   string
	Entries []Entry
	Updated string
	Warn    bool // Temporary: will remove when all journals have migrated to use h2
	Updated time.Time
	Warn    bool
}

func Parse(r io.Reader) (*Journal, error) {


@@ 69,14 70,15 @@ func walk(n *html.Node, j *Journal) error {
					return err
				}
			}
			j.Entries = append(j.Entries, Entry{
				Title:     title,
				Published: title[0:10],
				Content:   strings.TrimSpace(b.String()),
			})
			// TODO: remove when all journals have migrated to use h2
			if n.Data == "h1" {
				j.Warn = true
			if dt, err := time.Parse("2006-01-02", title[0:10]); err == nil {
				j.Entries = append(j.Entries, Entry{
					Title:     title,
					Published: dt,
					Content:   strings.TrimSpace(b.String()),
				})
				if n.Data == "h1" {
					j.Warn = true
				}
			}
		}
	}

M htmlj_test.go => htmlj_test.go +16 -0
@@ 3,6 3,7 @@ package htmlj
import (
	"strings"
	"testing"
	"time"
)

const simple = `


@@ 68,3 69,18 @@ func TestParseAdvanced(t *testing.T) {
		t.Fatalf("Error parsing content: got %s instead of <p>Hello world</p>", e.Content)
	}
}

func TestDate(t *testing.T) {
	j, err := Parse(strings.NewReader(simple))
	if err != nil {
		t.Fatal(err)
	}

	dt, err := time.Parse("2006-01-02", "2022-01-01")

	// The entry's publish date should be 2022-01-01
	if j.Entries[0].Published != dt {
		t.Fatalf("Error parsing date: got %s instead of %s",
			j.Entries[0].Published.Format(time.RFC3339), dt.Format(time.RFC3339))
	}
}