doyoucompute

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2025 License: MIT Imports: 13 Imported by: 8

README

DOYOUCOMPUTE

A lightweight framework for creating runnable documentation. Write your documentation once, then render it as markdown or execute it as a script. Ideal for tutorials, setup guides, and operational runbooks that need to stay up-to-date.

Features

  • 📝 Write documentation using a fluent, type-safe Go API
  • 🚀 Execute embedded commands to validate your docs stay current
  • 📋 Generate clean markdown output for GitHub, GitLab, etc.
  • 🔧 Compare generated docs with existing files for CI/CD validation
  • ⚡ Section-based execution for targeted testing

Quick Start

Installation
go get github.com/MoonMoon1919/doyoucompute
Basic Usage

Create a simple document with executable commands:

package samples

import "github.com/MoonMoon1919/doyoucompute"

func basics() {
	doc, err := doyoucompute.NewDocument("My Project")
	if err != nil {
		panic(err)
	}

	// Add an introduction
	doc.WriteIntro().
		Text("Welcome to my project! ").
		Text("Follow these steps to get started.")

	// Add a setup section with executable commands
	setup := doc.CreateSection("Setup")
	setup.WriteParagraph().
		Text("First, install dependencies:")

	setup.WriteCodeBlock("bash", []string{"npm install"}, doyoucompute.Exec)

	setup.WriteParagraph().
		Text("Then start the development server:")

	setup.WriteCodeBlock("bash", []string{"npm run dev"}, doyoucompute.Exec)
}

CLI Usage

Create a CLI wrapper for your documents:

package samples

import (
	"os"

	"github.com/MoonMoon1919/doyoucompute"
	"github.com/MoonMoon1919/doyoucompute/pkg/app"
)

func main() {
	service, err := doyoucompute.DefaultService()
	if err != nil {
		panic(err)
	}

	// Create and run CLI app
	app := app.New(service)

	doc, err := doyoucompute.NewDocument("My Project")
	if err != nil {
		panic(err)
	}

	app.Register(doc)

	if err := app.Run(os.Args); err != nil {
		panic(err)
	}
}

Available Commands
Command Description Example
render Generate markdown from document ./cli render --doc-name=readme --path=README.md
compare Compare document with existing file ./cli compare --doc-name=readme --path=README.md
run Execute all commands in document ./cli run --doc-name=setup
plan Show execution plan without running ./cli plan --doc-name=setup --section="Database Setup"
list List all available documents ./cli list

Security Features

DOYOUCOMPUTE includes built-in security features to prevent dangerous command execution:

  • 🛡️ Dangerous command blocking (rm -rf, sudo, etc.)
  • ⏱️ Configurable execution timeouts
  • 🐚 Shell allow-listing
  • 🔒 Command validation and sanitization
  • 🌍 Environment variable validation
Configuration

Customize execution behavior with security configurations:

package samples

import (
	"fmt"
	"time"

	"github.com/MoonMoon1919/doyoucompute"
)

func securityconfig() {
	// Default secure configuration
	config := doyoucompute.DefaultSecureConfig()

	// or, a custom configuration!
	config = doyoucompute.ExecutionConfig{
		Timeout:                30 * time.Second,
		AllowedShells:          []string{"bash", "python3"},
		BlockDangerousCommands: true,
	}

	service, err := doyoucompute.DefaultService(
		doyoucompute.WithTaskRunner(doyoucompute.NewTaskRunner(config)),
	)
	if err != nil {
		panic(err)
	}

	// do something with service, probably not print!
	fmt.Printf("service: %v\n", service)
}

Environment Variables

Commands can specify required environment variables:

package samples

import "github.com/MoonMoon1919/doyoucompute"

func envvars() {
	setup := doyoucompute.NewSection("Setup")

	setup.WriteExecutable(
		"bash",
		[]string{"curl", "-H", "Authorization: Bearer $API_KEY", "api.example.com"},
		[]string{"API_KEY"})
}

The command will fail to run if the required environment variables are not set and report which are missing.

Recommendations

  • 🔄 Run 'compare' in CI to ensure docs stay current
  • 🧪 Use 'plan' to preview commands before execution
  • 📂 Organize related commands into logical sections

Contributing

See CONTRIBUTING for details.

License

MIT License - see LICENSE for details.

Disclaimers

This work does not represent the interests or technologies of any employer, past or present. It is a personal project only.

Documentation

Index

Constants

