PTerm 示例库实战指南:89 个可运行示例、四大 Printer 家族与示例驱动的文档动画流水线

原创2026-10-14 09:52:092,179 阅读
文章标签:开发工具

PTerm 示例库实战指南:89 个可运行示例、四大 Printer 家族与示例驱动的文档动画流水线

本文以 _examples/README.md 这份示例目录文档为核心,带你完整走一遍 PTerm(github.com/pterm/pterm)示例库的目录组织、运行方式与 28 个功能分区、89 个可运行示例的分布,并结合 printers.go、scripts/animate.sh 等仓库源码,讲清楚示例代码如何成为文档与动画的单一事实来源(single source of truth)。读完后你既能快速找到并运行任意 printer 的示例,也能理解示例驱动的 README/动画生成流水线,乃至按项目约定编写自己的新示例。

1. 示例库定位:目录组织与运行方式

_examples/ 是 PTerm 面向用户的"活文档":每个示例都是一个小型、自包含的 Go 程序,只演示一个 printer 或一个功能特性。示例文档 _examples/README.md 的开头明确了三点组织原则:

  • 目录布局为 <printer>/<example>,例如 table/demo、box/title;
  • 每个示例文件夹都有自己的 main.go(包名固定为 main),外加由流水线生成的 README.md 与动画 GIF;
  • 动画和 README 中的示例章节由动画流水线(task animations)从各 main.go 生成,因此 main.go 才是唯一可信来源,不要手改生成的部分。

1.1 直接运行任意示例

每个示例文件夹可独立运行。以文档中给出的示例为例:

cd table/demo
go run main.go

这里有两个关键前提值得注意:

  1. 下划线前缀隔离构建:_examples 目录名以下划线开头,Go 工具链会跳过它,所以根目录执行 go build ./... 不会编译示例;反过来,每个示例需要进到自己目录里单独构建。项目约定每个示例必须能独立通过 go build ./...(在示例文件夹内执行)。
  2. 版本前提:根据 go.mod,模块为 github.com/pterm/pterm,要求 Go 1.26.0+。示例直接 import "github.com/pterm/pterm",在仓库内运行时由根模块提供依赖;若在自己项目中运行,需 go get github.com/pterm/pterm 引入(仓库只读,此处仅说明安装方式)。

示例中还有一类"交互型"程序(confirm/select/multiselect/textinput/continue),它们会阻塞等待按键输入;在 CI 环境下需要 ci.go 或 keys.tape 自动化(见第 5 节),否则录制会超时。

1.2 批量人工验证脚本

仓库提供了 _examples/test.sh 用于逐个人工验证示例。它的逻辑是:

  • 自动 cd 进 _examples 目录;
  • 遍历每个分区目录(ls -d */ | grep -v demo,跳过顶层 demo 分区,因为那是 15 秒倒计时的集成演示,不适合快速验证);
  • 再遍历每个示例子目录执行 go run main.go;
  • 每个示例跑完后询问 Was the example successful? (y/n),按 n 会打印红色高亮的失败示例完整路径并立即退出。

2. 示例总目录:28 个分区、89 个示例

