utils

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2026 License: MIT Imports: 19 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 是 KaTeX 样式表的 CDN 地址
	KaTeXCSSURL = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css"
	// KaTeXJSURL 是 KaTeX 核心 JS 的 CDN 地址
	KaTeXJSURL = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js"
	// KaTeXAutoRenderURL 是 KaTeX 自动渲染扩展的 CDN 地址,负责扫描文档中的 $...$ 和 $$...$$ 并渲染
	KaTeXAutoRenderURL = "https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/auto-render.min.js"
)

KaTeX CDN URL,统一版本号避免各处不一致。

View Source
const (
	// MaxImageSize is the maximum allowed size for a downloaded image (50 MB).
	MaxImageSize = 50 * 1024 * 1024
)
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 ImageExtensionMap = map[string]string{
	"image/jpeg":    ".jpg",
	"image/png":     ".png",
	"image/gif":     ".gif",
	"image/webp":    ".webp",
	"image/svg+xml": ".svg",
	"image/bmp":     ".bmp",
	"image/tiff":    ".tiff",
	"image/x-icon":  ".ico",
}

ImageExtensionMap maps MIME types to file extensions. This is used by multiple packages (epub, etc.) to ensure consistent MIME type handling.

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 ContainsCJK added in v0.3.1

func ContainsCJK(text string) bool

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

func ContainsChinese added in v0.3.1

func ContainsChinese(text string) bool

ContainsChinese reports whether the text contains Chinese characters specifically. This checks for CJK Unified Ideographs which are primarily Chinese 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 DownloadImage

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

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

func EnsureDir

func EnsureDir(path string) error

EnsureDir creates a directory when it does not already exist.

func Error

func Error(format string, args ...interface{})

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 ' 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 GetImageMIME

func GetImageMIME(path string) string

GetImageMIME returns a MIME type from the file extension.

func Green

func Green(text string) string

Green returns green text.

func Header(title string)

Header prints a titled separator.

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 ...interface{})

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 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.

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 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 Success

func Success(format string, args ...interface{})

Success prints a green success message with a checkmark prefix.

func Warning

func Warning(format string, args ...interface{})

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 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