View Source
const ALL_SECTIONS = ""

ALL_SECTIONS is a constant used to indicate that all sections should be processed when no specific section name is provided.

Variables

View Source
var (
	ErrShellNotAllowed   = errors.New("shell not allowed")
	ErrCommandNotAllowed = errors.New("command not allowed")
	ErrDangerousCommand  = errors.New("dangerous command blocked")
	ErrInvalidWorkingDir = errors.New("invalid working directory")
)

Functions

func LoadFile

func LoadFile(reader io.Reader) (string, error)

LoadFile reads all content from the provided io.Reader and returns it as a string. This utility function abstracts file reading operations and can work with any io.Reader implementation (files, network streams, etc.).

func ValidateCommandPlan

func ValidateCommandPlan(plan CommandPlan, config ExecutionConfig) error

ValidateCommandPlan validates that a command plan is safe to execute

func WriteFile

func WriteFile(writer io.Writer, content string) error

WriteFile writes the provided content string to the given io.Writer. This utility function abstracts file writing operations and can work with any io.Writer implementation (files, network streams, buffers, etc.).

Types

type BlockQuote

type BlockQuote string

BlockQuote represents quoted text content in documentation (e.g., > quoted text). It is defined as a string type for text that should be rendered as a block quote.

func (BlockQuote) Materialize

func (b BlockQuote) Materialize() (MaterializedContent, error)

Materialize converts the block quote into a MaterializedContent with its string content Block quotes are processed as-is without transformation.

func (BlockQuote) Type

func (b BlockQuote) Type() ContentType

Type returns the ContentType for this block quote element.

type Code

type Code string

Code represents inline code content in documentation. It is defined as a string type for short code snippets that appear within text (e.g., `variable` or `function()`).

func (Code) Materialize

func (c Code) Materialize() (MaterializedContent, error)

Materialize converts the inline code into a MaterializedContent with its string content Inline code is processed as-is without transformation.

func (Code) Type

func (c Code) Type() ContentType

Type returns the ContentType for this inline code element.

type CodeBlock

type CodeBlock struct {
	// BlockType specifies the language or type of the code block (e.g., "json", "bash", "go")
	BlockType string
	// Cmd contains the lines or components of the code block content
	Cmd []string
}

CodeBlock represents a non-executable code block used for displaying examples, payloads, or other code snippets that should not be run during documentation generation.

func (CodeBlock) Materialize

func (c CodeBlock) Materialize() (MaterializedContent, error)

Materialize converts the code block into a MaterializedContent by joining the Cmd slice with spaces as the content and storing the BlockType in metadata.

func (CodeBlock) Type

func (c CodeBlock) Type() ContentType

Type returns the ContentType for this code block element.

type CodeBlockExecType

type CodeBlockExecType int // todo: this name is awful

CodeBlockExecType represents how a code block should be processed during documentation generation - either as static display content or as executable code

const (
	// Static indicates the code block should be displayed as-is without execution
	Static CodeBlockExecType = iota + 1

	// Exec indicates the code block contains executable code that should be run
	// when processing the documentation as a script
	Exec
)

type CommandPlan

type CommandPlan struct {
	// Shell specifies the shell or interpreter to use for execution
	Shell string
	// Args contains the command and its arguments to be executed
	Args []string
	// Context provides information about which section this command originated from
	Context SectionInfo
	// Environment variables that must be set for the command to be executed
	Environment []string
}

CommandPlan represents a single executable command with its context information, used for planning and executing runnable documentation scripts.

type Comment

type Comment string

Comment represents comment content in documentation that provides additional context or notes. It is defined as a string type for text that may be rendered differently from regular content.

func (Comment) Materialize

func (c Comment) Materialize() (MaterializedContent, error)

Materialize converts the comment into a MaterializedContent with its string content Comments are processed as-is without transformation.

func (Comment) Type

func (c Comment) Type() ContentType

Type returns the ContentType for this comment element.

type ComparisonResult

type ComparisonResult struct {
	// Matches indicates whether the document content matches the existing file
	Matches bool
	// DocumentHash is the MD5 hash of the rendered document content
	DocumentHash string
	// FileHash is the MD5 hash of the existing file content
	FileHash string
}

ComparisonResult contains the results of comparing a document's rendered content with an existing file, including match status and content hashes.

type ContentType

type ContentType int

ContentType represents the different types of content elements that can be processed and rendered in runnable documentation. Each type corresponds to a specific markdown or documentation construct that may require different handling during parsing and execution.

