renderer

package
v0.0.78 Latest Latest
Warning

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

Go to latest
Published: Jun 18, 2026 License: Apache-2.0 Imports: 27 Imported by: 1

Documentation

Index

Constants

View Source
const (
	RefTypeComponentSchema         ReferenceType = "schema"
	RefTypeComponentParameter      ReferenceType = "parameter"
	RefTypeComponentHeader         ReferenceType = "header"
	RefTypeComponentResponse       ReferenceType = "response"
	RefTypeComponentRequestBody    ReferenceType = "requestBody"
	RefTypeComponentSecurityScheme ReferenceType = "securityScheme"
	RefTypeComponentExample        ReferenceType = "example"
	RefTypeComponentLink           ReferenceType = "link"
	RefTypeComponentCallback       ReferenceType = "callback"
	RefTypeOther                   ReferenceType = "other"
	Breaking                       string        = "**(💔 breaking)**"
)
View Source
const (
	// TreeBranch Branch symbols
	TreeBranch     = "├──" // Non-last child, leaf node
	TreeLastBranch = "└──" // Last child, leaf node

	// TreeBranchDown Branch symbols with children
	TreeBranchDown     = "├─┬" // Non-last child, has children
	TreeLastBranchDown = "└─┬" // Last child, has children

	// TreeVertical Prefix continuation
	TreeVertical = "│ " // Continue vertical line from parent
	TreeEmpty    = "  " // No vertical line (parent was last child)
)

Tree structure symbols for ASCII tree rendering

Variables

View Source
var (
	// ErrHTMLNotSupported indicates the renderer doesn't support HTML output.
	ErrHTMLNotSupported = errors.New("HTML rendering not supported by this renderer")

	// ErrMarkdownNotSupported indicates the renderer doesn't support markdown output.
	ErrMarkdownNotSupported = errors.New("markdown rendering not supported by this renderer")

	// ErrInvalidInput indicates the render input is nil or missing required fields.
	ErrInvalidInput = errors.New("invalid render input: missing required fields")
)
View Source
var ASCIISymbols = ChangeSymbols{
	Modified: "[M]",
	Added:    "[+]",
	Removed:  "[-]",
	Breaking: "{X}",
}

ASCIISymbols uses plain ASCII characters for terminal/non-markdown rendering

View Source
var MarkdownSymbols = ChangeSymbols{
	Modified: "[🔀]",
	Added:    "[➕]",
	Removed:  "[➖]",
	Breaking: "❌",
}

MarkdownSymbols uses emoji for markdown/GitHub rendering

Functions

func ConvertJSONToYAML

func ConvertJSONToYAML(jsonStr string) (string, bool)

ConvertJSONToYAML converts a JSON string to YAML format.

func FormatAsCodeBlock

func FormatAsCodeBlock(value string, format StructuredDataFormat) string

FormatAsCodeBlock wraps a value in a markdown code fence with the appropriate language.

func FormatExtensionValue

func FormatExtensionValue(value string) (formatted string, isCodeBlock bool)

FormatExtensionValue formats an extension value for display. If the value is structured data (JSON/YAML/XML), it returns a code block.

func FormatExtensionValueWithTargetFormat

func FormatExtensionValueWithTargetFormat(value string, targetFormat StructuredDataFormat) (formatted string, isCodeBlock bool)

FormatExtensionValueWithTargetFormat formats an extension value with a target output format. If the value is JSON but targetFormat is YAML, it converts JSON → YAML. This is used when the source document is YAML but libopenapi serializes values as JSON.

func FormatObjectType

func FormatObjectType(objType string) string

FormatObjectType formats an object type for display. It converts internal type identifiers (e.g., "requestBody", "mediaType") to human-readable display names (e.g., "Request Body", "Media Type").

func FormatValue

func FormatValue(value string) string

FormatValue formats a value for display, handling multi-line values.

func IndentCodeBlock

func IndentCodeBlock(codeBlock string, indentSpaces int) string