对当前仓库 _examples 目录的枚举统计显示,共有 28 个分区、89 个 main.go 示例(示例文档 _examples/README.md 中每个分区以 ### <section>/<name> 小节列出,附动画与折叠源码)。完整目录如下,可把它当作 PTerm 能力地图使用:

分区 示例数 示例列表(<分区>/<示例>) 演示内容
area 6 demo、center、default、dynamic-chart、fullscreen、fullscreen-center LivePrinter 动态区域:原地重绘、居中、全屏、配合 BigText/BarChart 做实时时钟与动态图表
barchart 9 demo、custom-height、custom-width、default、horizontal、horizontal-show-value、mixed-values、negative-values、show-value 条形图:竖直/水平方向、高度/宽度缩放、显示数值、正负混合值布局
basictext 1 demo 无样式基础文本 printer,满足 TextPrinter 接口可替换任意带样式 printer
bigtext 3 demo、colored、default ASCII 大字号艺术字:整字着色、逐段 LettersFromStringWithStyle、TrueColor RGB 与自动降采样
box 4 demo、custom-padding、default、title 边框盒:自适应尺寸、四边 padding、标题在七种边框位置的摆放、嵌套成网格
bulletlist 2 demo、customized 项目符号列表:Level 缩进、putils.BulletListFromString 从缩进字符串构建、逐项自定义符号与样式
center 1 demo 居中打印:整块居中(默认)与 WithCenterEachLineSeparately 逐行居中
coloring 8 demo、disable-output、fade-colors、fade-colors-rgb-style、fade-multiple-colors、override-default-printers、print-color-rgb、print-color-rgb-style 颜色体系:16 ANSI 前景/背景色、pterm.Red 等简写函数、NewStyle 组合、RGB.Fade 渐变、DisableOutput/EnableOutput、覆盖默认 printer
demo 1 demo PTDP 集成演示:依次展示 Logging、Progressbar、Spinner、Live Output、Tables、TrueColor、可定制性、主题等章节
header 2 demo、custom 标题头:默认宽度、WithFullWidth 全宽、WithMargin/样式重设、从零构造 HeaderPrinter 结构体
heatmap 6 demo、custom_colors、custom_legend、custom_rgb、no_grid、separated 热力图:HeatmapAxis 坐标轴、ANSI 自定义色板、TrueColor 渐变与 WithRGBRange 渐变停靠点、图例、去网格/去框
interactive_confirm 2 demo、custom-answers 确认提示:y/n 快捷键、默认值、WithConfirmText/WithRejectText 自定义答案文本
interactive_continue 1 demo 连续选择提示:默认 yes/no/all/cancel,首字母选择,回车取默认
interactive_multiselect 5 demo、custom-checkmarks、custom-filter-placeholder、custom-keys、show-selected-options 多选菜单:模糊搜索过滤、滚动、自定义勾选符号、重绑定确认/选择键、已选项列表
interactive_select 2 demo、custom-filter-placeholder 单选菜单:长列表滚动 + 模糊过滤、自定义过滤框占位符
interactive_textinput 4 demo、default-value、multi-line、password 文本输入:单行回车提交、默认值预填、多行模式(回车换行/tab 提交)、WithMask 密码掩码
logger 5 demo、custom-key-styles、default、json、with-caller 结构化日志:六级日志、Args/ArgsFromMap、JSON formatter、WithCaller 调用位置、按键自定义样式、长消息自动换行、Fatal 退出
multiple-live-printers 1 demo DefaultMultiPrinter 同时渲染 2 个 Spinner + 5 个 Progressbar,各自独立速率推进
panel 2 demo、boxed 二维面板网格:pterm.Panels 行列结构、WithPadding、WithBoxPrinter 套框、WithSameColumnWidth 列对齐
paragraph 2 demo、customized 段落 printer:按词边界自动换行(对比裸 Println 的任意折行)、WithMaxWidth 限宽
prefix 2 demo、custom 前缀 printer:Info/Success/Warning/Error/Fatal 家族、WithShowLineNumber、从零构造带 Scope 的 PrefixPrinter
progressbar 3 demo、custom-style、multiple 进度条:Increment/Add、运行中输出不打断进度条、全套字符/样式换装、多进度条并发
section 1 demo 章节标题:WithLevel 控制子节层级
slog 1 demo pterm.NewSlogHandler 接入标准库 log/slog,PTerm logger 级别实时生效
spinner 3 demo、custom、multiple 旋转指示器:四种收尾(Info/Success/Warning/Fail)、替换 InfoPrinter、自定义帧序列 WithSequence、多 Spinner 并发
style 1 demo NewStyle 组合多颜色与 Bold/Italic 等选项,Style 本身也是 TextPrinter
table 7 demo、alternate-row-style、boxed、from-csv、from-structs、multiple-lines、right-alignment 表格:表头样式、CJK 显示宽度对齐、单元格内换行、斑马纹、CSV/结构体反射建表、右对齐、行分隔符
theme 1 demo 默认主题 ThemeDefault:用反射遍历并逐字段打印全部主题样式
tree 3 demo、from-leveled-list、styled 树形结构:TreeNode 嵌套、LeveledList 平铺列表转换、分支线/节点文本独立着色

分区与示例数的统计基于对仓库 _examples 目录的实际枚举;示例文档 _examples/README.md 中的 ### 小节与之一一对应。

3. 四大 Printer 家族:示例分区背后的 API 骨架

理解示例分区最快的方式是先认识 PTerm 的四个 printer 家族。printers.go 用编译期断言(var _ TextPrinter = ... 等)强制每个 printer 归入唯一家族,示例分区与家族的对应关系非常清晰:

家族 接口/形态 核心方法 对应示例分区
TextPrinter interface_text_printer.go Sprint/Sprintln/Sprintf/Sprintfln(返回字符串)+ Print/Println/...(写出) basictext、prefix、header、section、box、center、paragraph、style、coloring
RenderPrinter interface_renderable_printer.go Render()(写出)、Srender()(返回字符串) table、tree、barchart、bulletlist、panel、heatmap、bigtext
LivePrinter interface_live_printer.go Start() 启动(返回已启动实例)、Stop() 结束,期间原地刷新 spinner、progressbar、area、multiple-live-printers
交互式 printer 无共享接口(返回类型不同),遵循 Default* + With* + Show() 约定 Show() 阻塞读取输入并返回结果 interactive_confirm、interactive_continue、interactive_select、interactive_multiselect、interactive_textinput

家族设计对写代码的直接价值在 Sprint*/Srender 这类"返回字符串"方法上:它们让 printer 之间可以互相嵌套组合。示例文档中大量用到这一点,例如 box/demo 用 DefaultBox.Sprint(...) 得到字符串后再塞进 panel 的 Data;area/demo 用 DefaultBigText...Srender() 渲染时钟字符串再 area.Update(str) 原地换帧。

3.1 Builder 模式:With* 永不修改原 printer

所有 printer 遵循同一套 builder 约定:With* 方法使用值接收者,修改副本并返回指向副本的指针。因此链式调用是安全、无副作用的——这解释了示例文档 box/title 中 paddedBox 能作为模板被复用、派生出 7 个不同标题位置的盒:

// One box per title position. WithTitle* methods return a modified copy,
// so paddedBox can be reused as a template without being changed.
paddedBox := pterm.DefaultBox.WithLeftPadding(4).WithRightPadding(4).WithTopPadding(1).WithBottomPadding(1)

// Titles may contain styled text.
title := pterm.LightRed("I'm a box!")

box1 := paddedBox.WithTitle(title).Sprint("Hello, World!\n      1") // top left is the default
box2 := paddedBox.WithTitle(title).WithTitleTopCenter().Sprint("Hello, World!\n      2")
box3 := paddedBox.WithTitle(title).WithTitleTopRight().Sprint("Hello, World!\n      3")
box4 := paddedBox.WithTitle(title).WithTitleBottomRight().Sprint("Hello, World!\n      4")
box5 := paddedBox.WithTitle(title).WithTitleBottomCenter().Sprint("Hello, World!\n      5")
box6 := paddedBox.WithTitle(title).WithTitleBottomLeft().Sprint("Hello, World!\n      6")
box7 := paddedBox.WithTitle(title).WithTitleTopLeft().Sprint("Hello, World!\n      7")

pterm.DefaultPanel.WithPanels([][]pterm.Panel{
	{{box1}, {box2}, {box3}},
	{{box4}, {box5}, {box6}},
	{{box7}},
}).Render()

来源:_examples/box/title/main.go。

另外,coloring/override-default-printers 展示了与 builder 互补的另一条定制路径:默认 printer 本身就是包级变量(pterm.Error 等),其字段(如 Prefix)可以直接赋值修改,影响之后所有对该默认 printer 的调用:

pterm.Error.Println("This is the default Error")

// The default printers are package-level variables, so their fields can
// be changed directly. This swaps the Error prefix text and style for
// every subsequent pterm.Error call in the program.
pterm.Error.Prefix = pterm.Prefix{Text: "OVERRIDE", Style: pterm.NewStyle(pterm.BgCyan, pterm.FgRed)}

pterm.Error.Println("This is the default Error after the prefix was overridden")

来源:_examples/coloring/override-default-printers/main.go。

4. 按家族精读代表性示例

下面从示例文档中挑选每个家族最具代表性的示例,完整保留其源码并补充实现背景。所有代码均可在 _examples/<分区>/<示例>/main.go 逐字核对。

4.1 RenderPrinter:table/demo —— CJK 宽度与多行单元格

表格示例是示例文档中"能力密度"最高的之一,同时验证了两个易踩坑点:CJK 字符按显示宽度度量(列不会错位)、单元格可含换行(行高自动撑开):

package main

import "github.com/pterm/pterm"

func main() {
	// With WithHasHeader the first row is styled as the header. The CJK
	// characters are measured by display width, so the columns stay aligned.
	tableData1 := pterm.TableData{
		{"Firstname", "Lastname", "Email", "Note"},
		{"Paul", "Dean", "augue@velitAliquam.co.uk", ""},
		{"Callie", "Mckay", "nunc.sed@est.com", "这是一个测试, haha!"},
		{"Libby", "Camacho", "lobortis@semper.com", "just a test, hey!"},
		{"张", "小宝", "zhang@example.com", ""},
	}

	pterm.DefaultTable.WithHasHeader().WithData(tableData1).Render()

	pterm.Println()

	// Cells may contain newlines; a row grows to fit its tallest cell.
	tableData2 := pterm.TableData{
		{"Firstname", "Lastname", "Email"},
		{"Paul\n\nNewline", "Dean", "augue@velitAliquam.co.uk"},
		{"Callie", "Mckay", "nunc.sed@est.com\nNewline"},
		{"Libby", "Camacho", "lobortis@semper.com"},
		{"张", "小宝", "zhang@example.com"},
	}

	pterm.DefaultTable.WithHasHeader().WithData(tableData2).Render()
}

来源:_examples/table/demo/main.go。table 分区其余 6 个示例分别覆盖:WithBoxed 整表套框(table/boxed)、斑马纹 WithAlternateRowStyle(table/alternate-row-style)、putils.TableDataFromCSV 从 CSV 建表(table/from-csv)、putils.DefaultTableFromStructSlice 反射结构体切片建表(table/from-structs)、WithRowSeparator/WithHeaderRowSeparator 配合多行单元格(table/multiple-lines)、WithRightAlignment(table/right-alignment)。

4.2 TextPrinter:prefix/custom —— 从零构造前缀 printer

PrefixPrinter 只是一个普通结构体,内置的 Info/Success/Error 等就是按同样方式构造的。示例展示了完全自定义 printer,包括前缀之后以方括号打印的 Scope(适合标注子系统/组件名):

package main

import "github.com/pterm/pterm"

func main() {
	// A PrefixPrinter is just a struct, so custom printers can be built from
	// scratch. The built-ins (Info, Success, ...) are constructed the same way.
	deploy := pterm.PrefixPrinter{
		Prefix: pterm.Prefix{
			Text:  "DEPLOY",
			Style: pterm.NewStyle(pterm.BgLightMagenta, pterm.FgBlack),
		},
		// The scope is printed after the prefix in brackets. Useful for
		// tagging messages with a subsystem or component name.
		Scope: pterm.Scope{
			Text:  "database",
			Style: pterm.NewStyle(pterm.FgGray),
		},
		MessageStyle: pterm.NewStyle(pterm.FgLightMagenta),
	}

	deploy.Println("Running migrations...")
	deploy.Println("Migrations complete!")

	// Existing printers can be tweaked on the fly. With* methods return a
	// modified copy, so pterm.Info itself stays untouched.
	pterm.Info.WithScope(pterm.Scope{
		Text:  "api",
		Style: pterm.NewStyle(pterm.BgGray, pterm.FgLightWhite),
	}).Println("Listening on port 8080")
}

来源:_examples/prefix/custom/main.go。姊妹示例 prefix/demo 还覆盖了 pterm.EnableDebugMessages()(Debug 默认隐藏)、pterm.Error 自动附带文件名与行号、WithShowLineNumber、以及 pterm.Fatal.WithFatal(false) 关闭致命退出。

4.3 LivePrinter:area/dynamic-chart —— 字符串渲染 + 区域换帧

Area 是 LivePrinter 家族的"画布":内容通过 Update 原地重绘,而不是追加新行。area/dynamic-chart 是"RenderPrinter 字符串 + LivePrinter 画布"组合模式的典型:

package main

import (
	"time"

	"github.com/pterm/pterm"
)

func main() {
	// A live bar chart: render the chart to a string each tick and let the
	// area redraw it in place. Fullscreen gives the area the whole terminal.
	area, _ := pterm.DefaultArea.WithFullscreen().WithCenter().Start()
	defer area.Stop()

	for i := range 10 {
		barchart := pterm.DefaultBarChart.WithBars(dynamicBars(i))
		content, _ := barchart.Srender()
		area.Update(content)
		time.Sleep(500 * time.Millisecond)
	}
}

// dynamicBars returns the chart data for the given tick. B and D grow over
// time, A and C stay constant.
func dynamicBars(i int) pterm.Bars {
	return pterm.Bars{
		{Label: "A", Value: 10},
		{Label: "B", Value: 20 * i},
		{Label: "C", Value: 30},
		{Label: "D", Value: 40 + i},
	}
}

来源:_examples/area/dynamic-chart/main.go。area 分区其余示例依次演示:Start/Update/Stop 基本循环(default)、WithCenter 横向居中(center)、WithFullscreen 接管整屏并在 Stop() 时清屏还原(fullscreen、fullscreen-center)、以及把 BigText 时钟渲染成字符串后 Update 进居中区域、且区域之外先前打印的文本保持不动(demo)。progressbar/demo 则展示了另一个实用特性:进度条运行期间穿插 pterm.Success.Println 等输出,文本会出现在进度条上方而不会打断条的渲染。

4.4 交互式 printer:custom-keys 与 password

交互式示例都通过 Show() 返回结果。interactive_multiselect/custom-keys 展示按键重绑定——默认是"回车切换选项、tab 确认",这里改为"空格切换、回车确认",并关闭过滤避免打字干扰:

package main

import (
	"fmt"

	"atomicgo.dev/keyboard/keys"

	"github.com/pterm/pterm"
)

func main() {
	var options []string
	for i := 0; i < 5; i++ {
		options = append(options, fmt.Sprintf("Option %d", i))
	}

	// By default, enter toggles an option and tab confirms the selection.
	// Both keys can be rebound, here to space for toggling and enter for
	// confirming. The filter is disabled so typing is not needed.
	printer := pterm.DefaultInteractiveMultiselect.
		WithOptions(options).
		WithFilter(false).
		WithKeyConfirm(keys.Enter).
		WithKeySelect(keys.Space)

	selectedOptions, _ := printer.Show()

	pterm.Info.Printfln("Selected options: %s", pterm.Green(selectedOptions))
}

来源:_examples/interactive_multiselect/custom-keys/main.go。

文本输入侧,WithMask 一行即可把输入框变成密码提示(掩码回显为 *):

package main

import "github.com/pterm/pterm"

func main() {
	// WithMask echoes the given string instead of the typed characters,
	// which turns the text input into a password prompt.
	passwordInput := pterm.DefaultInteractiveTextInput.WithMask("*")

	result, _ := passwordInput.Show("Enter your password")

	// Never log passwords in a real application, this is just a demo.
	logger := pterm.DefaultLogger
	logger.Info("Password received", logger.Args("password", result))
}

来源:_examples/interactive_textinput/password/main.go。同分区的 default-value(预填默认值,回车直接返回)与 multi-line(WithMultiLine() 后回车换行、tab 提交)补齐了输入场景。

4.5 coloring:Fade 多停靠点渐变与 RGBStyle

coloring/fade-multiple-colors 展示了 RGB.Fade 的核心用法:第一个参数是取值下界、第二个是上界、第三个是当前因子,后续可变参数是渐变途经的停靠点——水平方向逐字符横向渐变,垂直方向按终端高度逐行渐变,一行之内即可从青色一路经过品红、红、绿到达白色:

package main

import (
	"strings"

	"github.com/pterm/pterm"
)

func main() {
	// Fade accepts multiple target colors, so a gradient can pass through
	// several points instead of just blending between two.
	startColor := pterm.NewRGB(0, 255, 255)
	firstPoint := pterm.NewRGB(255, 0, 255)
	secondPoint := pterm.NewRGB(255, 0, 0)
	thirdPoint := pterm.NewRGB(0, 255, 0)
	endColor := pterm.NewRGB(255, 255, 255)

	str := "RGB colors only work in Terminals which support TrueColor."
	strs := strings.Split(str, "")

	// Fade a single line horizontally, character by character.
	var fadeInfo string
	for i := 0; i < len(str); i++ {
		fadeInfo += startColor.Fade(0, float32(len(str)), float32(i), firstPoint).Sprint(strs[i])
	}

	pterm.Info.Println(fadeInfo)

	terminalHeight := pterm.GetTerminalHeight()

	// Fade vertically over the visible terminal height, passing through all
	// four gradient points from top to bottom.
	for i := 0; i < terminalHeight-2; i++ {
		startColor.Fade(0, float32(terminalHeight-2), float32(i), firstPoint, secondPoint, thirdPoint, endColor).Println("Hello, World!")
	}
}

来源:_examples/coloring/fade-multiple-colors/main.go。

需要强调适用前提:示例注释明确写了 "RGB colors only work in Terminals which support TrueColor"。从源码结构看,终端颜色能力检测与 RGB 降采样位于 internal/color(internal/color/downsample.go),终端不支持 TrueColor 时 PTerm 会自动降采样到最接近的支持色;PrintColor 还会在初始化时依据 NO_COLOR、TERM=dumb、FORCE_COLOR 等环境变量自动判定。

fade-colors-rgb-style 进一步演示了 NewRGBStyle(fg, bg) 让前景/背景独立渐变,并用 AddOptions(pterm.Bold) 在渐变之上叠加文本属性(AddOptions 返回新样式,互不影响)。print-color-rgb 则展示了 NewRGB(r, g, b, true) 最后一个可选参数表示作用于背景。

4.6 heatmap/custom_rgb —— 渐变停靠点配置

热力图分区的 custom_rgb 示例完整展示了 WithRGBRange 的配置方式:最低值取第一个颜色、最高值取最后一个颜色、中间按位置插值:

	// The RGB range defines the gradient stops: the lowest value gets the
	// first color, the highest the last, and everything in between is faded.
	rgbRange := []pterm.RGB{
		pterm.NewRGB(0, 0, 255),
		pterm.NewRGB(255, 0, 0),
		pterm.NewRGB(0, 255, 0),
		pterm.NewRGB(255, 255, 0),
	}

	pterm.DefaultHeatmap.
		WithData(data).
		WithBoxed(false).
		WithAxisData(axisLabels).
		WithEnableRGB().
		WithRGBRange(rgbRange...).
		Render()

来源:_examples/heatmap/custom_rgb/main.go。该分区另外五个示例分别演示:默认调色板 + 坐标轴 + RGB 模式(demo)、WithColors 用 ANSI 背景色替换色板(任意终端可用)+ WithLegend(custom_colors)、WithLegendLabel/WithLegendOnlyColoredCells 自定义图例(custom_legend)、WithGrid(false) 去掉单元格分隔形成连续色面(no_grid)、去掉外框与图例(separated)。

5. 交互示例的 CI 自动化:ci.go 与 keys.tape

交互式示例必须能在无人值守的 CI 中被录制,否则动画流水线会卡死。项目约定(见 AGENTS.md):每个交互示例要么提供一个在 CI=true 时模拟按键的 ci.go,要么提供一个 keys.tape 文件。

以 _examples/interactive_confirm/demo/ci.go 为例,实现非常薄——在 init 中检查环境变量,两秒后通过 keyboard.SimulateKeyPress('y') 模拟用户按键:

package main

import (
	"os"
	"time"

	"atomicgo.dev/keyboard"
)

// ------ Automation for CI ------
// Simulates the user's keystrokes when CI=true, so the demo can run
// unattended and be recorded for the example animation. You can ignore this file.
func init() {
	if os.Getenv("CI") == "true" {
		go func() {
			time.Sleep(time.Second * 2)
			keyboard.SimulateKeyPress('y')
		}()
	}
}

录制脚本 scripts/record-example.sh 会把这一约定落到执行层面:对 interactive_* 分区,若示例目录既没有 ci.go 也没有 keys.tape,流水线会打印警告 No ci.go automation or keys.tape found for ...;若有 keys.tape,其内容会被追加进 VHS tape 以回放按键序列。运行器还会显式导出 CI=true 与 TERM=xterm-256color,保证录制环境的确定性。

6. 动画生成流水线:从 main.go 到 README 的全链路

示例文档反复强调"README 小节与动画由 task animations 从 main.go 生成"。这条流水线在仓库中的完整实现是:

task animations
  └─ scripts/animate.sh
       ├─ 并发(ANIMATE_JOBS,默认 nproc)调度 scripts/record-example.sh 逐例录制
       │    ├─ go build 示例(生成 .pterm-vhs-example 二进制与 runner 脚本)
       │    ├─ VHS(Docker 镜像,默认 VHS_DOCKER_IMAGE 为 ghcr.io/charmbracelet/vhs:latest)执行 tape:
       │    │    1200×600、60fps、主题 catppuccin-macchiato,输出 animation.gif
       │    │    并同时把原始终端输出写成黄金文件 testdata/raw/<分区>_<示例>.txt
       │    └─ 发布 GIF 并记录 manifest(相对路径 → GIF URL)
       ├─ scripts/render-animation-docs.sh 依据 manifest 重写文档
       └─ scripts/update-unittestcount.sh 刷新单元测试计数徽章

对应的 Task 定义见 Taskfile.yml,有三个入口:

命令 作用
task animations 完整流程:录制、发布 GIF、更新文档
task animations:dry 本地录制(--dry-run),生成 GIF 与黄金文件,跳过发布与文档更新
task animate -- <section>/<example> 只渲染单个示例,如 task animate -- logger/default

依赖方面,scripts/animate.sh 启动时会检查 go、docker、python3、realpath 四个命令,并通过 ANIMATE_JOBS 环境变量控制并发数(默认取 nproc)。

6.1 生成物与回写点

scripts/render-animation-docs.sh 是"生成回写"的核心,它做四类事:

  1. 生成每个示例的 README:为 _examples/<rel>/README.md 写入 # <分区>/<示例> 标题、动画 GIF 与完整源码块(例如 _examples/table/demo/README.md);
  2. 重写示例目录正文:把所有分区小节(### 分区/示例 + GIF + 折叠源码 <details>)拼成正文,用标记替换法写入 _examples/README.md 的 <!-- examples:start --> 与 <!-- examples:end --> 之间,同时替换 README.md 中同名标记区间——替换逻辑在 scripts/animation-common.sh 的 replace_between 函数中,标记缺失会直接报错退出;
  3. 重建 printer 特性表:扫描 _examples 一级目录(排除 README.md 与 demo),生成特性表格写入 README 的 <!-- printers --> 标记区,并生成 docs/index.html 中的 printer 列表;
  4. 更新演示 GIF:用 demo/demo 的发布 URL 正则替换 README.md 与 docs/index.html 中的主演示动画链接,替换不到恰好一处会报错终止。

这就解释了示例文档的"勿手改"警告:_examples/README.md 中 <!-- examples:start -->(第 20 行)到 <!-- examples:end -->(第 3629 行)之间的全部内容,以及每个示例目录下的 README.md/animation.gif,都是上述脚本的产物;唯一可信来源是各示例的 main.go。

6.2 黄金文件与测试数据

录制时 VHS 的 Output 指令会把终端原始文本落到 testdata/raw/ 下,文件名规则是"相对路径中的 / 替换为 _"(见 scripts/animation-common.sh 中 example_key 函数),例如 table/demo → testdata/raw/table_demo.txt,heatmap/custom_colors → testdata/raw/heatmap_custom_colors.txt。当前仓库中 testdata/raw 下已存有与 89 个示例一一对应的 89 份原始输出,可与快照测试(testdata/snapshots/*.snap,由 snapshot_test.go 驱动,每个 printer 分别以 styled/plain 两种形态比对)互为参照:前者锁定"示例程序真实跑出的终端画面",后者锁定"printer 渲染结果的回归基线"。

7. 运行验证:从单例到全量

把前面各节串起来,日常开发中与示例库打交道的完整操作面如下:

# 1) 运行单个示例(最常用)
cd _examples/table/demo && go run main.go

# 2) 验证单个示例可独立构建(项目约定:每个示例必须能单独 go build)
cd _examples/box/title && go build ./...

# 3) 只本地录制一个示例的动画(不发布、不更新文档)
task animate -- logger/default

# 4) 本地全量录制(生成 GIF 与 testdata/raw 黄金文件)
task animations:dry

# 5) 完整流水线:录制 + 发布 + 重写 README/_examples/README.md 生成区
task animations

# 6) 人工逐例走查(交互式确认 y/n,跳过顶层 demo 分区)
bash _examples/test.sh

# 7) 单元测试(含竞态检测;快照比对见 snapshot_test.go)
task test

其中 task test 展开为 CGO_ENABLED=1 go test -race ./...;若你有意修改了渲染输出,需按 AGENTS.md 说明用 UPDATE_SNAPSHOTS=1 go test ./... 再生成快照并审阅 diff(CI 环境下该变量被忽略,防止快照在 CI 中被静默改写)。

8. 编写新示例的项目约定

如果你要为 PTerm 贡献示例,AGENTS.md 给出了明确的准入规则:

  • 新 printer:必须新建 _examples/<printer>/ 目录,且至少包含一个 demo 示例——demo 示例是文档中每个分区最先展示、被 README 特性表引用的那个;
  • 既有 printer 新增主要功能/选项:为它单独开一个小而聚焦的目录(如 table/from-csv 就是为 CSV 建表单独开的),不要求每个设置都有示例,但主要功能应该各有一个;
  • 行为或 API 变化:更新受影响的示例,使其仍能编译并展示当前最佳实践;
  • 代码风格:保持短小自包含,使用小而真实的演示数据;注释应解释意图或 PTerm 行为("human-written"口吻),而不是叙述语法;
  • 交互示例:必须附带 ci.go(CI=true 时模拟按键,参考 _examples/interactive_confirm/demo/ci.go)或 keys.tape,保证动画可无人值守录制。

9. 小结

_examples/ 是 PTerm 仓库中"文档即代码"的集中体现:89 个 main.go 既是给开发者的可复制范例(覆盖 TextPrinter/RenderPrinter/LivePrinter/交互式四大家族的 28 个功能分区),又是 README、示例文档、动画 GIF 与 testdata/raw 黄金文件这四处内容的唯一来源;task animations 流水线(scripts/animate.sh + scripts/record-example.sh + scripts/render-animation-docs.sh)负责在 main.go 与文档之间保持同步。掌握 cd _examples/<分区>/<示例> && go run main.go 的运行姿势、记住"生成区勿手改、示例须独立可构建、交互示例须带 CI 自动化"这三条约定,就能在 PTerm 中高效地查阅、验证和扩展全部示例内容。

登录后查看全文
pterm