formatgo

package module
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2026 License: MIT Imports: 14 Imported by: 8

README

GitHub Workflow Status (branch) GoDoc Coverage Status Supported Go Versions GitHub Release Go Report Card

formatgo

Go source code formatting utilities with advanced import management and condensing capabilities.


CHINESE README

中文说明

Main Features

🎯 Multi-Stage Formatting: Standard formatting, import condensing, and automatic import management ⚡ Flexible Processing: Format bytes, strings, files, and entire DIR trees 🔄 Import Optimization: Remove blank lines from import blocks and organize imports 🌍 Customizable Filtering: Configure DIR and file filtering with predicates 📋 Type-Safe Options: Comprehensive configuration with sensible defaults

Installation

go get github.com/yylego/formatgo

Usage

The package provides multiple functions to format Go code at different granularities.

FormatBytes

Formats Go source code from a byte slice.

formattedCode, err := formatgo.FormatBytes(code []byte)
  • code: The source code as a byte slice.
  • Returns the formatted code as a byte slice with an exception when formatting fails.
FormatCode

Formats Go source code from a string.

formattedCode, err := formatgo.FormatCode(code string)
  • code: The source code as a string.
  • Returns the formatted code as a string with an exception when formatting fails.
FormatFile

Formats a Go source code file at the given path.

err := formatgo.FormatFile(path string)
  • path: The path to the Go source code file.
  • Returns an exception when the formatting fails.
FormatRoot

Formats Go source files in the specified root DIR and its subdirectories.

err := formatgo.FormatRoot(root string)
  • root: The root DIR to start formatting files from.
  • Returns an exception when something happens during the formatting process.

Example

Here's a simple example showing how to format Go code from a string:

package main

import (
	"fmt"
	"github.com/yylego/formatgo"
)

func main() {
	code := `package main

import "fmt"

func main() {fmt.Println("Hello, world!")}`

	formattedCode, err := formatgo.FormatCode(code)
	if err != nil {
		fmt.Println("Exception when formatting code:", err)
		return
	}

	fmt.Println("Formatted Code:", formattedCode)
}

Advanced Usage

Custom Options

Use FormatBytesWithOptions to customize the formatting process:

options := formatgo.NewOptions()
options.CondenseImport = true  // Remove blank lines from imports
options.IsFormatImport = true  // Enable automatic import management

formattedCode, err := formatgo.FormatBytesWithOptions(code, options)
DIR Formatting with Filters

Use FormatRootWithOptions to customize DIR processing:

options := formatgo.NewRootOptions()
options.FilterFile = func(depth int, path string, name string) bool {
    // Skip test files
    return !strings.HasSuffix(name, "_test.go")
}

err := formatgo.FormatRootWithOptions(root, options)

📄 License

MIT License. See LICENSE.


🤝 Contributing

Contributions are welcome! Report bugs, suggest features, and contribute code:

  • 🐛 Found a mistake? Open an issue on GitHub with reproduction steps
  • 💡 Have a feature idea? Create an issue to discuss the suggestion
  • 📖 Documentation confusing? Report it so we can improve
  • 🚀 Need new features? Share the use cases to help us understand requirements
  • Performance issue? Help us optimize through reporting slow operations
  • 🔧 Configuration problem? Ask questions about complex setups
  • 📢 Follow project progress? Watch the repo to get new releases and features
  • 🌟 Success stories? Share how this package improved the workflow
  • 💬 Feedback? We welcome suggestions and comments

🔧 Development

New code contributions, follow this process:

  1. Fork: Fork the repo on GitHub (using the webpage UI).
  2. Clone: Clone the forked project (git clone https://github.com/yourname/repo-name.git).
  3. Navigate: Navigate to the cloned project (cd repo-name)
  4. Branch: Create a feature branch (git checkout -b feature/xxx).
  5. Code: Implement the changes with comprehensive tests
  6. Testing: (Golang project) Ensure tests pass (go test ./...) and follow Go code style conventions
  7. Documentation: Update documentation to support client-facing changes and use significant commit messages
  8. Stage: Stage changes (git add .)
  9. Commit: Commit changes (git commit -m "Add feature xxx") ensuring backward compatible code
  10. Push: Push to the branch (git push origin feature/xxx).
  11. PR: Open a merge request on GitHub (on the GitHub webpage) with detailed description.

Please ensure tests pass and include relevant documentation updates.


🌟 Support

Welcome to contribute to this project via submitting merge requests and reporting issues.

Project Support:

  • Give GitHub stars if this project helps you
  • 🤝 Share with teammates and (golang) programming friends
  • 📝 Write tech blogs about development tools and workflows - we provide content writing support
  • 🌟 Join the ecosystem - committed to supporting open source and the (golang) development scene

Have Fun Coding with this package! 🎉🎉🎉


GitHub Stars

Stargazers

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func CleanCodeImportNewlines

func CleanCodeImportNewlines(source []byte) ([]byte, error)

CleanCodeImportNewlines removes consecutive newlines from import blocks using AST parsing.

Algorithm:

  1. Parse source into AST
  2. Locate import declaration range
  3. Extract and condense the import text
  4. Replace the import block with condensed version

Returns unchanged source if no imports exist and no changes needed.

CleanCodeImportNewlines 使用 AST 解析从导入块中删除连续换行符。

算法:

  1. 将源代码解析为 AST
  2. 定位导入声明范围
  3. 提取并压缩导入文本
  4. 用压缩版本替换原始导入块

如果不存在导入或不需要更改则返回未改变的源代码。

func CleanFileImportNewlines

func CleanFileImportNewlines(path string) error

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:

  1. Read the file
  2. Clean imports via CleanCodeImportNewlines
  3. Write back the cleaned content

CleanFileImportNewlines 压缩 Go 源文件中的导入语句。

该函数删除导入块内的连续换行符, 使导入部分更紧凑而不改变语义。

处理流程:

  1. 读取文件
  2. 应用 CleanCodeImportNewlines
  3. 写回清理后的内容

func FormatBytes

func FormatBytes(code []byte) ([]byte, error)

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

func FormatBytesWithOptions(code []byte, options *Options) ([]byte, error)

FormatBytesWithOptions formats Go source code with configurable options.

The formatting process consists of three stages:

  1. Standard formatting via go/format.Source
  2. Import newline condensing (if CondenseImport is enabled)
  3. 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 源代码。

格式化过程包含三个阶段:

  1. 通过 go/format.Source 进行标准格式化
  2. 可选的导入换行压缩(如果启用 CondenseImport)
  3. 可选的导入管理(如果启用 IsFormatImport)

即使部分失败也返回最佳可用结果。 如果任何阶段失败,返回上一个成功阶段的输出。

func FormatCode

func FormatCode(code string) (string, error)

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

func FormatCodeWithOptions(code string, options *Options) (string, error)

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

func FormatFile(path string) error

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

func FormatFileWithOptions(path string, options *Options) error

FormatFileWithOptions formats a Go source file in place with configurable options.

Process:

  1. Read the file contents
  2. Format content via FormatBytesWithOptions
  3. Write back to file if content changed (skip write if unchanged)

File updates are atomic when WriteFile truncates before writing.

FormatFileWithOptions 使用可配置选项就地格式化 Go 源文件。

处理流程:

  1. 读取文件内容
  2. 通过 FormatBytesWithOptions 应用格式化
  3. 如果内容改变则写回文件(未改变则跳过写入)

当 WriteFile 在写入前截断时,文件被原子性更新。

func FormatRoot

func FormatRoot(root string) error

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

func NewImportsOptions() *imports.Options

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL