parse

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 8, 2026 License: MIT Imports: 24 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package parse turns a raw document into text plus the structure the rest of the pipeline needs: section boundaries a splitter can respect, link targets, and — for tabular and tree formats — the decoded value itself.

A Format reads one format and is registered under a short name. Any picks that name from Doc.Meta["format"] when the ingester already knew it, and otherwise from the document's extension and the shape of its text, so a pipeline that does not know what it is reading still needs only one parser.

Formats whose decoders are not in the standard library — pdf, docx, xlsx, pptx — are registered as placeholders that fail with ErrFormat. Supplying a reader is one Register call under the same name; nothing else changes.

Parsing never opens a file. Turning a source into a Doc is ingest's job; what parse reads is Doc.Text. Parsing also does not touch the caller's Doc: the returned Doc carries a copy of Meta.

Formats record what they found in Doc.Meta under these keys. Read them with the accessors rather than asserting the types by hand:

format    string             the format that read the document
title     string             document title, where the format carries one
sections  []Section          spans of Doc.Text
links     []Link             link targets
images    []Link             image targets, alt text as the link text
tags      map[string]string  the document's own metadata pairs
fields    []string           column names (csv, tsv)
data      any                decoded value: JSON any, CSV []map[string]string, XML *Node

Index

Constants

This section is empty.

Variables

View Source
var ErrFormat = errors.New("no reader for format")

ErrFormat reports a format this package can name but not read, either because no reader is registered under that name or because the format's decoder is not in the standard library. Register supplies one.

Functions

func Data

func Data(d semantic.Doc) any

Data returns the decoded value of a structured document: any for JSON, []map[string]string for CSV, *Node for XML, nil for prose.

func Detect

func Detect(d semantic.Doc) string

Detect names the format of d, from the extension of its source when that says anything and from the shape of its text otherwise. It falls back to "text", which reads anything.

func Fields

func Fields(d semantic.Doc) []string

Fields returns the column names of a delimited document.

func Flatten

func Flatten(v any) map[string]any

Flatten reduces a decoded JSON value to its leaves, keyed by path: object keys and array indices joined by ".". An empty object or array has no leaves and so contributes nothing.

func Names

func Names() []string

Names lists the registered format names in order.

func Register

func Register(name string, f Format)

Register makes f the reader for name, replacing whatever held that name.

func Tags

func Tags(d semantic.Doc) map[string]string

Tags returns the document's own metadata pairs: HTML meta elements by name or property, Markdown front matter by key.

func Title

func Title(d semantic.Doc) string

Title returns the document title, empty when the format carries none.

Types

type Any

type Any struct{}

Any parses whatever the document turns out to be. It takes the format from Doc.Meta["format"] when the ingester set one and otherwise detects it, so a pipeline reading a mixed corpus needs only this one parser.

func (Any) Parse

func (Any) Parse(ctx context.Context, d semantic.Doc) (semantic.Doc, error)

Parse detects the document's format and hands it to the registered reader.

type CSV

type CSV struct {
	// Sep is the field separator. Zero takes it from the document.
	Sep rune
	// Bare says the document has no header row, so its fields are numbered
	// from one.
	Bare bool
}

CSV reads delimited text. The header row names the fields, the rows become the decoded value, and the text becomes one "field: value" line per cell — which is what gives a splitter and an extractor something to work on, since a grid of bare cells says nothing about what the cells mean.

One reader covers the family. Sep set to a tab reads TSV; Sep left at zero takes the separator from the document, which is what a file named .csv but written with semicolons needs.

Rows come back rectangular: every field the header named is present in every row, empty where the row had no cell. Empty cells contribute no text, an empty cell being nothing to assert, so a row of them is no section.

func (CSV) Parse

func (c CSV) Parse(_ context.Context, d semantic.Doc) (semantic.Doc, error)

Parse reads the rows and renders their cells as "field: value" lines.

type Email

type Email struct{}

Email reads a mail message. Its headers become the tags, decoded, so a subject written in another script arrives as words rather than as an encoded word; the subject becomes the title; the body becomes the text, one section per part, titled with the part's media type.

A multipart/alternative holds one message written more than once, so only its plainest part is read. An HTML part is read as HTML, which keeps its markup out of the text and puts its link targets in Links. Parts that are not text — the attachments — are not read: their bytes are a different document, and ingest is what turns a source into one.

func (Email) Parse

func (Email) Parse(ctx context.Context, d semantic.Doc) (semantic.Doc, error)

Parse reads the message's headers and the text of its body.

type Format