IndentCodeBlock adds indentation to each line of a code block (including fences). preserves the code block structure while making it part of a list continuation.

func ShouldFormatAsBlock

func ShouldFormatAsBlock(value string) bool

ShouldFormatAsBlock determines if a value should be rendered as a code block. For extensions, we always format structured data as code blocks (no size limits).

Types

type BreakingConfig

type BreakingConfig struct {
	Badge    string
	Class    string
	DataAttr string
}

BreakingConfig controls how breaking changes are presented.

type ChangeReportRenderer

type ChangeReportRenderer interface {
	// RenderMarkdown generates a markdown representation of the changes.
	RenderMarkdown(input *RenderInput) (string, error)

	// RenderHTML generates an HTML representation of the changes.
	RenderHTML(input *RenderInput) (string, error)
}

ChangeReportRenderer defines the interface for rendering change reports. Implementations can generate markdown, HTML, or any other format from API changes.

type ChangeSymbols

type ChangeSymbols struct {
	Modified string // Symbol for modified properties
	Added    string // Symbol for added properties
	Removed  string // Symbol for removed properties
	Breaking string // Suffix for breaking changes
}

ChangeSymbols defines the symbols used for different change types

func GetSymbols

func GetSymbols(useEmojis bool) ChangeSymbols

GetSymbols returns the appropriate symbol set based on the useEmojis flag

type ChangeType

type ChangeType int

ChangeType categorizes the nature of a change.

const (
	ChangeTypeUnknown ChangeType = iota
	ChangeTypeAddition
	ChangeTypeModification
	ChangeTypeRemoval
	ChangeTypeBreaking
)

func (ChangeType) String

func (ct ChangeType) String() string

String returns the string representation of the change type.

type CodeBlockConfig

type CodeBlockConfig struct {
	EnableSyntaxHighlighting bool
	Class                    string
	HeaderGenerator          CodeBlockHeaderGenerator
}

CodeBlockConfig controls code block rendering.

type CodeBlockHeaderGenerator

type CodeBlockHeaderGenerator interface {
	Generate(language string) string
}

CodeBlockHeaderGenerator generates header HTML for code blocks.

type CustomConfig

type CustomConfig struct {
	ElementRenderers map[string]ElementRenderer
}

CustomConfig holds user-defined custom element renderers.

type ElementRenderer

type ElementRenderer interface {
	// Render generates HTML for a specific element.
	// elementType identifies what's being rendered (e.g., "code-span", "list-item").
	// content is the element's content.
	// metadata provides context (e.g., "breaking": "true").
	Render(elementType string, content string, metadata map[string]string) (string, error)
}

ElementRenderer allows users to provide custom rendering for specific elements.

type HTMLConfig

type HTMLConfig struct {
	ExternalLinksNewTab   bool
	LinkClass             string
	HeadingIDPrefix       string
	HeadingClass          string
	AddHeadingAnchors     bool
	TableClass            string
	TableHeaderClass      string
	TableRowClass         string
	WrapSectionsInDivs    bool
	SectionDivClass       string
	AllowRawHTML          bool
	XHTMLOutput           bool
	HardWraps             bool
	EnableObjectIcons     bool
	EnableNestedListFix   bool
	NestedListFixStrategy NestedListFixStrategy
	EnableFloatingSidebar bool
	SidebarWidth          string
}

HTMLConfig controls general HTML output options.

type HTMLRenderer

type HTMLRenderer struct {
	// contains filtered or unexported fields
}

HTMLRenderer generates HTML reports from change data using Goldmark. supports extensive customization through config and custom node renderers.

func NewHTMLRenderer

func NewHTMLRenderer(config *RenderConfig) *HTMLRenderer

NewHTMLRenderer creates a new HTML renderer with the given configuration.

func (*HTMLRenderer) RenderHTML

func (r *HTMLRenderer) RenderHTML(input *RenderInput) (string, error)

RenderHTML generates HTML output from the change data.

func (*HTMLRenderer) RenderMarkdown

