utils

package
v0.7.5 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

color.go provides ANSI color output helpers. It exposes Success / Warning / Error / Info helpers and automatically falls back to plain text when color is unavailable.

progress.go provides progress output for build steps. It supports step counting, status markers, and colored output.

Index

Constants

View Source
const (
	// KaTeXCSSURL is the CDN URL for the KaTeX stylesheet.
	KaTeXCSSURL = "https://cdn.jsdelivr.net/npm/katex@0.16.44/dist/katex.min.css"
	// KaTeXJSURL is the CDN URL for the KaTeX core JavaScript library.
	KaTeXJSURL = "https://cdn.jsdelivr.net/npm/katex@0.16.44/dist/katex.min.js"
	// KaTeXAutoRenderURL is the CDN URL for the KaTeX auto-render extension, which scans for $...$ and $$...$$ in the document and renders them.
	KaTeXAutoRenderURL = "https://cdn.jsdelivr.net/npm/katex@0.16.44/dist/contrib/auto-render.min.js"
)

KaTeX CDN URLs. Centralized here to keep the version consistent across the codebase.

View Source
const (
	// MaxImageSize is the maximum allowed size for a downloaded image (50 MB).
	MaxImageSize = 50 * 1024 * 1024
	// DefaultMaxConcurrentDownloads is the default number of concurrent image downloads.
	DefaultMaxConcurrentDownloads = 4
)
View Source
const MaxHTTPRedirects = 10

MaxHTTPRedirects is the maximum number of HTTP redirects to follow. Shared across image downloads, upgrade checks, and PlantUML rendering.

View Source
const MermaidCDNURL = "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"

MermaidCDNURL is the CDN URL for the Mermaid diagram library. Centralized here so every part of the codebase uses the same version.

Variables

View Source
var HTMLTagPattern = regexp.MustCompile(`<[^>]*>`)

HTMLTagPattern matches any HTML tag. Useful for stripping tags to obtain plain text. Shared across cmd and internal/output packages.

View Source
var ImgSrcRegex = regexp.MustCompile(`<img\s+([^>]*\s+)?src=["']([^"']+)["']([^>]*)>`)

ImgSrcRegex matches HTML <img> tags and captures the src attribute. Exported so that other packages (e.g. internal/output/epub) can reuse the same compiled pattern instead of declaring a duplicate.

Functions

func Blue

func Blue(text string) string

Blue returns blue text.

func Bold

func Bold(text string) string

Bold returns bold text.

func CJKFontInstallHint added in v0.3.1

func CJKFontInstallHint() string

CJKFontInstallHint returns platform-specific instructions for installing CJK fonts.

func CacheDisabled added in v0.3.1

func CacheDisabled() bool

CacheDisabled reports whether runtime caches are disabled for this process.

func CacheRootDir added in v0.3.1

func CacheRootDir() string

CacheRootDir returns the root directory used for mdpress runtime caches. MDPRESS_CACHE_DIR overrides the default location when set.

func CheckURLNotPrivate added in v0.7.0

func CheckURLNotPrivate(u *url.URL) error

CheckURLNotPrivate checks that a URL's hostname does not resolve to a private, loopback, or link-local IP address (SSRF prevention). Exported so that other packages (e.g. internal/plantuml) can reuse the same validation instead of duplicating the logic.

func ContainsCJK added in v0.3.1

func ContainsCJK(text string) bool

ContainsCJK reports whether the text contains any CJK (Chinese, Japanese, Korean) characters.

func CopyFile

func CopyFile(src, dst string) error

CopyFile copies a file from src to dst.

func Cyan

func Cyan(text string) string

Cyan returns cyan text.

func DetectImageMIME

func DetectImageMIME(path string, data []byte) string

DetectImageMIME determines the MIME type from content when possible. This is more reliable than extension-only detection for remote assets whose URLs do not include a file suffix, such as Shields badges.

func Dim

func Dim(text string) string

Dim returns dimmed text.

func DisableSSRFCheck added in v0.6.2

func DisableSSRFCheck()

DisableSSRFCheck disables the SSRF prevention check. Intended for testing only.

func DownloadImage

func DownloadImage(urlStr string, destDir string) (string, error)

DownloadImage downloads an image from a URL and returns the local path.

func EnableSSRFCheck added in v0.6.2

func EnableSSRFCheck()

EnableSSRFCheck re-enables the SSRF prevention check.

func EnsureDir

func EnsureDir(path string) error