const (
	// HeaderType represents markdown headers (# ## ### etc.)
	HeaderType ContentType = iota + 1

	// LinkType represents hyperlinks and references
	LinkType

	// TextType represents plain text content
	TextType

	// CodeType represents inline code snippets
	CodeType

	// CodeBlockType represents fenced code blocks that may contain
	// examples
	CodeBlockType

	// TableRowType represents individual rows within a table
	TableRowType

	// BlockQuoteType represents quoted text blocks (> quoted text)
	BlockQuoteType

	// ExecutableType represents code or commands that can be executed
	// as part of the runnable documentation
	ExecutableType

	// RemoteType represents content that is fetched from remote sources
	RemoteType

	// CommentType represents comment blocks in the documentation
	CommentType

	// ListType represents ordered and unordered lists
	ListType

	// TableType represents table structures
	TableType

	// ParagraphType represents standard paragraph content
	ParagraphType

	// SectionType represents logical sections or divisions of content
	SectionType

	// DocumentType represents the root document container
	DocumentType

	// FrontmatterType represents YAML/TOML frontmatter metadata
	// typically found at the beginning of markdown documents
	FrontmatterType
)

type Contenter

type Contenter interface {
	Node
	// Materialize converts the content into a MaterializedContent with rendered output
	// and associated metadata. Returns an error if materialization fails.
	Materialize() (MaterializedContent, error)
}

Contenter represents content elements that can be materialized into their final form. This interface is implemented by leaf nodes that contain actual content data (text, code, links, etc.) that needs to be processed and rendered.

type ContextPath

type ContextPath []SectionInfo

ContextPath represents a stack of section information that tracks the current position within a nested document structure during traversal or rendering.

func (ContextPath) Current

func (c ContextPath) Current() SectionInfo

Current returns the SectionInfo for the current (most recent) section. Returns an empty SectionInfo if the path is empty.

func (ContextPath) CurrentLevel

func (c ContextPath) CurrentLevel() int

CurrentLevel returns the nesting level of the current section. Returns -1 if no sections are in the path.

func (ContextPath) CurrentSection

func (c ContextPath) CurrentSection() string

CurrentSection returns the name of the current section. Returns an empty string if no sections are in the path.

func (ContextPath) Push

func (c ContextPath) Push(name string) ContextPath

Push adds a new section to the context path and returns the updated path. The level is automatically calculated based on the current depth.

type Document

type Document struct {
	// Name is the identifier/title for this document
	Name string
	// Frontmatter contains optional metadata for the document
	Frontmatter Frontmatter
	// Content holds all the content elements within this document
	Content []Node
}

Document represents the top-level container for a complete document with optional frontmatter metadata and structured content organized into sections and paragraphs.

func NewDocument

func NewDocument(name string) (Document, error)

NewDocument creates a new Document with the specified name and empty content.

func (*Document) AddFrontmatter

func (d *Document) AddFrontmatter(f Frontmatter)

AddFrontmatter sets the frontmatter metadata for the document.

func (*Document) AddIntro

func (d *Document) AddIntro(content *Paragraph)

AddIntro prepends a paragraph to the beginning of the document content.

func (*Document) AddSection

func (d *Document) AddSection(section Section)

AddSection appends an existing section to the document.

func (Document) Children

func (d Document) Children() []Node

Children returns all content within the document as Node interfaces.

func (*Document) CreateSection

func (d *Document) CreateSection(name string) *Section

CreateSection creates a new section with the given name and returns it for editing.

func (*Document) HasFrontmatter

func (d *Document) HasFrontmatter() bool

HasFrontmatter returns true if the document has frontmatter data.

func (Document) Identifier

func (d Document) Identifier() string

Identifier returns the document name as its identifier.

func (Document) Type

func (d Document) Type() ContentType

Type returns the ContentType for this document element.

func (Document) Valid

func (d Document) Valid() error

func (*Document) WriteIntro

func (d *Document) WriteIntro() *Paragraph

WriteIntro creates a new paragraph at the beginning of the document and returns it for editing.

type Executable

type Executable struct {
	// Shell specifies the shell or interpreter to use for execution (e.g., "bash", "sh", "python")
	Shell string
	// Cmd contains the command and arguments to be executed
	Cmd []string
	// Environment variables that must be set for the command to be run
	Environment []string
}

