Prism
是一个 DSL,它使用声明式语法为 Swift 命令行工具创建美观的格式化文本。它功能强大、易于使用,并支持 macOS 和 Linux。
将以下依赖项添加到您的 Package.swift
文件中
.package(url: "https://github.com/jordanbaird/Prism", from: "0.1.2")
首先,创建一个 Prism
类型的实例。它的初始化器接受一个闭包,您可以在其中填充各种属性。
let formatted = Prism(spacing: .spaces) {
ForegroundColor(.green, "This text's color is green.")
Bold("This text is bold.")
Italic("This text is italic.")
Underline("This text is underlined.")
Strikethrough("This text has a strikethrough.")
}
属性的行为类似于 Prism
本身,让您能够将其他元素嵌套在其中。
let formatted = Prism(spacing: .newlines) {
Bold {
"This text is bold."
Italic("This text is bold and italic.")
Underline("This text is bold and underlined.")
BackgroundColor(.cyan) {
Underline {
"This text is bold, underlined, and has a cyan background."
IgnoreFormatting("This text has no formatting.")
"Back to bold and underlined, with a cyan background."
}
}
}
}
DSL 的 ElementBuilder
隐式地将字符串包装在一个特殊的、非修改的 Standard
属性中,允许 String
类型的实例(包括字符串字面量)与其他元素和属性一起内联使用。 在以下示例中,两个 Prism
块在语义上是相同的
let formatted1 = Prism {
Bold("Some bold text.")
Standard("Just regular old text.")
Italic("Some italic text.")
}
let formatted2 = Prism {
Bold("Some bold text.")
"Just regular old text."
Italic("Some italic text.")
}
print(formatted1 == formatted2)
// Prints: "true"
Prism
类型符合 CustomStringConvertible
协议,允许将其格式化的内容直接打印到 stdout
。
let wonderfulWorld = Prism {
"I see"
ForegroundColor(.blue) {
"skies that are blue."
}
ForegroundColor(.red) {
"Red roses, too."
}
}
print(wonderfulWorld)
如果输出目标(即终端或控制台)不支持格式化文本,则会自动打印该文本的未格式化版本。 例如,以下是上述代码在 Xcode 控制台中打印的内容
请注意,某些终端客户端可能会以不同于其他客户端的方式显示某些元素。 Prism
只是为终端提供了每个属性的一组控制代码。 由终端来决定如何显示 Prism
提供给它的控制代码。
Prism 在 MIT 许可下可用。