utils

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 30 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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.

humanlog.go renders log records the way the rest of the terminal UI speaks.

The default logger used slog's key=value TextHandler at every verbosity, so the first warning a user ever saw was a machine line — spliced mid-line into the styled step progress, timestamps and quoting included. mdbook prints "warning: …", Docusaurus "[WARNING] …"; next to them the raw handler read like debug output that escaped into production. The TextHandler remains the right tool under --verbose, where the audience is a person debugging mdpress itself; this handler serves everyone else.

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

Index

Constants

View Source
const (
	// MermaidCDNURL is the CDN URL for the Mermaid diagram library.
	// Centralized here so every part of the codebase uses the same version.
	MermaidCDNURL = "https://cdn.jsdelivr.net/npm/mermaid@11.16.0/dist/mermaid.min.js"
	// MermaidSRI is the Subresource Integrity digest of MermaidCDNURL.
	MermaidSRI = "sha384-T/0lMUdJpd2S1ZHtRiofG3htU3xPCrFVeAQ1UUE2TJwlEJSV5NUwn30kP28n238E"

	// KaTeXCSSURL is the CDN URL for the KaTeX stylesheet.
	KaTeXCSSURL = "https://cdn.jsdelivr.net/npm/katex@0.16.44/dist/katex.min.css"
	// KaTeXCSSSRI is the Subresource Integrity digest of KaTeXCSSURL.
	KaTeXCSSSRI = "sha384-irXK0JiCGinqGL+slwVklbhJetrjczNwaP2lANewD8lKAs9n61SbQ3As28iSqXUE"
	// 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"
	// KaTeXJSSRI is the Subresource Integrity digest of KaTeXJSURL.
	KaTeXJSSRI = "sha384-m/s9umSlhJbqEdA/j7pQVdGCMx2fHf7GXtgCVhNGOwLuu+1qJQES5AzIE8pn3nKQ"
	// 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"
	// KaTeXAutoRenderSRI is the Subresource Integrity digest of KaTeXAutoRenderURL.
	KaTeXAutoRenderSRI = "sha384-bjyGPfbij8/NDKJhSGZNP/khQVgtHUE5exjm4Ydllo42FwIgYsdLO2lXGmRBf5Mz"
)

Mermaid and KaTeX are fetched from a public CDN when a reader opens a page that needs them. Two rules apply to every URL here:

  • Pin an exact version. `mermaid@11` was a floating range, so the bytes a reader executed could change without any mdpress release, and there was no fixed content to hash.
  • Ship a Subresource Integrity digest alongside it, so a tampered or substituted CDN response is rejected by the browser instead of running.

To move to a new version, change the URL and recompute the digest:

curl -sSL --compressed <url> | openssl dgst -sha384 -binary | openssl base64 -A

Verify the result against a second mirror (unpkg.com serves the same npm tarball) before committing it.

View Source
const (
	CacheDirTagName      = "CACHEDIR.TAG"
	CacheDirTagSignature = "Signature: 8a477f597d28d172789f06886806bc55"
	// CacheDirTagContent is what mdpress writes when it creates a cache root.
	CacheDirTagContent = CacheDirTagSignature + "\n" +
		"# This file is a cache directory tag created by mdpress.\n" +
		"# For information about cache directory tags, see https://bford.info/cachedir/\n"
)