Executable represents a code block that can be executed while running documentation as a script. This is the core component that enables "runnable documentation" by storing commands that will be executed, while representing them as code blocks in rendered output.

func (Executable) Materialize

func (e Executable) Materialize() (MaterializedContent, error)

Materialize converts the executable into a MaterializedContent with the joined command as content and execution metadata including the shell, executable flag, and original command.

func (Executable) Type

func (e Executable) Type() ContentType

Type returns the ContentType for this executable element.

type ExecutionConfig

type ExecutionConfig struct {
	// Timeout for command execution (0 means no timeout)
	Timeout time.Duration

	// AllowedShells restricts which shells/interpreters can be used
	AllowedShells []string

	// AllowedCommands restricts which commands can be executed (nil means allow all)
	AllowedCommands []string

	// BlockDangerousCommands prevents obviously dangerous operations
	BlockDangerousCommands bool
}

func DefaultSecureConfig

func DefaultSecureConfig() ExecutionConfig

type Executioner

type Executioner struct{}

Executioner implements the Renderer interface to extract executable commands from document nodes and create execution plans for runnable documentation.

func NewExecutionRenderer

func NewExecutionRenderer() Executioner

NewExecutionRenderer creates a new Executioner instance for building command execution plans.

func (Executioner) Render

func (e Executioner) Render(node Node) ([]CommandPlan, error)

Render traverses a document node and extracts all executable commands, returning them as a slice of CommandPlan for execution planning. This is the main entry point for the Renderer interface implementation.

type FileRepository

type FileRepository struct{}

FileRepository implements the Repository interface using the local file system for loading and saving content. It provides concrete file operations for the runnable documentation system.

func NewFileRepository

func NewFileRepository() FileRepository

NewFileRepository creates a new FileRepository instance for file system operations.

func (FileRepository) Load

func (f FileRepository) Load(path string) (string, error)

Load opens and reads the content of a file at the specified path, returning the content as a string. Returns an error if the file cannot be opened or read.

func (FileRepository) Save

func (f FileRepository) Save(path string, content string) error

Save creates a new file at the specified path and writes the provided content to it. If the file already exists, it will be overwritten. Returns an error if the file cannot be created or written to.

type Frontmatter

type Frontmatter struct {
	// Data holds the parsed frontmatter key-value pairs
	Data map[string]interface{}
}

Frontmatter represents YAML/TOML metadata typically found at the beginning of markdown documents, containing key-value configuration and metadata pairs.

func NewFrontmatter

func NewFrontmatter(data map[string]interface{}) *Frontmatter

NewFrontmatter creates a new Frontmatter instance with the provided data map.

func (*Frontmatter) Empty

func (f *Frontmatter) Empty() bool

Empty returns true if the frontmatter contains no data.

type Header struct {
	// Content holds the text content of the header
	Content string
}

Header represents a header element containing text content

func (Header) Materialize

func (h Header) Materialize() (MaterializedContent, error)

Materialize converts the header into a MaterializedContent with its content Headers are processed as-is without transformation

func (Header) Type

func (h Header) Type() ContentType

Type returns the ContentType for this header element

type Link struct {
	// Text holds the display text for the link
	Text string
	// Url holds the target URL that the link points to
	Url string
}

Link represents a hyperlink element with display text and a target URL.

func (Link) Materialize

func (l Link) Materialize() (MaterializedContent, error)

Materialize converts the link into a MaterializedContent with the display text as content and the URL stored in metadata under the "Url" key.

func (Link) Type

func (l Link) Type() ContentType

Type returns the ContentType for this link element.

type List

type List struct {
	// Items contains the text content for each list item
	Items []Text
	// TypeOfList specifies whether this is a bulleted or numbered list
	TypeOfList ListTypeE
}

List represents a container for rendering content as either bulleted or numbered lists.

func NewList

func NewList(typeOfList ListTypeE) *List

NewList creates a new List instance of the specified type with an empty items slice.

func (*List) Append

func (l *List) Append(val string)

Append adds a new item to the end of the list.

func (List) Children

func (l List) Children() []Node

Children returns all list items as Node interfaces, allowing the list to be treated as a parent node in a document tree structure.

func (List) Identifier

func (l List) Identifier() string

Identifier returns an empty string as lists do not have specific identifiers.

func (*List) Push

func (l *List) Push(val string)

Push adds a new item to the beginning of the list.

func (List) Type

func (l List) Type() ContentType