EnsureDir creates a directory when it does not already exist. MkdirAll is idempotent, so we call it directly to avoid a TOCTOU race.

func Error

func Error(format string, args ...any)

Error prints a red error message with an error prefix.

func EscapeAttr

func EscapeAttr(s string) string

EscapeAttr escapes an HTML attribute value.

func EscapeHTML

func EscapeHTML(s string) string

EscapeHTML escapes HTML special characters including single quotes. This is the canonical HTML escaping function used throughout mdpress.

func EscapeXML

func EscapeXML(s string) string

EscapeXML escapes XML special characters. Similar to EscapeHTML but uses &apos; for single quotes per the XML specification.

func ExtractTitleFromFile added in v0.5.2

func ExtractTitleFromFile(path string) string

ExtractTitleFromFile scans a Markdown file and returns the first H1 heading. For performance, scanning stops after 50 lines.

func FileExists

func FileExists(path string) bool

FileExists reports whether a file or directory exists.

func Green

func Green(text string) string

Green returns green text.

func Header(title string)

Header prints a titled separator.

func ImageExtForMIME added in v0.7.0

func ImageExtForMIME(mimeType string) (string, bool)

ImageExtForMIME returns the file extension for a given image MIME type. Returns the extension and true if found, or "" and false otherwise.

func ImageToBase64

func ImageToBase64(path string) (string, error)

ImageToBase64 converts an image file to a base64 data URI.

func Info

func Info(format string, args ...any)

Info prints a blue informational message with an info prefix.

func IsCJKRune added in v0.5.0

func IsCJKRune(r rune) bool

IsCJKRune reports whether the rune is a CJK character.

func IsColorEnabled

func IsColorEnabled() bool

IsColorEnabled reports whether color output is enabled.

func IsRemoteURL

func IsRemoteURL(path string) bool

IsRemoteURL reports whether a path is an HTTP(S) URL.

func ParseVersionPart added in v0.6.0

func ParseVersionPart(s string) (int, error)

ParseVersionPart parses a version number component (e.g., "25" from "1.25.0").

func ProcessImages

func ProcessImages(htmlContent string, baseDir string, embedAsBase64 bool, logger ...*slog.Logger) (string, error)

ProcessImages resolves image paths in HTML and optionally embeds them as base64. An optional logger can be provided to record warnings when image processing fails. Pass nil to silently skip failures (legacy behavior).

func ProcessImagesWithOptions added in v0.3.1

func ProcessImagesWithOptions(htmlContent string, baseDir string, options ImageProcessingOptions) (string, error)

ProcessImagesWithOptions resolves image paths in HTML with explicit control over embedding, remote downloads, and file URL rewriting.

func ReadFile

func ReadFile(path string) ([]byte, error)

ReadFile reads a file and returns clearer errors. It rejects files larger than 100 MB as a safety net against OOM.

The size check uses Fstat on the open file descriptor to avoid a TOCTOU race between a separate Stat call and the subsequent read.

func Red

func Red(text string) string

Red returns red text.

func RelPath

func RelPath(basePath, targetPath string) string

RelPath computes the target path relative to the base path.

func ResolveCDNPlaceholders added in v0.7.0

func ResolveCDNPlaceholders(tmpl string) string

ResolveCDNPlaceholders replaces CDN URL placeholders in a template string with the actual CDN URLs defined in this package.

func SSRFSafeTransport added in v0.7.4

func SSRFSafeTransport() *http.Transport

SSRFSafeTransport returns a clone of the SSRF-safe HTTP transport that validates resolved IP addresses at dial time to prevent DNS rebinding attacks. Callers should use this when building HTTP clients for user-controlled URLs.

func SafeJoin added in v0.6.4

func SafeJoin(baseDir, untrusted string) (string, error)

SafeJoin joins a base directory with an untrusted relative path and verifies the result stays within the base directory. It returns an error if the resolved path escapes the base via ".." or absolute-path tricks.

func SanitizeCSS added in v0.7.0

func SanitizeCSS(css string) string

SanitizeCSS removes sequences from CSS content that could break out of a <style> block or perform injection attacks. This prevents: - </style> tag breakout - @import-based data exfiltration - expression()-based script execution (legacy IE) - url() references to external HTTP(S) origins - javascript:/vbscript: URIs inside url() values

Note: @font-face rules are allowed because external url() references are already blocked by cssExternalURLPattern. This permits legitimate local font declarations (e.g. src: local("...") or src: url("fonts/my.woff")) while still preventing data exfiltration via external URLs.