The Cache Directory Tagging Specification (https://bford.info/cachedir/). A tagged directory is skipped by backup tools (restic, borg, tar --exclude-caches), and a tag that names mdpress is how `mdpress cache clear` knows the directory is one mdpress created rather than one a user pointed --cache-dir at.

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.

Variables

View Source
var ErrNoSVGElement = errors.New("no <svg> element found")

ErrNoSVGElement is returned by SanitizeSVG when the markup contains no <svg> element to keep.

View Source
var ErrSSRFBlocked = errors.New("blocked by SSRF protection")

ErrSSRFBlocked marks a request refused because its target is a private, loopback or link-local address. It is never worth retrying.

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.

Besides the explicit MDPRESS_DISABLE_CACHE opt-out, caching is refused when the cache root is not a private directory belonging to this user: trusting a tree someone else can write to is the same as trusting their HTML.

func CacheOptedOut added in v0.9.0

func CacheOptedOut() bool

CacheOptedOut reports the explicit MDPRESS_DISABLE_CACHE opt-out (which --no-cache sets). Unlike CacheDisabled it has no side effects: it never creates or inspects the cache root, so read-only commands can call it.

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.

The default is the per-user cache directory, not the system temp dir. A parsed-chapter cache entry's HTML is emitted into the published book verbatim, so a cache at a fixed path under a shared, world-writable /tmp let any other local user pre-create the tree and plant entries — arbitrary script in someone else's site, from a build that reports success, and it defeated markdown.allow_html: false, the setting whose entire purpose is publishing content you did not write.

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. It is DownloadImageContext with context.Background().

func DownloadImageContext added in v0.9.0

func DownloadImageContext(ctx context.Context, urlStr string, destDir string) (string, error)

DownloadImageContext downloads an image from a URL into destDir and returns the local path, reusing a previously cached download when there is one.

Canceling ctx (Ctrl+C) aborts the transfer and any pending retry. Only transient failures are retried — timeouts, connection resets, HTTP 5xx and 429 (honoring a Retry-After of up to 10s) — with exponential backoff, up to three attempts. SSRF refusals, 4xx responses and other permanent errors fail on the first attempt.

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 EvalSymlinksAncestor added in v0.7.10

func EvalSymlinksAncestor(path string) string

EvalSymlinksAncestor resolves symlinks on the nearest existing ancestor of path and re-appends the non-existent tail. This handles the case where filepath.EvalSymlinks fails because the leaf file does not exist yet, but an intermediate directory is a symlink pointing outside the base.

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 InterruptPendingLine added in v0.8.3

func InterruptPendingLine() bool

InterruptPendingLine reports whether a progress line is currently open, and records the interruption so its owner reprints the line. The caller is expected to start its own output on a fresh line when this returns true.

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 IsExternalAssetRef added in v0.8.0

func IsExternalAssetRef(ref string) bool

IsExternalAssetRef reports whether an asset reference points somewhere the build must not touch: another origin (https://…, //cdn…), an inline data URI, or a site-root-absolute path that the deployment supplies itself. Anything else is a path inside the project, to be resolved and copied.

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 SanitizeSVG added in v0.9.0

func SanitizeSVG(markup string) (string, error)

SanitizeSVG returns the first <svg> element of markup with everything that can execute script or load third-party content removed. It is intended for SVG that will be inlined into an HTML document, where — unlike an SVG loaded through <img> — any script, event handler or javascript: link runs with the page's privileges.

The markup is parsed with the same HTML5 parser rules a browser applies to inline SVG, so the sanitizer sees exactly the tree the browser would build (no regex/parser differential). Elements are filtered against an allowlist; attributes lose event handlers (on*), script-bearing values, external <use> references and non-fragment URL references; <style> blocks containing @import or script URLs are dropped.

func SanitizedGitEnv added in v0.8.3

func SanitizedGitEnv() []string

SanitizedGitEnv returns the process environment without the variables that would redirect git away from the directory the command selects itself. Use it as the base environment for any git subprocess.

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 WriteFileAtomic added in v0.8.3

func WriteFileAtomic(path string, data []byte, perm os.FileMode) error

WriteFileAtomic writes data to path via a temp file in the same directory that is then renamed into place, so a failed or interrupted write can never replace an existing good file at path with a truncated or empty one. Unlike os.WriteFile, which opens the destination with O_TRUNC before writing, a write error here (ENOSPC, a quota, an NFS error on close) leaves the original file untouched and removes the temp file. The rename is atomic on a single filesystem, which the same-directory temp guarantees.

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 HumanLogHandler added in v0.8.3

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

HumanLogHandler formats records as single styled lines:

⚠ intro.md: Markdown link target is outside the build graph: ./nothere.md

A record's attributes are folded into the sentence rather than appended as key=value pairs: one attribute names the subject (file, path, src, …), one carries the substance (detail, error, hint), and whatever remains prints as a short parenthetical. It also coordinates with the step progress so a warning never lands in the middle of a pending "2/5 … ..." line.

func NewHumanLogHandler added in v0.8.3

func NewHumanLogHandler(out *os.File, level slog.Leveler) *HumanLogHandler

NewHumanLogHandler returns a handler writing styled lines to out.

func (*HumanLogHandler) Enabled added in v0.8.3

func (h *HumanLogHandler) Enabled(_ context.Context, level slog.Level) bool

Enabled implements slog.Handler.

func (*HumanLogHandler) Handle added in v0.8.3

func (h *HumanLogHandler) Handle(_ context.Context, r slog.Record) error

Handle implements slog.Handler.

func (*HumanLogHandler) WithAttrs added in v0.8.3

func (h *HumanLogHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs implements slog.Handler.

func (*HumanLogHandler) WithGroup added in v0.8.3

func (h *HumanLogHandler) WithGroup(string) slog.Handler

WithGroup implements slog.Handler. mdpress does not log groups; the name is dropped rather than modeled.

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
	// ContainmentRoot bounds where a relative image may resolve to. Paths are
	// resolved against the chapter's own directory, but validated against this
	// root, so a shared `../assets/logo.png` works while `../../etc/passwd`
	// still does not. Empty falls back to the chapter directory, which silently
	// dropped every parent-relative image.
	ContainmentRoot string
	// LocalURLPrefix, when set (and neither EmbedLocalAsBase64 nor
	// RewriteLocalToFileURL is), rewrites each local image to LocalURLPrefix
	// followed by its path relative to ContainmentRoot (or the chapter
	// directory when that is empty). It is meant for a document served over
	// HTTP from that root, such as the PDF generator's local server
	// (pdf.AssetURLPrefix with pdf.WithAssetRoot): the browser then loads each
	// file once instead of decoding a base64 copy per reference. SVGs with CJK
	// text are still inlined, as with EmbedLocalAsBase64.
	LocalURLPrefix string
	// Context, when set, bounds remote image downloads: canceling it (for
	// example on Ctrl+C) aborts in-flight transfers and pending retries, and
	// no new download starts. Nil means context.Background().
	Context context.Context
	// QuietUnresolved suppresses the warning for a local image that cannot be
	// found or resolves outside ContainmentRoot. It is meant for a second pass
	// over HTML whose images an earlier pass already reported, so each broken
	// reference is reported once rather than once per pass. Other warnings
	// (an image that exists but cannot be embedded) are still logged.
	QuietUnresolved bool
}

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
	// Truncated is set once any byte has been discarded, so a caller can
	// report "output too large" instead of failing later on the cut-off data.
	Truncated bool
}

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) SetSilent added in v0.8.0

func (p *ProgressTracker) SetSilent(silent bool)

SetSilent suppresses the per-step output. --quiet documents itself as "only output errors", but the five-step progress and the completion banner were printed regardless, so piping a quiet build still produced a screenful. The final "Generated <format> → <path>" summary is printed by the caller and deliberately survives quiet mode: it is the one line a script wants.

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