Type returns the ContentType for this list element.

type ListTypeE

type ListTypeE int

ListTypeE represents the different types of lists that can be rendered.

const (
	// BULLET represents an unordered list with bullet points
	BULLET ListTypeE = iota + 1
	// NUMBERED represents an ordered list with numbers
	NUMBERED
)

func (ListTypeE) Prefix

func (l ListTypeE) Prefix() string

Prefix returns the string prefix used for rendering this list type. Returns "-" for bullet lists and "1." for numbered lists.

type Markdown

type Markdown struct{}

Markdown implements the Renderer interface to convert document nodes into markdown format. It handles hierarchical document structures and maintains proper heading levels during traversal.

func NewMarkdownRenderer

func NewMarkdownRenderer() Markdown

NewMarkdownRenderer creates a new Markdown renderer instance.

func (Markdown) Render

func (m Markdown) Render(node Node) (string, error)

Render converts a document node into markdown format, starting with an empty context path. This is the main entry point for the Renderer interface implementation.

type MaterializedContent

type MaterializedContent struct {
	// Type specifies what kind of content this represents (header, code block, etc.)
	Type ContentType

	// Content contains the final rendered or processed content as a string
	Content string

	// Metadata holds additional key-value pairs associated with this content,
	// such as styling information
	Metadata map[string]interface{}
}

MaterializedContent represents a processed content element with its type, rendered content, and associated metadata.

type Node

type Node interface {
	// Type returns the ContentType that identifies what kind of content this node represents
	Type() ContentType
}

Node represents the base interface for all content elements in the documentation system. It provides type identification for polymorphic handling of different content types.

type OptionsServiceFunc

type OptionsServiceFunc func(c *Service) error

func WithExecutionRenderer

func WithExecutionRenderer(renderer Renderer[[]CommandPlan]) OptionsServiceFunc

func WithFileRenderer

func WithFileRenderer(renderer Renderer[string]) OptionsServiceFunc

func WithRepository

func WithRepository(repo Repository) OptionsServiceFunc

func WithTaskRunner

func WithTaskRunner(runner Runner) OptionsServiceFunc

type Paragraph

type Paragraph struct {
	// Items contains the various content elements (text, code, links) within this paragraph
	Items []Node
}

Paragraph represents a container for mixed content elements that should be rendered together as a cohesive paragraph block.

func NewParagraph

func NewParagraph() *Paragraph

NewParagraph creates a new Paragraph instance with an empty items slice.

func (Paragraph) Children

func (p Paragraph) Children() []Node

Children returns all items within the paragraph as Node interfaces.

func (*Paragraph) Code

func (p *Paragraph) Code(val string) *Paragraph

Code adds an inline code element to the paragraph and returns the paragraph for method chaining.

func (Paragraph) Identifier

func (p Paragraph) Identifier() string

Identifier returns an empty string as paragraphs do not have specific identifiers.

func (p *Paragraph) Link(text, url string) *Paragraph

Link adds a hyperlink element to the paragraph and returns the paragraph for method chaining.

func (*Paragraph) Text

func (p *Paragraph) Text(val string) *Paragraph

Text adds a text element to the paragraph and returns the paragraph for method chaining.

func (Paragraph) Type

func (p Paragraph) Type() ContentType

Type returns the ContentType for this paragraph element.

type Remote

type Remote struct {
	// Reader provides access to the remote content data
	Reader io.Reader
}

Remote represents content that is sourced from external locations such as local files in a docs folder, GitHub repositories, or other remote sources.

func (Remote) Materialize

func (r Remote) Materialize() (MaterializedContent, error)

Materialize reads all content from the Reader and converts it into a MaterializedContent. Returns an error if the content cannot be read from the remote source.

func (Remote) Type

func (r Remote) Type() ContentType

Type returns the ContentType for this remote content element.

type Renderer

type Renderer[T any] interface {
	// Render processes a node and converts it to the target format T.
	// Returns an error if the rendering process fails.
	Render(node Node) (T, error)
}

Renderer defines a generic interface for converting Node elements into different output formats. The type parameter T allows for different renderers to produce different output types (e.g., string for markdown, []CommandPlan for execution planning).

type Repository

type Repository interface {
	// Load reads content from the specified file path and returns it as a string.
	// Returns an error if the file cannot be read or does not exist.
	Load(path string) (string, error)
	// Save writes the provided content to the specified file path.
	// Returns an error if the file cannot be written.
	Save(path string, content string) error
}

