pterm SectionPrinter 实战:用「章节式」标题为终端输出建立结构层级

原创2026-10-14 14:57:581,960 阅读
文章标签:开发工具

pterm SectionPrinter 实战:用「章节式」标题为终端输出建立结构层级

本文以 pterm 仓库中 section/demo 示例为核心,讲解如何用 pterm.DefaultSection 将冗长的终端输出组织成带层级的章节块。读完后,你将能够使用 SectionPrinter 控制标题级别、缩进字符、上下留白与样式,并结合 Sprint 布局逻辑与单元测试快照验证渲染结果,把 CLI 程序的日志、报告输出变成可读的“目录 + 章节”结构。

1. 示例代码:section/demo 的完整写法

section/demo/main.go 展示了 DefaultSection 最典型的两段用法:默认级别输出一个章节标题,再用 WithLevel(2) 输出一个“子章节”:

package main

import "github.com/pterm/pterm"

func main() {
	// Sections structure long output into headed blocks, like chapters.
	pterm.DefaultSection.Println("This is a section!")
	pterm.Info.Println("And here is some text.\nThis text could be anything.\nBasically it's just a placeholder")

	// Higher levels render as smaller subsections.
	pterm.DefaultSection.WithLevel(2).Println("This is another section!")
	pterm.Info.Println("And this is\nmore placeholder text")
}

在 _examples/section/demo/ 目录下执行 go run main.go 即可运行(仓库的 _examples/test.sh 脚本也是逐个示例目录执行 go run main.go)。其真实终端输出见 testdata/raw/section_demo.txt 的录制结果:

» This is a section!

  INFO    And here is some text.
          This text could be anything.
          Basically it's just a placeholder

»» This is another section!

  INFO    And this is
          more placeholder text

可以看到两个要点:

  • 一级章节渲染为单个 » 前缀,二级章节渲染为两个 » 前缀,形成类似文档标题层级的缩进;
  • pterm.Info.Println 输出的是带 INFO 徽标的前缀文本,与 Section 标题组合后,正文自然对齐在章节标题之下。

2. SectionPrinter 结构体与默认值

核心实现在 section_printer.go。SectionPrinter 是一个纯值结构体,五个字段分别对应章节标题的五个可调维度:

// SectionPrinter prints a new section title.
// It can be used to structure longer text, or different chapters of your program.
type SectionPrinter struct {
	Style           *Style    // 标题(含缩进字符)使用的样式
	Level           int       // 章节层级,决定缩进字符重复次数
	IndentCharacter string  // 缩进字符,默认 "»"
	TopPadding      int       // 标题上方的空行数
	BottomPadding   int       // 标题下方的空行数
	Writer          io.Writer // 输出目标
}