func SetColorEnabled

func SetColorEnabled(enabled bool)

SetColorEnabled overrides color output for tests or forced modes.

func StableHash added in v0.3.1

func StableHash(parts ...string) string

StableHash returns a stable SHA-256 hex digest for the given strings.

func StripHTMLTags added in v0.6.4

func StripHTMLTags(s string) string

StripHTMLTags removes all HTML tags from s, returning plain text.

func Success

func Success(format string, args ...any)

Success prints a green success message with a checkmark prefix.

func Warning

func Warning(format string, args ...any)

Warning prints a yellow warning message with a warning prefix.

func WriteFile

func WriteFile(path string, data []byte) error

WriteFile writes file content and creates parent directories when needed.

func Yellow

func Yellow(text string) string

Yellow returns yellow text.

Types

type CJKFontStatus added in v0.3.1

type CJKFontStatus struct {
	Available bool     // Whether any CJK font is installed.
	Fonts     []string // Names of detected CJK fonts (up to 5).
}

CJKFontStatus describes the availability of CJK fonts on the system.

func CheckCJKFonts added in v0.3.1

func CheckCJKFonts() CJKFontStatus

CheckCJKFonts checks whether CJK fonts are installed on the system. It uses platform-specific methods: fc-list on Linux, system_profiler on macOS.

type ImageProcessingOptions added in v0.3.1

type ImageProcessingOptions struct {
	EmbedLocalAsBase64     bool
	EmbedRemoteAsBase64    bool
	RewriteLocalToFileURL  bool
	RewriteRemoteToFileURL bool
	DownloadRemote         bool
	CacheDir               string
	MaxConcurrentDownloads int
	Logger                 *slog.Logger
}

ImageProcessingOptions controls how image references are rewritten.

type LimitedWriter added in v0.7.0

type LimitedWriter struct {
	W io.Writer // underlying writer
	N int64     // remaining bytes allowed
}

LimitedWriter wraps an io.Writer and silently discards writes that would exceed the configured byte limit. This prevents unbounded memory growth when capturing output from external processes.

After the limit is reached, Write still reports consuming all bytes so that callers such as io.Copy do not treat a truncated write as io.ErrShortWrite.

func (*LimitedWriter) Write added in v0.7.0

func (lw *LimitedWriter) Write(p []byte) (int, error)

Write writes p to the underlying writer, truncating silently once the byte limit is exhausted. It always returns len(p), nil to avoid spurious io.ErrShortWrite errors in callers like io.Copy.

type PageDimensions added in v0.7.0

type PageDimensions struct {
	Width  float64
	Height float64
}

PageDimensions holds page width and height in millimeters.

func GetPageDimensions added in v0.7.0

func GetPageDimensions(size string) PageDimensions

GetPageDimensions returns the page dimensions for a named page size. If the size is unknown, A4 dimensions are returned.

func (PageDimensions) HeightMM added in v0.7.0

func (d PageDimensions) HeightMM() string

HeightMM returns the height as a Typst-compatible "Xmm" string.

func (PageDimensions) WidthMM added in v0.7.0

func (d PageDimensions) WidthMM() string

WidthMM returns the width as a Typst-compatible "Xmm" string.

type ProgressTracker

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

ProgressTracker tracks build progress.

func NewProgressTracker

func NewProgressTracker(total int) *ProgressTracker

NewProgressTracker creates a new progress tracker.

func (*ProgressTracker) Done

func (p *ProgressTracker) Done()

Done marks the current step as completed.

func (*ProgressTracker) DoneWithDetail

func (p *ProgressTracker) DoneWithDetail(detail string)

DoneWithDetail marks the current step as completed with extra detail.

func (*ProgressTracker) Fail

func (p *ProgressTracker) Fail()

Fail marks the current step as failed.

func (*ProgressTracker) Finish

func (p *ProgressTracker) Finish()

Finish prints the build-complete summary.

func (*ProgressTracker) FinishWithError

func (p *ProgressTracker) FinishWithError(err error)

FinishWithError prints the build-failed summary.

func (*ProgressTracker) Skip

func (p *ProgressTracker) Skip(reason string)

Skip marks the current step as skipped.

func (*ProgressTracker) Start

func (p *ProgressTracker) Start(description string)

Start marks the beginning of a new step and prints the pending state.

Jump to

Keyboard shortcuts

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