Repository provides abstraction for file system operations, allowing the service to load and save content without being tied to specific storage implementations.

type Runner

type Runner interface {
	// Run executes the provided command plan and returns the result with status and error information
	Run(plan CommandPlan) TaskResult
}

Runner defines the interface for executing command plans and returning results. This abstraction allows for different execution strategies (local, remote, mock, etc.).

type Section

type Section struct {
	// Name is the identifier/title for this section
	Name string
	// Content holds all the content elements within this section
	Content []Node
}

Section represents a named container that holds various types of content elements, allowing for hierarchical document organization.

func NewSection

func NewSection(name string) Section

NewSection creates a new Section with the specified name and empty content.

func (*Section) AddIntro

func (s *Section) AddIntro(content *Paragraph)

AddIntro prepends a paragraph to the beginning of the section content.

func (*Section) AddList

func (s *Section) AddList(listType ListTypeE, items []Text)

AddList creates and adds a list of the specified type with the given items.

func (*Section) AddParagraph

func (s *Section) AddParagraph(paragraph Paragraph)

AddParagraph appends an existing paragraph to the section.

func (*Section) AddSection

func (s *Section) AddSection(section Section)

AddSection appends an existing section as a subsection.

func (*Section) AddTable

func (s *Section) AddTable(headers []string, rows []TableRow)

AddTable creates and adds a table with the specified headers and rows.

func (Section) Children

func (s Section) Children() []Node

Children returns all content within the section as Node interfaces.

func (*Section) CreateList

func (s *Section) CreateList(listType ListTypeE) *List

CreateList creates a new list of the specified type and returns it for editing.

func (*Section) CreateSection

func (s *Section) CreateSection(name string) *Section

CreateSection creates a new subsection with the given name and returns it for editing.

func (*Section) CreateTable

func (s *Section) CreateTable(headers []string) *Table

CreateTable creates a new table with the given headers and returns it for editing.

func (Section) Identifier

func (s Section) Identifier() string

Identifier returns the section name as its identifier.

func (Section) Type

func (s Section) Type() ContentType

Type returns the ContentType for this section element.

func (Section) Valid

func (s Section) Valid() error

func (*Section) WriteBlockQuote

func (s *Section) WriteBlockQuote(value string)

WriteBlockQuote adds a block quote with the specified content to the section.

func (*Section) WriteCodeBlock

func (s *Section) WriteCodeBlock(blockType string, cmd []string, executable CodeBlockExecType)

WriteCodeBlock adds either an executable or non-executable code block based on the executable parameter. If executable is Exec, creates an Executable; otherwise creates a CodeBlock.

func (*Section) WriteComment

func (s *Section) WriteComment(value string)

WriteComment adds a comment to the section.

func (*Section) WriteExecutable

func (s *Section) WriteExecutable(shell string, cmd []string, env []string)

func (*Section) WriteIntro

func (s *Section) WriteIntro() *Paragraph

WriteIntro creates a new paragraph at the beginning of the section and returns it for editing.

func (*Section) WriteParagraph

func (s *Section) WriteParagraph() *Paragraph

WriteParagraph creates a new paragraph in the section and returns it for editing.

func (*Section) WriteRemoteContent

func (s *Section) WriteRemoteContent(remote Remote)

WriteRemoteContent adds remote content to the section.

type SectionInfo

type SectionInfo struct {
	// Name is the identifier of the section
	Name string
	// Level indicates the nesting depth of the section (1 for top-level, 2 for subsection, etc.)
	Level int
}

SectionInfo contains metadata about a section's position within the document hierarchy.

type Service

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

Service orchestrates the core functionality of the runnable documentation system, coordinating between content rendering, script execution, and file operations.

func DefaultService

func DefaultService(opts ...OptionsServiceFunc) (*Service, error)

DefaultService creates a service instance with FileRepository, MarkdownRender, ExecutionRenderer, and TaskRunner with DefaultSecureConfig It takes in any number of OptionsServiceFunc to configure the options of the service

func NewService

func NewService(repo Repository, runner Runner, fileRenderer Renderer[string], executionRenderer Renderer[[]CommandPlan]) Service

NewService creates a new Service instance with the provided dependencies for repository access, task execution, and content rendering.

func (Service) CompareFile

func (s Service) CompareFile(document *Document, pathToFile string) (ComparisonResult, error)