func (r *HTMLRenderer) RenderMarkdown(input *RenderInput) (string, error)

RenderMarkdown generates markdown first, then converts to HTML.

type MarkdownRenderer

type MarkdownRenderer struct{}

MarkdownRenderer implements ChangeReportRenderer for markdown output.

func NewMarkdownRenderer

func NewMarkdownRenderer() *MarkdownRenderer

NewMarkdownRenderer creates a new markdown-only renderer.

func (*MarkdownRenderer) RenderHTML

func (r *MarkdownRenderer) RenderHTML(input *RenderInput) (string, error)

RenderHTML is not supported by the markdown-only renderer.

func (*MarkdownRenderer) RenderMarkdown

func (r *MarkdownRenderer) RenderMarkdown(input *RenderInput) (string, error)

RenderMarkdown generates markdown using the existing MarkdownReporter implementation.

type MarkdownReporter

type MarkdownReporter struct {
	// contains filtered or unexported fields
}

MarkdownReporter generates markdown reports directly from DocumentChanges. This approach avoids duplication by using the already-deduplicated what-changed model.

func MarkdownReport added in v0.0.50

func MarkdownReport(docChanges *model.DocumentChanges, doctor *drModel.DrDocument, rightDocContent []byte, config *RenderConfig, deduplicatedChanges []*model.Change) *MarkdownReporter

MarkdownReport creates a new markdown reporter from DocumentChanges. When deduplicatedChanges is non-nil, summary statistics use deduplicated counts.

func (*MarkdownReporter) Generate

func (r *MarkdownReporter) Generate() string

Generate creates a comprehensive markdown report from DocumentChanges

type NestedListFixStrategy

type NestedListFixStrategy int

NestedListFixStrategy defines how code blocks in deeply nested lists are handled

const (
	NestedListFixInline  NestedListFixStrategy = iota
	NestedListFixExtract                       // reserved for future
	NestedListFixFlatten                       // reserved for future
)

type OutputFormat

type OutputFormat int

OutputFormat specifies the desired output format.

const (
	OutputFormatMarkdown OutputFormat = iota
	OutputFormatHTML
)

func (OutputFormat) String

func (of OutputFormat) String() string

String returns the string representation of the output format.

type ReferenceInfo

type ReferenceInfo struct {
	FullPath  string        // Full reference path (e.g., "#/components/schemas/Pet")
	Type      ReferenceType // Type of component being referenced
	Component string        // Component name (e.g., "Pet")
	FilePath  string        // File path for remote references
	IsLocal   bool          // Whether this is a local reference (#/...)
	IsRemote  bool          // Whether this is a remote reference (file.yaml#/...)
}

ReferenceInfo holds structured information about a $ref pointer

type ReferenceType

type ReferenceType string

ReferenceType represents the type of component being referenced

type ReferencedChange

type ReferencedChange struct {
	Reference *ReferenceInfo  // Information about the reference
	Changes   []*model.Change // The actual changes to this component
	UsedIn    []UsageLocation // Locations where this component is used
}

ReferencedChange represents a component change that is referenced in multiple locations

type RenderConfig

type RenderConfig struct {
	Breaking  *BreakingConfig
	Styling   *StylingConfig
	CodeBlock *CodeBlockConfig
	HTML      *HTMLConfig
	Custom    *CustomConfig
}

RenderConfig provides high-level customization options for report rendering.

func DefaultRenderConfig

func DefaultRenderConfig() *RenderConfig

DefaultRenderConfig returns sensible defaults for change report rendering.

func MergeConfigs

func MergeConfigs(base, override *RenderConfig) *RenderConfig

MergeConfigs merges override config into base config, with override taking precedence. returns a new config without modifying the originals.

type RenderInput

type RenderInput struct {
	// DocumentChanges contains the structured change tree from what-changed library.
	DocumentChanges *model.DocumentChanges

	// Doctor provides line-based model lookup for accurate type inference.
	Doctor *drModel.DrDocument

	// RightDocContent is the raw bytes of the new/right document.
	RightDocContent []byte

	// DeduplicatedChanges is the pre-deduplicated change list.
	// When set, the reporter uses its length for the total count instead of
	// the raw recursive TotalChanges() which can double-count.
	DeduplicatedChanges []*model.Change

	// Config provides rendering customization options.
	Config *RenderConfig
}

