mutation

package
v0.1.11 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package mutation provides utilities for reading and writing YAML frontmatter in Markdown note files while preserving key order, scalar styles, and line ending conventions.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CommitMessage

func CommitMessage(req MutationRequest, id string) string

CommitMessage generates a structured commit message based on the operation.

func DetectLineEnding

func DetectLineEnding(raw []byte) string

DetectLineEnding returns "\r\n" if CRLF detected, "\n" otherwise.

func DetectTrailingNewline

func DetectTrailingNewline(raw []byte) bool

DetectTrailingNewline returns true if raw bytes end with a newline.

func GenerateDiff

func GenerateDiff(path string, original, modified string) string

GenerateDiff produces a unified diff string between original and modified.

func NormalizeDates

func NormalizeDates(mapping *yaml.Node, stripTime bool)

NormalizeDates strips the time component from date-field scalar values. When stripTime is false, only midnight timestamps are stripped. When stripTime is true, all time components are removed regardless.

func ParseFrontmatterNode

func ParseFrontmatterNode(raw []byte) (*yaml.Node, int, error)

ParseFrontmatterNode parses raw file bytes into a yaml.Node tree. Returns the document node and the body byte offset (after closing ---\n).

func ScalarToList

func ScalarToList(mapping *yaml.Node, key string) bool

ScalarToList converts a scalar value at the given key into a single-element sequence node. Returns true if a conversion was performed, false otherwise (key absent, value already a sequence, etc.).

func SerializeFrontmatter

func SerializeFrontmatter(doc *yaml.Node, lineEnding string) ([]byte, error)

SerializeFrontmatter marshals the yaml.Node back to YAML bytes, wrapped in --- delimiters, using the specified line ending convention.

func SetKey

func SetKey(mapping *yaml.Node, key string, value interface{}) error

SetKey sets or inserts a key in a yaml.Node mapping. Preserves position of existing keys. New keys are appended at the end.

func SortKeys

func SortKeys(mapping *yaml.Node)

SortKeys sorts the keys of a YAML mapping node: canonical keys first (in canonical order), then remaining keys alphabetically.

func SpliceFile

func SpliceFile(original []byte, newFrontmatter []byte, bodyOffset int) []byte

SpliceFile replaces the frontmatter section in original bytes with newFrontmatter, preserving body bytes untouched. Normalizes gap to exactly one blank line when body has leading blank lines; otherwise preserves body as-is from its first character.

func UnsetKey

func UnsetKey(mapping *yaml.Node, key string) bool

UnsetKey removes a key from a yaml.Node mapping.

func ValidateMutation

func ValidateMutation(req MutationRequest, note ParsedNoteInfo, reg *schema.Registry) error

ValidateMutation checks a MutationRequest against schema rules before any file is modified. It returns a *MutationError with a structured code on failure, or nil when the request is safe to apply.

Types

type FixWikilinksResult

type FixWikilinksResult struct {
	FilesScanned int             `json:"files_scanned"`
	FilesChanged int             `json:"files_changed"`
	LinksFixed   int             `json:"links_fixed"`
	Details      []LinkFixDetail `json:"details,omitempty"`
}

FixWikilinksResult is the output of a FixWikilinks run.

func FixWikilinks(db *index.DB, vaultPath string, fix bool) (*FixWikilinksResult, error)

FixWikilinks scans all .md files in vaultPath and rewrites [[Title]] to [[filename|Title]] wherever Title resolves to a note whose filename stem differs from the link target. When fix is false the function performs a dry-run: it counts and records changes but does not write any files.

type GitInfo

type GitInfo struct {
	RepoDetected     bool   `json:"repo_detected"`
	WorkingTreeClean bool   `json:"working_tree_clean"`
	TargetFileClean  bool   `json:"target_file_clean"`
	CommitSHA        string `json:"commit_sha,omitempty"`
}

GitInfo reports git state in mutation responses.

type KeyRename

type KeyRename struct {
	OldKey string
	NewKey string
}

KeyRename records a key rename performed by SnakeCaseKeys.

func SnakeCaseKeys

func SnakeCaseKeys(mapping *yaml.Node) []KeyRename

SnakeCaseKeys converts camelCase key names in a mapping node to snake_case in-place and returns the list of renames performed.

type LinkFixDetail

type LinkFixDetail struct {
	Path    string `json:"path"`
	OldLink string `json:"old_link"`
	NewLink string `json:"new_link"`
}

LinkFixDetail describes a single wikilink rewrite.

type MutationError

type MutationError struct {
	Code    string
	Message string
	Field   string
}

MutationError is a structured error with an SRS error code.

func (*MutationError) Error

func (e *MutationError) Error() string

type MutationRequest

type MutationRequest struct {
	Op         OpType
	Target     string
	Key        string
	Value      interface{}
	Fields     map[string]interface{}
	DryRun     bool
	Diff       bool
	Commit     bool
	AllowExtra bool
	StripTime  bool
}

MutationRequest describes what to mutate.

type MutationResult

type MutationResult struct {
	Path            string          `json:"path"`
	ID              string          `json:"id"`
	Operation       string          `json:"operation"`
	Key             string          `json:"key,omitempty"`
	OldValue        interface{}     `json:"old_value,omitempty"`
	NewValue        interface{}     `json:"new_value,omitempty"`
	DryRun          bool            `json:"dry_run"`
	Diff            string          `json:"diff,omitempty"`
	WriteHash       string          `json:"write_hash,omitempty"`
	Git             GitInfo         `json:"git"`
	ReindexRequired bool            `json:"reindex_required"`
	Warnings        []PolicyWarning `json:"warnings"`
}

MutationResult is the JSON response for all mutation commands.

type Mutator

type Mutator struct {
	VaultPath string
	Detector  git.RepoStateDetector
	Checker   *git.PolicyChecker
	Committer *git.Committer
	Registry  *schema.Registry
}

Mutator orchestrates the 7-step mutation pipeline: resolve target -> read file -> validate -> compute change -> generate diff -> atomic write -> post-write.

func (*Mutator) Run

func (m *Mutator) Run(req MutationRequest) (*MutationResult, error)

Run executes the mutation pipeline for the given request.

type OpType

type OpType int

OpType identifies the mutation operation.

const (
	OpSet       OpType = iota // set a single key=value
	OpUnset                   // remove a key
	OpMerge                   // merge multiple key=value pairs
	OpNormalize               // reformat frontmatter
)

func (OpType) String

func (o OpType) String() string

type ParsedNoteInfo

type ParsedNoteInfo struct {
	ID       string
	Type     string
	IsDomain bool
	Keys     []string
}

ParsedNoteInfo holds the minimal note info needed for validation.

type PolicyWarning

type PolicyWarning struct {
	Rule    string `json:"rule"`
	Message string `json:"message"`
}

PolicyWarning describes a git policy warning that was triggered but didn't block.

Jump to

Keyboard shortcuts

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