Documentation
¶
Overview ¶
Package formatgo provides utilities to format Go source code with advanced options.
The package offers multi-stage formatting capabilities:
- Standard Go code formatting via go/format
- Import statement management and condensing
- Automatic import organization via golang.org/x/tools/imports
It supports formatting at different granularities:
- Byte slices and strings
- Single files with in-place updates
- Recursive DIR processing with custom filtering
formatgo 提供了带有高级选项的 Go 源代码格式化工具。
该包提供多层次的格式化能力:
- 通过 go/format 进行标准 Go 代码格式化
- 导入语句管理和压缩
- 通过 golang.org/x/tools/imports 自动组织导入
支持不同粒度的格式化:
- 单个字节切片和字符串
- 带就地更新的单个文件
- 带过滤功能的递归目录遍历
Index ¶
- func CleanCodeImportNewlines(source []byte) ([]byte, error)
- func CleanFileImportNewlines(path string) error
- func FormatBytes(code []byte) ([]byte, error)
- func FormatBytesWithOptions(code []byte, options *Options) ([]byte, error)
- func FormatCode(code string) (string, error)
- func FormatCodeWithOptions(code string, options *Options) (string, error)
- func FormatFile(path string) error
- func FormatFileWithOptions(path string, options *Options) error
- func FormatRoot(root string) error
- func FormatRootWithOptions(root string, options *RootOptions) error
- func NewImportsOptions() *imports.Options
- type Options
- type RootOptions
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CleanCodeImportNewlines ¶
CleanCodeImportNewlines removes consecutive newlines from import blocks using AST parsing.
Algorithm:
- Parse source into AST
- Locate import declaration range
- Extract and condense the import text
- Replace the import block with condensed version
Returns unchanged source if no imports exist and no changes needed.
CleanCodeImportNewlines 使用 AST 解析从导入块中删除连续换行符。
算法:
- 将源代码解析为 AST
- 定位导入声明范围
- 提取并压缩导入文本
- 用压缩版本替换原始导入块
如果不存在导入或不需要更改则返回未改变的源代码。
func CleanFileImportNewlines ¶
CleanFileImportNewlines condenses import statements in a Go source file.
The function removes consecutive newlines within the import block, making the imports section more compact without changing semantics.
Process:
- Read the file
- Clean imports via CleanCodeImportNewlines
- Write back the cleaned content
CleanFileImportNewlines 压缩 Go 源文件中的导入语句。
该函数删除导入块内的连续换行符, 使导入部分更紧凑而不改变语义。
处理流程:
- 读取文件
- 应用 CleanCodeImportNewlines
- 写回清理后的内容
func FormatBytes ¶
FormatBytes formats Go source code with default options.
Convenience function applying standard formatting settings. When custom formatting is needed, use FormatBytesWithOptions.
FormatBytes 使用默认选项格式化 Go 源代码。
这是一个便捷包装,应用标准格式化设置。 对于自定义格式化行为,使用 FormatBytesWithOptions。
func FormatBytesWithOptions ¶
FormatBytesWithOptions formats Go source code with configurable options.
The formatting process consists of three stages:
- Standard formatting via go/format.Source
- Import newline condensing (if CondenseImport is enabled)
- Import management (if IsFormatImport is enabled)
Returns the best available result even with failures. When a stage fails, returns the output from the most recent success.
FormatBytesWithOptions 使用可配置选项格式化 Go 源代码。
格式化过程包含三个阶段:
- 通过 go/format.Source 进行标准格式化
- 可选的导入换行压缩(如果启用 CondenseImport)
- 可选的导入管理(如果启用 IsFormatImport)
即使部分失败也返回最佳可用结果。 如果任何阶段失败,返回上一个成功阶段的输出。
func FormatCode ¶
FormatCode formats Go source code from a string with default options.
Equivalent to FormatBytes but accepts and returns strings. When custom formatting is needed, use FormatCodeWithOptions.
FormatCode 使用默认选项从字符串格式化 Go 源代码。
等效于 FormatBytes 但接受并返回字符串。 对于自定义格式化行为,使用 FormatCodeWithOptions。
func FormatCodeWithOptions ¶
FormatCodeWithOptions formats Go source code from a string with configurable options.
Convenience function wrapping FormatBytesWithOptions with string conversion. Applies the same three-stage formatting process as FormatBytesWithOptions.
FormatCodeWithOptions 使用可配置选项从字符串格式化 Go 源代码。
这是 FormatBytesWithOptions 的便捷包装,处理字符串转换。 应用与 FormatBytesWithOptions 相同的三阶段格式化过程。
func FormatFile ¶
FormatFile formats a single Go source file with default options.
Updates the file in place if formatting changes the content. When custom formatting is needed, use FormatFileWithOptions.
FormatFile 使用默认选项格式化单个 Go 源文件。
如果格式化改变内容,就地更新文件。 对于自定义格式化行为,使用 FormatFileWithOptions。
func FormatFileWithOptions ¶
FormatFileWithOptions formats a Go source file in place with configurable options.
Process:
- Read the file contents
- Format content via FormatBytesWithOptions
- Write back to file if content changed (skip write if unchanged)
File updates are atomic when WriteFile truncates before writing.
FormatFileWithOptions 使用可配置选项就地格式化 Go 源文件。
处理流程:
- 读取文件内容
- 通过 FormatBytesWithOptions 应用格式化
- 如果内容改变则写回文件(未改变则跳过写入)
当 WriteFile 在写入前截断时,文件被原子性更新。
func FormatRoot ¶
FormatRoot formats Go files in a DIR using recursion with default options.
Traverses the DIR tree and formats .go files found. When custom filtering is needed, use FormatRootWithOptions.
FormatRoot 使用默认选项递归格式化目录中的所有 Go 文件。
遍历目录树并格式化找到的所有 .go 文件。 对于自定义遍历或过滤,使用 FormatRootWithOptions。
func FormatRootWithOptions ¶
func FormatRootWithOptions(root string, options *RootOptions) error
FormatRootWithOptions formats Go files in a DIR tree using recursion.
Processing rules:
- Respects FilterRoot and FilterFile predicates
- Skips hidden directories based on SkipHiddenDepth
- Formats files matching .go extension and FileHasSuffixes
Depth tracking enables filtering decisions at each recursion stage.
FormatRootWithOptions 递归格式化目录树中的所有 Go 文件。
遍历行为:
- 遵循 FilterRoot 和 FilterFile 谓词
- 根据 SkipHiddenDepth 跳过隐藏目录
- 格式化匹配 .go 扩展名或 FileHasSuffixes 的文件
depth 参数跟踪递归级别用于过滤决策。
func NewImportsOptions ¶
NewImportsOptions creates default configuration to use with imports.Process.
Default settings:
- TabWidth: 4 (spaces in each tab)
- TabIndent: true (use tabs instead of spaces)
- Comments: true (preserve existing comments)
- Fragment: true (allow incomplete source fragments)
NewImportsOptions 为 imports.Process 函数创建默认配置。
默认设置:
- TabWidth: 4(每个制表符的空格数)
- TabIndent: true(使用制表符而不是空格)
- Comments: true(保留现有注释)
- Fragment: true(允许不完整的源代码片段)
Types ¶
type Options ¶
type Options struct {
ImportsOptions *imports.Options // Options when formatting imports // 导入格式化的选项
CondenseImport bool // Condense imports and remove blank lines // 是否压缩导入部分,去除空行
IsFormatImport bool // Enable import statement formatting // 是否格式化导入语句
}
Options configures the formatting process of Go source code.
Fields:
- ImportsOptions: Settings passed to golang.org/x/tools/imports.Process
- CondenseImport: Remove consecutive newlines from import blocks
- IsFormatImport: Enable automatic import management and organization
Options 配置 Go 源代码的格式化行为。
字段:
- ImportsOptions: 传递给 golang.org/x/tools/imports.Process 的设置
- CondenseImport: 从导入块中删除连续换行符
- IsFormatImport: 启用自动导入管理和组织
func NewOptions ¶
func NewOptions() *Options
NewOptions creates Options with recommended defaults.
Default configuration:
- Import condensing enabled
- Import formatting enabled
- Tab-based indentation with width 4
NewOptions 使用推荐的默认值创建 Options。
默认配置:
- 启用导入压缩
- 启用导入格式化
- 基于制表符的缩进,宽度为 4
type RootOptions ¶
type RootOptions struct {
FileOptions *Options // File formatting options // 文件格式化选项
FilterRoot func(depth int, path string, name string) bool // Predicate to select directories matching certain criteria // 用于过滤目录名/路径的条件,只有符合条件的目录才会被格式化
FilterFile func(depth int, path string, name string) bool // Predicate to select files matching certain criteria // 用于过滤文件名/路径的条件,只有符合条件的文件才会被格式化
FileHasSuffixes []string // Suffixes of files to be formatted // 要格式化的文件后缀列表
SkipHiddenDepth int // Depth threshold to skip hidden directories (e.g., .git, .idea) // 跳过隐藏目录的深度级别(例如 .git,.idea)
}
RootOptions configures recursive DIR formatting settings.
Fields:
- FileOptions: Formatting settings applied to each file
- FilterRoot: Predicate to select which subdirectories to traverse
- FilterFile: Predicate to select which files to format
- FileHasSuffixes: Extra file extensions to format (beyond .go)
- SkipHiddenDepth: Depth threshold when skipping hidden directories
RootOptions 配置递归目录格式化行为。
字段:
- FileOptions: 应用于每个文件的格式化设置
- FilterRoot: 用于选择要遍历的子目录的谓词
- FilterFile: 用于选择要格式化的文件的谓词
- FileHasSuffixes: 要格式化的附加文件扩展名(除 .go 之外)
- SkipHiddenDepth: 跳过隐藏目录的深度阈值
func NewRootOptions ¶
func NewRootOptions() *RootOptions
NewRootOptions creates RootOptions with sensible defaults suitable when formatting projects.
Default configuration:
- Formats .go and .GO files
- Skips hidden directories at each depth (e.g., .git, .idea)
- Includes debug logging when making processing decisions
- Accepts directories and files (no filtering)
NewRootOptions 为典型项目创建具有合理默认值的 RootOptions。
默认行为:
- 格式化所有 .go 和 .GO 文件
- 跳过所有深度的隐藏目录(例如 .git、.idea)
- 包含遍历决策的调试日志
- 接受所有目录和文件(无过滤)
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
utils
Package utils provides filesystem utilities to handle DIR and file operations Includes path existence checking and DIR listing functions The formatgo package uses these utilities when processing files and validation
|
Package utils provides filesystem utilities to handle DIR and file operations Includes path existence checking and DIR listing functions The formatgo package uses these utilities when processing files and validation |