RenderInput provides all data needed to render a change report.

type SemanticLeaf added in v0.0.50

type SemanticLeaf struct {
	// contains filtered or unexported fields
}

type SemanticTreeRenderer added in v0.0.50

type SemanticTreeRenderer struct {
	// contains filtered or unexported fields
}

SemanticTreeRenderer renders a semantic change tree using grouped change keys instead of raw node-distributed leaves.

func NewSemanticTreeRenderer added in v0.0.50

func NewSemanticTreeRenderer(root *v3.Node, allChanges []*wcModel.Change, config *TreeConfig) *SemanticTreeRenderer

NewSemanticTreeRenderer creates a semantic tree renderer for the given node tree and raw change list. Changes are grouped by JSONPath + property while retaining grouped before/after fidelity for display.

func (*SemanticTreeRenderer) Highlights added in v0.0.50

func (sr *SemanticTreeRenderer) Highlights(limit int) []string

Highlights returns up to limit semantic breaking highlights.

func (*SemanticTreeRenderer) Render added in v0.0.50

func (sr *SemanticTreeRenderer) Render() string

Render returns the semantic tree output.

type StructuredDataFormat

type StructuredDataFormat int

StructuredDataFormat represents the detected format of a value.

const (
	FormatPlainText StructuredDataFormat = iota
	FormatJSON
	FormatYAML
	FormatXML
)

func DetectDocumentFormat

func DetectDocumentFormat(content []byte) StructuredDataFormat

DetectDocumentFormat detects whether a document is YAML or JSON based on its content.

func DetectFormat

func DetectFormat(value string) StructuredDataFormat

DetectFormat analyzes a value string and determines its structured data format. YAML is checked first since JSON syntax is valid YAML (subset relationship).

func PrettyPrint

func PrettyPrint(value string) (formatted string, format StructuredDataFormat)

PrettyPrint attempts to format structured data for better readability. Returns the formatted string and the detected format.

func (StructuredDataFormat) String

func (f StructuredDataFormat) String() string

String returns the string representation of the format for use in markdown code fences.

type StylingConfig

type StylingConfig struct {
	PropertyNameClass  string
	PropertyNamePrefix string
	PropertyNameSuffix string
	AdditionClass      string
	ModificationClass  string
	RemovalClass       string
}

StylingConfig controls CSS classes for different change types.

type TreeConfig

type TreeConfig struct {
	UseEmojis       bool                 // true = markdown mode (🔀➕➖), false = ASCII ([M][+][-])
	ShowLineNumbers bool                 // Include (line:col) after property names
	ShowStatistics  bool                 // Show (N changes, M breaking) on branch nodes
	ColorScheme     terminal.ColorScheme // Optional color scheme for terminal output (nil = no color)
}

TreeConfig configures the tree renderer output

type TreeRenderer

type TreeRenderer struct {
	// contains filtered or unexported fields
}

TreeRenderer renders a v3.Node tree as an ASCII tree string

func NewTreeRenderer

func NewTreeRenderer(root *v3.Node, config *TreeConfig) *TreeRenderer

NewTreeRenderer creates a new tree renderer for the given node tree

func (*TreeRenderer) Render

func (tr *TreeRenderer) Render() string

Render generates the ASCII tree string representation

type TypeStatistic

type TypeStatistic struct {
	Total    int
	Breaking int
}

TypeStatistic holds change counts for a type

type UsageLocation

type UsageLocation struct {
	Path        string // Path to the usage (e.g., "/pets GET")
	Description string // Description of how it's used (e.g., "Response 200")
	LineNumber  int    // Line number in the spec (if available)
}

UsageLocation represents where a referenced component is used

Jump to

Keyboard shortcuts

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