而包级变量 DefaultSection 给出了默认配置(section_printer.go#L10-L16):

字段 默认值 含义
Style &ThemeDefault.SectionStyle 默认主题样式,即 Style{Bold, FgLightMagenta}(粗体 + 浅品红色),定义于 theme.go#L37
Level 1 一级章节,输出单个缩进字符
TopPadding 1 标题前输出 1 个换行
BottomPadding 1 标题后输出 1 个换行
IndentCharacter "»" 缩进/章节前缀字符

Sprint 内部对 Style 做了空指针保护:若 Style == nil 会退化为 NewStyle(),因此零值 pterm.SectionPrinter{} 也能安全渲染(见第 6 节测试)。

3. 层级机制:WithLevel 与缩进字符的重复规则

示例中 pterm.DefaultSection.WithLevel(2).Println(...) 之所以输出 »»,来自 Sprint 中的这段布局逻辑(section_printer.go#L67-L90):

func (p SectionPrinter) Sprint(a ...any) string {
	if p.Style == nil {
		p.Style = NewStyle()
	}

	var ret strings.Builder

	for i := 0; i < p.TopPadding; i++ {
		ret.WriteByte('\n')
	}

	if p.Level > 0 {
		ret.WriteString(p.Style.Sprint(strings.Repeat(p.IndentCharacter, p.Level)))
		ret.WriteByte(' ')
	}

	ret.WriteString(p.Style.Sprint(a...))

	for i := 0; i < p.BottomPadding; i++ {
		ret.WriteByte('\n')
	}

	return ret.String()
}

规则很直接:

  • Level > 0 时,把 IndentCharacter 重复 Level 次,追加一个空格,再输出标题文本;
  • Level == 0 时完全省略缩进与分隔空格,只输出带样式的标题本身;
  • 缩进字符与标题文本都会被 Style 包裹,而上下 padding 的换行不染色。

behavioral test 对这一行为做了逐档验证:

func TestSectionPrinterLevelRepeatsIndentCharacter(t *testing.T) {
	assert.Equal(t, "\n» Title\n", stripANSI(pterm.DefaultSection.WithLevel(1).Sprint("Title")))
	assert.Equal(t, "\n»» Title\n", stripANSI(pterm.DefaultSection.WithLevel(2).Sprint("Title")))
	assert.Equal(t, "\n»»» Title\n", stripANSI(pterm.DefaultSection.WithLevel(3).Sprint("Title")))
}

func TestSectionPrinterLevelZeroOmitsIndent(t *testing.T) {
	// Level 0 renders neither indent characters nor the separating space.
	assert.Equal(t, "\nTitle\n", stripANSI(pterm.DefaultSection.WithLevel(0).Sprint("Title")))
}

也就是说,把 Level 当作“文档大纲级别”来使用:1 级 »、2 级 »»、3 级 »»»,是完全可以预期和断言的。

4. 自定义缩进字符与上下留白

SectionPrinter 提供链式的 builder 方法(均为值接收者,返回指向副本的指针,不修改原 printer):

p := pterm.DefaultSection.WithIndentCharacter("=>").WithLevel(2)
// 渲染为 "=>=> Title"(不含 padding 时为 "\n=>=> Title\n")

对应测试在 section_printer_test.go#L33-L37:

func TestSectionPrinterCustomIndentCharacter(t *testing.T) {
	p := pterm.DefaultSection.WithIndentCharacter("=>").WithLevel(2)

	assert.Equal(t, "\n=>=> Title\n", stripANSI(p.Sprint("Title")))
}

IndentCharacter 是任意字符串而不仅是单字符——传 =>、-、* 都可以,层级重复时按字符串整体重复。

TopPadding / BottomPadding 控制标题前后的空行数量,每个 padding 值恰好对应一个 \n:

p := pterm.DefaultSection.WithTopPadding(3).WithBottomPadding(2)
// 渲染结果: "\n\n\n» Title\n\n"

测试断言(section_printer_test.go#L39-L49)保证了这一点:WithTopPadding(3).WithBottomPadding(2) 精确产生 3 个前导换行和 2 个尾部换行;而 WithTopPadding(0).WithBottomPadding(0) 时输出就是裸的 » Title,没有任何换行。默认值(上下各 1)则给出 \n» Title\n 的标准章节间距,避免标题紧贴上一条输出。

5. 样式与主题:SectionStyle 从哪里来

DefaultSection.Style 指向 ThemeDefault.SectionStyle,其默认定义为 Style{Bold, FgLightMagenta}(theme.go#L37)。从 styled 快照 可以看到最终产生的 ANSI 序列:

\x1b[1;95m»\x1b[0m \x1b[1;95mSection Title\x1b[0m

即 » 与标题文本分别被 <a href="https://link.gitcode.com/i/5782ed15405592ec256b5526b6b00239" target="_blank">1;95m(粗体 + 浅品红)包裹,中间的 空格不带样式。快照由 [snapshot_test.go#L80-L82 生成:

testSnapshot(t, "Section", func(_ *testing.T) string {
	return pterm.DefaultSection.Sprint("Section Title")
})

配套的 plain 快照(testdata/snapshots/TestSnapshots__Section__plain.snap)内容为 \n» Section Title,正是第 4 节所述默认布局(TopPadding=1, Level=1, BottomPadding=1)的“无 ANSI”版本。

如果不想依赖主题,也可以直接 WithStyle 覆盖:

pterm.DefaultSection.WithStyle(pterm.NewStyle(pterm.Bold, pterm.FgCyan)).Println("Custom styled section")

6. 输出方法族与 Writer 重定向

除 Println 外,SectionPrinter 提供与其他 printer 一致的完整方法族(section_printer.go#L65-L169):

方法 说明
Sprint / Sprintln / Sprintf / Sprintfln 渲染为字符串,不输出,可用于嵌入表格、文件等任意场景
Print / Println / Printf / Printfln 写入 Writer(默认标准输出),返回 *TextPrinter,便于链式调用
PrintOnError / PrintOnErrorf 仅当参数中存在非 nil error 时输出,适合简单的错误检查
WithWriter 将输出重定向到任意 io.Writer(如 bytes.Buffer),也是测试中验证输出的标准手段

一个典型的组合用法是:先用 Section 打章节头,再在章节体内混合其他 printer 输出正文、日志或表格;pterm.Info 这类 PrefixPrinter(定义见 prefix_printer.go#L21-L27,前缀为固定宽度的 " INFO " 徽标)就是 demo 示例中与 Section 搭配使用的正文输出器。

零值安全也值得注意:pterm.SectionPrinter{} 的 Sprint("Title") 原样返回 "Title"(无 padding、无缩进、无样式),该行为由 TestSectionPrinterZeroValueRendersBareText(section_printer_test.go#L57-L62)锁定,说明 Sprint 对缺省配置全部采用“无则不加”的保守策略。

7. 验证与延伸阅读

  • 行为测试:section_printer_test.go 覆盖了默认布局、各级缩进重复、Level 0、自定义缩进字符、padding 换行精确性、样式作用域(仅标题染色)与零值渲染;builder 方法与 Print*/Sprint* 委托关系则由 contract_test.go 中的通用契约测试统一覆盖(其中 pterm.DefaultSection 以 WithWriter 形式注册)。
  • 快照测试:testdata/snapshots/TestSnapshots__Section__plain.snap 与 styled 版本 分别保存去 ANSI 与带 ANSI 的渲染结果,可作为回归基线。
  • 真实运行录屏数据:testdata/raw/section_demo.txt 保存了 demo 示例在录制终端中的逐帧输出,可用于确认 »/»» 与 INFO 前缀的实际对齐效果。

小结:SectionPrinter 通过 Level × IndentCharacter 表达章节层级、通过 TopPadding/BottomPadding 控制章节呼吸感、通过 Style(默认主题 Bold + FgLightMagenta)统一标题视觉权重,是 pterm 中把长输出组织成“章节式”结构的最轻量工具。在 section/demo 的基础上,按需调整这四个维度,即可在自己的 CLI 报告中构建清晰的多级章节输出。

登录后查看全文
pterm