type Format interface {
	Parse(context.Context, semantic.Doc) (semantic.Doc, error)
}

Format reads one document format: it returns the document with its text normalized and what it found recorded in Meta.

func Get

func Get(name string) (Format, bool)

Get returns the Format registered under name.

type HTML

type HTML struct {
	// Base resolves relative link and image targets. When it is empty the
	// document's own <base href> is used, and failing that its Source.
	Base string
}

HTML strips the markup and keeps what the markup meant: the text with its block structure as line breaks, a section per heading, the link and image targets, the title, and the meta elements as tags. Script, style and template content is dropped rather than read as prose.

The scanner is tolerant by design — unclosed tags, stray angle brackets and unquoted attributes are all common in the wild, and a document that a strict parser rejects is exactly the one an ingest pipeline still has to read.

func (HTML) Parse

func (h HTML) Parse(_ context.Context, d semantic.Doc) (semantic.Doc, error)

Parse extracts the document's text, headings, links and metadata.

type JSON

type JSON struct{}

JSON reads JSON and, without being told, the line-delimited form: it decodes values until the input runs out, so one object and a stream of records are the same code path. The decoded value goes in Meta as data; the text becomes one "path: value" line per leaf, which is what makes a JSON document something a splitter and an extractor can work on at all. Each record of a stream is a section.

Numbers keep the digits they were written with rather than becoming floats.

func (JSON) Parse

func (JSON) Parse(_ context.Context, d semantic.Doc) (semantic.Doc, error)

Parse decodes the document and renders its leaves as text.

type Link struct {
	Text string
	URL  string
}

Link is one target and the text that pointed at it. For an image the text is the alt attribute.

func Images

func Images(d semantic.Doc) []Link

Images returns the image targets a format found in d.

func Links(d semantic.Doc) []Link

Links returns the link targets a format found in d.

type Markdown

type Markdown struct{}

Markdown reads Markdown. The text it returns is the source with any front matter removed — nothing is rewritten, so a reader still sees the emphasis and the code the author wrote — and the structure the source declares comes back in Meta: a section per heading, the links and images, and the front matter as tags.

Headings and links inside a fenced code block are code, not structure, and are ignored.

func (Markdown) Parse

Parse splits the document at its headings and collects its links.

type Node

type Node struct {
	Name  string            // local name, without its namespace prefix
	Space string            // namespace URI, empty when the element is in none
	Attr  map[string]string // attributes by local name
	Text  string            // the element's own character data, spacing collapsed
	Nodes []*Node
}

Node is one element: its name, the namespace it is in, its attributes, the character data it holds directly, and the elements inside it.

func (*Node) Find

func (n *Node) Find(name string) []*Node

Find returns every element named name in document order, n itself included.

type Section

type Section struct {
	Title string
	Level int
	Start int
	End   int
}

Section is a span of Doc.Text that stands on its own: a heading and the body under it, a CSV row, a JSON record, a child of an XML root. Start and End are byte offsets into Doc.Text, so a splitter can respect boundaries it did not compute itself. Sections neither nest nor overlap.

func Sections

func Sections(d semantic.Doc) []Section

Sections returns the spans a format found in d.

func (Section) Text

func (s Section) Text(d semantic.Doc) string

Text returns the span of d.Text that s covers, or "" when s does not fit it.

type Text

type Text struct{}

Text is the plain-text format. It normalizes line endings and leaves the content alone, recording no sections: prose has no boundaries the document declares, and inventing them here would compete with the splitter's own rule for dividing it.

func (Text) Parse

func (Text) Parse(_ context.Context, d semantic.Doc) (semantic.Doc, error)

Parse normalizes the document's line endings.

type XML

type XML struct{}

XML reads XML into a tree and lays that tree out as text: one "path: text" line per element that carries character data, and one "path@name: value" line per attribute, the path being the element names from the root down. Siblings that share a name are numbered, so two <item> elements do not land on the same lines.

The tree itself comes back as Data, since the document's shape is the point of writing it in XML at all. Each child of the root is a section, which for the two feed vocabularies is one section per entry.

Reading is tolerant of what documents in the wild get wrong: a missing end tag is supplied, an unquoted attribute value is read, an unknown entity is left as it was written, and the encoding named in the prolog is ignored, ingest having decoded the bytes to UTF-8 long before parse sees them. A document that ends in the middle of an element is an error, since half a tree is not a smaller tree.

func (XML) Parse

func (XML) Parse(_ context.Context, d semantic.Doc) (semantic.Doc, error)

Parse reads the document's elements and lays them out as text.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL