mdconfig

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2026 License: MIT Imports: 8 Imported by: 0

README

mdconfig

A lightweight, robust Go library designed to parse structured configurations directly from Markdown files. It parses Markdown elements into logical sections, typed tables, standard lists, and task-lists (boolean maps), providing validation with clear, actionable context when data does not conform to the expected schema.

Features

  • Sections as Categories: Headings (#, ##, ###) are interpreted as configuration section boundaries, mapping titles directly to isolated configuration environments.
  • Typed Tables: Automatically parses Markdown tables, allowing you to enforce data types (string, int, float, bool) on columns using the :type suffix.
  • Lists & Checklists:
    • Standard sequential lists (- item) are parsed into lists of strings.
    • Checklists (- [x] key, - [ ] key) are parsed into boolean maps.
  • Config Validation: Validates actual cell contents against declared column schemas, returning structured, detailed errors including section names, row and column indices, expected types, and original values.
  • Stable Serialization: Outputs structured text representation of parsed configurations via AsString(), utilizing deterministic sorted keys for consistent testing and debugging.

Supported Format Example

# Global configuration defined before any heading belongs to the "Root" section.

## services

The services configuration table:
| name:string | enabled:bool | retries:int | timeout:float |
|-------------|--------------|-------------|---------------|
| api         | true         | 3           | 1.5           |
| gateway     | false        | 5           | 5.0           |

## features

- [x] auth
- [ ] billing
- [x] rate_limiting

## hosts

- localhost
- 127.0.0.1

Types and Coercion

Types can be specified inside column headers using the column_name:type suffix. The library supports the following data types:

  • string: No coercion needed. Default type if no suffix is specified.
  • int: Parsed into an int64 using base-10 conversion.
  • float: Parsed into a float64.
  • bool: Parsed into a bool using Go's strconv.ParseBool conventions (true, false, 1, 0, etc.).

Usage Example

package main

import (
	"fmt"
	"log"

	"github.com/konkero-project/mdconfig"
)

func main() {
	markdownData := []byte(`
## app
| port:int | debug:bool | ratio:float |
|----------|------------|-------------|
| 8080     | true       | 0.75        |
`)

	cfg, err := mdconfig.Parse(markdownData)
	if err != nil {
		log.Fatalf("Failed to parse: %v", err)
	}

	// Validate cell values against types
	if err := cfg.Validate(); err != nil {
		if valErr, ok := err.(*mdconfig.ValidationError); ok {
			fmt.Printf("Validation error details:\n")
			fmt.Printf("  Section: %s\n", valErr.Section)
			fmt.Printf("  Table: %s (Index: %d)\n", valErr.TableName, valErr.TableIndex)
			fmt.Printf("  Position: Row %d, Col %d (%q)\n", valErr.RowIndex+1, valErr.ColIndex+1, valErr.ColName)
			fmt.Printf("  Value: %q (Expected: %s)\n", valErr.Value, valErr.ExpectedType)
			fmt.Printf("  Details: %s\n", valErr.Message)
		}
		log.Fatalf("Validation failed: %v", err)
	}

	// Access parsed configuration
	appSection := cfg.Sections["app"]
	table := appSection.Tables[0]
	row := table.Rows[0]

	port := row[0].Typed.(int64)
	debug := row[1].Typed.(bool)
	ratio := row[2].Typed.(float64)

	fmt.Printf("App Port: %d, Debug: %t, Ratio: %f\n", port, debug, ratio)

	// Print stable, deterministic configuration string representation
	fmt.Println(cfg.AsString())
}

Running Tests

Tests are written using the Ginkgo v2 BDD testing framework and Gomega matchers.

To run tests:

make test

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Column

type Column struct {
	// Name is the clean name of the column without any type suffixes.
	Name string
	// Type is the declared column type, defaulting to TypeString if not specified.
	Type ColumnType
}

Column defines the schema of a single table column.

type ColumnType

type ColumnType string

ColumnType represents the parsed data type of a table column.

const (
	// TypeString represents a string column type.
	TypeString ColumnType = "string"
	// TypeInt represents an integer column type.
	TypeInt ColumnType = "int"
	// TypeFloat represents a floating-point column type.
	TypeFloat ColumnType = "float"
	// TypeBool represents a boolean column type.
	TypeBool ColumnType = "bool"
)

type Config

type Config struct {
	// RootSection holds tables, lists, and checklists defined before any Markdown heading.
	RootSection Section
	// Sections maps section heading titles to their respective parsed Section configurations.
	Sections map[string]*Section
}

Config is the root configuration structure containing all parsed Markdown data.

func Parse

func Parse(text []byte) (*Config, error)

Parse processes a Markdown byte slice and returns a structured Config or an error if parsing fails.

func ParseFrom

func ParseFrom(inp io.Reader) (*Config, error)

ParseFrom reads Markdown data from an io.Reader and parses it into a structured Config.

func (*Config) AsString

func (c *Config) AsString() string

AsString generates a stable, deterministic, and highly detailed human-readable textual representation of the entire parsed configuration. It lists the root section first, followed by all other sections sorted alphabetically by their titles. For each section, it outputs its tables (including schemas and cell data with parsed types), sequential lists, and checklists (with keys sorted alphabetically to ensure consistency across separate executions). This is highly useful for debugging and golden-file testing.

func (*Config) String

func (c *Config) String() string

String provides a convenience wrapper over AsString, satisfying the standard fmt.Stringer interface. It returns the stable, human-readable dump of the parsed configuration structure.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks all table cells in the configuration against their schemas and returns any validation errors.

type Section

type Section struct {
	// Title is the heading text that represents the section category name.
	Title string
	// Level is the Markdown heading level (e.g., 1 for #, 2 for ##, etc.).
	Level int
	// Tables is the collection of tables parsed within this section.
	Tables []Table
	// Lists contains ordinary sequential list items grouped by list.
	Lists [][]string
	// BoolLists contains checklist maps representing checklist items and their checked status.
	BoolLists []map[string]bool
}

Section represents a configuration category defined by a Markdown heading.

type Table

type Table struct {
	// Name is the name of the table, typically extracted from the preceding paragraph.
	Name string
	// Columns is the list of columns defining the table's schema.
	Columns []Column
	// Rows contains the table data, where each row is a slice of typed Values corresponding to the columns.
	Rows [][]Value
}

Table represents a parsed Markdown table.

type ValidationError

type ValidationError struct {
	// Section is the title of the section containing the invalid table.
	Section string
	// TableIndex is the 0-based index of the table within its section.
	TableIndex int
	// TableName is the name of the table, if specified.
	TableName string
	// RowIndex is the 0-based index of the row containing the invalid value.
	RowIndex int
	// ColIndex is the 0-based index of the column containing the invalid value.
	ColIndex int
	// ColName is the name of the column containing the invalid value.
	ColName string
	// ExpectedType is the schema type that the value failed to conform to.
	ExpectedType ColumnType
	// Value is the raw string value that caused the validation failure.
	Value string
	// Message is the detailed description of the type conversion failure.
	Message string
}

ValidationError describes an error that occurred while validating a table cell value against its column schema.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error formats the ValidationError into a detailed, human-readable string.

type Value

type Value struct {
	// Raw is the original string value extracted from the Markdown document.
	Raw string
	// Typed contains the validated Go typed value (string, int64, float64, bool) if parsed successfully, or nil otherwise.
	Typed interface{}
}

Value represents a single cell or list item value that holds both its raw string representation and its successfully parsed typed value.

Jump to

Keyboard shortcuts

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