CompareFile renders a document and compares its content with an existing file, returning detailed comparison results including MD5 hashes for verification.

func (Service) ExecuteScript

func (s Service) ExecuteScript(document *Document, sectionName string) ([]TaskResult, error)

ExecuteScript creates an execution plan for the specified document section and runs all executable blocks, returning the results of each executed command.

func (Service) PlanScriptExecution

func (s Service) PlanScriptExecution(document *Document, sectionName string) ([]CommandPlan, error)

PlanScriptExecution analyzes a document and creates an execution plan for all executable content blocks. If sectionName is provided, only executable blocks from that section are included. Use ALL_SECTIONS constant to include all sections.

func (Service) RenderFile

func (s Service) RenderFile(document *Document, outpath string) error

RenderFile generates the final content for a document and saves it to the specified output path. Returns an error if rendering fails or the file cannot be saved.

type Structurer

type Structurer interface {
	Node
	// Identifier returns a name for this structural element
	Identifier() string
	// Children returns all child nodes contained within this structural element
	Children() []Node
}

Structurer represents container elements that organize and structure the document. This interface is implemented by nodes that can contain other nodes and provide hierarchical organization (sections, documents, tables, lists, etc.).

type Table

type Table struct {
	// Headers contains the column header names for the table
	Headers []string
	// Items contains all the rows of data in the table
	Items []TableRow
}

Table represents a complete table structure with headers and multiple rows of data.

func NewTable

func NewTable(headers []string, items []TableRow) *Table

NewTable creates a new Table instance with the specified headers and rows.

func (*Table) AddRow

func (t *Table) AddRow(row ...string) error

AddRow appends a new row to the table with the provided column values. Returns an error if the number of values exceeds the number of headers.

func (Table) Children

func (t Table) Children() []Node

Children returns all table rows as Node interfaces, allowing the table to be treated as a parent node in a document tree structure.

func (Table) Identifier

func (t Table) Identifier() string

Identifier returns an empty string as tables do not have specific identifiers.

func (Table) Type

func (t Table) Type() ContentType

Type returns the ContentType for this table element.

type TableRow

type TableRow struct {
	// Values contains the content for each column in this table row
	Values []string
}

TableRow represents a single row in a table with multiple column values.

func (TableRow) Materialize

func (t TableRow) Materialize() (MaterializedContent, error)

Materialize converts the table row into a MaterializedContent with empty content and the row values stored in metadata under the "Items" key.

func (TableRow) Type

func (t TableRow) Type() ContentType

Type returns the ContentType for this table row element.

type TaskResult

type TaskResult struct {
	// SectionName identifies which document section the task originated from
	SectionName string
	// Command contains the full command string that was executed
	Command string
	// Status indicates whether the task completed successfully or failed
	Status TaskStatus
	// Error holds any error that occurred during task execution (nil if successful)
	Error error
}

TaskResult contains the outcome and details of executing a single command, including context information and any errors that occurred.

func RunExecutionPlan

func RunExecutionPlan(plans []CommandPlan, runner Runner) []TaskResult

RunExecutionPlan executes a sequence of command plans using the provided runner, logging each command before execution and returning results for all commands. Commands are executed sequentially in the order they appear in the plan.

type TaskRunner

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

TaskRunner implements the Runner interface for executing commands locally using the operating system's command execution facilities.

func NewTaskRunner

func NewTaskRunner(config ExecutionConfig) TaskRunner

NewTaskRunner creates a new TaskRunner instance for local command execution.

func (TaskRunner) Run

func (t TaskRunner) Run(plan CommandPlan) TaskResult

Run executes a command plan locally using exec.Command, streaming output to stdout/stderr in real-time. Returns a TaskResult with execution status and any errors.

type TaskStatus

type TaskStatus int

TaskStatus represents the outcome of executing a command or task.

const (
	// COMPLETED indicates the task executed successfully without errors
	COMPLETED TaskStatus = iota + 1
	// FAILED indicates the task execution failed or encountered an error
	FAILED
)

type Text

type Text string

Text represents plain text content in documentation.

func (Text) Materialize

func (t Text) Materialize() (MaterializedContent, error)

Materialize converts the text into a MaterializedContent with its string content. Plain text is processed as-is without transformation.

func (Text) Type

func (t Text) Type() ContentType

Type returns the ContentType for this text element.

Directories

Path Synopsis
pkg
app

Jump to

Keyboard shortcuts

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