From 38659f85e52e22667fd11b178969d25863db0ee4 Mon Sep 17 00:00:00 2001 From: Aaron Bieber Date: Wed, 15 Apr 2020 07:39:20 -0600 Subject: [PATCH] Create a test for parsing header info --- internal/{main.go => utils.go} | 45 ++++++++++++++++++++++++++++++++-- internal/utils_test.go | 17 +++++++++++++ 2 files changed, 60 insertions(+), 2 deletions(-) rename internal/{main.go => utils.go} (63%) create mode 100644 internal/utils_test.go diff --git a/internal/main.go b/internal/utils.go similarity index 63% rename from internal/main.go rename to internal/utils.go index 5e74401..f17520f 100644 --- a/internal/main.go +++ b/internal/utils.go @@ -5,6 +5,7 @@ import ( "io/ioutil" "os" "regexp" + "strings" "time" "github.com/google/uuid" @@ -13,8 +14,8 @@ import ( // AuthorRE is a regex to grab our Authors var AuthorRE = regexp.MustCompile(`^author:\s(.*)$`) -// TitleRE matches our article title -var TitleRE = regexp.MustCompile(`^title:\s(.*)$`) +// TitleRE matches our article title for either plain text or org-mode +var TitleRE = regexp.MustCompile(`^(?:\*|title:)\s(.*)$`) // DateRE matches our article date var DateRE = regexp.MustCompile(`^date:\s(.*)$`) @@ -35,6 +36,46 @@ func ReadFileBody(f string) ([]byte, error) { return ioutil.ReadFile(f) } +//ParseHeader grabs the header info out of a string +func ParseHeader(f string) (*Header, error) { + var err error + h := &Header{} + for _, line := range strings.Split(f, "\n") { + if AuthorRE.MatchString(line) { + aline := AuthorRE.ReplaceAllString(line, "$1") + if h.Author == "" { + h.Author = aline + } + } + + if TitleRE.MatchString(line) { + if h.Title == "" { + h.Title = TitleRE.ReplaceAllString(line, "$1") + } + } + + if DateRE.MatchString(line) { + if h.Date.String() == "" { + d := DateRE.ReplaceAllString(line, "$1") + h.Date, err = time.Parse(time.RFC1123, d) + if err != nil { + return nil, err + } + } + } + + if UUIDRE.MatchString(line) { + u := UUIDRE.ReplaceAllString(line, "$1") + h.UUID, err = uuid.Parse(u) + if err != nil { + return nil, err + } + } + } + + return h, nil +} + //ParseFileHeader grabs the header info out of an existing file func ParseFileHeader(f string) (*Header, error) { h := &Header{} diff --git a/internal/utils_test.go b/internal/utils_test.go new file mode 100644 index 0000000..1c769ff --- /dev/null +++ b/internal/utils_test.go @@ -0,0 +1,17 @@ +package cromp + +import "testing" + +func TestParseHeader(t *testing.T) { + const orgHeader = ` +* Thing with many heads +` + h, err := ParseHeader(orgHeader) + if err != nil { + t.Error("parsing", err) + } + + if h.Title != "Thing with many heads" { + t.Errorf("expected 'Thing with many heads'; got: %q\n", h.Title) + } +}