testmark.go
// Package testmark v2 provides a clean, easy-to-use API for working with testmark documents.
package testmark
import (
"flag"
)
// Global configuration
var defaultRegenFlag = flag.Bool("testmark.regen", false, "regenerate test fixtures")
// ShouldRegen returns whether fixture regeneration is enabled.
func ShouldRegen() bool {
return *defaultRegenFlag
}
// Internal type for positioning info
type hunkInfo struct {
lineStart int
lineEnd int
hunk *Hunk
}
// Hunk represents a single data block within a testmark document.
type Hunk struct {
name string
infoString string
body []byte
}
// Document represents a parsed testmark document.
type Document struct {
original []byte
lines [][]byte
hunks []hunkInfo
hunksByName map[string]*Hunk
dirIndex *DirEntry
patchAccum *PatchAccumulator
autoPatching bool
}
// DirEntry represents a directory-like entry in the testmark document hierarchy.
type DirEntry struct {
name string
path string
hunk *Hunk
children map[string]*DirEntry
childrenOrdered []*DirEntry
}
// PatchAccumulator collects patches for document modification.
type PatchAccumulator struct {
patches []Hunk
}
// Hunk accessor methods
// Name returns the hunk's name.
func (h *Hunk) Name() string {
return h.name
}
// InfoString returns the code block's info string (language hint).
func (h *Hunk) InfoString() string {
return h.infoString
}
// Body returns a copy of the hunk's body bytes.
func (h *Hunk) Body() []byte {
body := make([]byte, len(h.body))
copy(body, h.body)
return body
}
// String returns the body as a string.
func (h *Hunk) String() string {
return string(h.body)
}
// Document accessor methods
// HunkByName returns a hunk by name, or nil if not found.
func (d *Document) HunkByName(name string) *Hunk {
return d.hunksByName[name]
}
// Count returns the number of hunks in the document.
func (d *Document) Count() int {
return len(d.hunks)
}
// Root returns the root directory entry for hierarchical access.
func (d *Document) Root() *DirEntry {
return d.dirIndex
}
// DirEntry accessor methods
// Name returns the entry's name (just the last path segment).
func (e *DirEntry) Name() string {
return e.name
}
// Path returns the full path of this entry.
func (e *DirEntry) Path() string {
return e.path
}
// Hunk returns the hunk associated with this entry, or nil.
func (e *DirEntry) Hunk() *Hunk {
return e.hunk
}
// Child returns a child entry by name, or nil if not found.
func (e *DirEntry) Child(name string) *DirEntry {
return e.children[name]
}
// Hunks returns an iterator over all hunks in document order.
func (d *Document) Hunks() HunkIterator {
return HunkIterator{doc: d, index: 0}
}
// Children returns an iterator over child entries.
func (e *DirEntry) Children() DirIterator {
return DirIterator{entries: e.childrenOrdered, index: 0}
}
v2/testmark.go · 2.9 KiB · 7cd9a20593