Skip to content

Commit

Permalink
fix: Fix parser failure when the content contains a seperator (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
MaikelVeen authored May 20, 2024
1 parent 37592c7 commit 82a1402
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 17 deletions.
43 changes: 27 additions & 16 deletions parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,40 +15,51 @@ var (
)

const (
numParts = 3
seperatorBytes = 4
)

// Parse reads the content of a source and returns an item.
func Parse(src sourcer.Source) (*item.Item, error) {
c, err := io.ReadAll(src)
if err != nil {
return nil, err
}
defer src.Close()

// FIXME: This is a naive implementation that breaks if the content contains "---\n".

// Split the content into front matter and markdown
parts := bytes.SplitN(c, []byte("---\n"), numParts)
if len(parts) < numParts {
return nil, ErrInvalidFrontMatter
}

// Parse the YAML front matter
var properties map[string]any
err = yaml.Unmarshal(parts[1], &properties)
frontMatter, content, err := extractFrontMatter(c)
if err != nil {
return nil, err
}

// Keep the markdown content as is
content := string(parts[2])
var properties map[string]any
if len(frontMatter) > 0 {
err = yaml.Unmarshal(frontMatter, &properties)
if err != nil {
return nil, err
}
}

return &item.Item{
Name: src.Name(),
Content: content,
Content: string(content),
CreateTime: src.CreatedAt(),
UpdateTime: src.ModifiedAt(),
Properties: properties,
}, nil
}

func extractFrontMatter(content []byte) ([]byte, []byte, error) {
if !bytes.HasPrefix(content, []byte("---\n")) {
return nil, content, nil
}

frontMatterEnd := bytes.Index(content[seperatorBytes:], []byte("\n---\n"))
if frontMatterEnd == -1 {
return nil, nil, ErrInvalidFrontMatter
}

frontMatterEnd += seperatorBytes // Account for the initial "---\n"
frontMatter := content[seperatorBytes:frontMatterEnd]
markdown := content[frontMatterEnd+seperatorBytes:]

return frontMatter, markdown, nil
}
2 changes: 1 addition & 1 deletion parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,6 @@ func TestParse(t *testing.T) {
require.NoError(t, err)
assert.NotNil(t, item)
assert.Equal(t, "test", item.Name)
assert.Equal(t, "# Test\n", item.Content)
assert.Equal(t, "\n# Test\n", item.Content)
assert.Equal(t, map[string]interface{}{"title": "Test"}, item.Properties)
}

0 comments on commit 82a1402

Please sign in to comment.