├── .github └── workflows │ └── release.yml ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── README.zh.md ├── format.go ├── format_test.go ├── go.mod ├── go.sum ├── import.go ├── import_test.go ├── internal ├── examples │ └── example1 │ │ ├── example1.go │ │ └── example1_test.go └── utils │ ├── utils.go │ └── utils_test.go ├── option.go ├── option_test.go ├── simple.go └── simple_test.go /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: create-release 2 | 3 | on: 4 | push: 5 | branches: 6 | - main # 监听 main 分支的 push 操作(编译和测试/代码检查) 7 | tags: 8 | - 'v*' # 监听以 'v' 开头的标签的 push 操作(发布 Release) 9 | 10 | jobs: 11 | lint: 12 | name: lint 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/setup-go@v5 16 | with: 17 | go-version: "1.23.x" 18 | - uses: actions/checkout@v4 19 | - name: golangci-lint 20 | uses: golangci/golangci-lint-action@v6 21 | with: 22 | version: latest 23 | 24 | test: 25 | runs-on: ubuntu-latest 26 | strategy: 27 | matrix: 28 | go: [ "1.22.x", "1.23.x" ] 29 | steps: 30 | - uses: actions/checkout@v4 31 | 32 | - uses: actions/setup-go@v5 33 | with: 34 | go-version: ${{ matrix.go }} 35 | 36 | - name: Run test 37 | run: make test COVERAGE_DIR=/tmp/coverage 38 | 39 | - name: Send goveralls coverage 40 | uses: shogo82148/actions-goveralls@v1 41 | with: 42 | path-to-profile: /tmp/coverage/combined.txt 43 | flag-name: Go-${{ matrix.go }} 44 | parallel: true 45 | if: ${{ github.event.repository.fork == false }} # 仅在非 fork 时上传覆盖率 46 | 47 | check-coverage: 48 | name: Check coverage 49 | needs: [ test ] 50 | runs-on: ubuntu-latest 51 | steps: 52 | - uses: shogo82148/actions-goveralls@v1 53 | with: 54 | parallel-finished: true 55 | if: ${{ github.event.repository.fork == false }} # 仅在非 fork 时检查覆盖率 56 | 57 | # 发布 Release 58 | release: 59 | name: Release a new version 60 | needs: [ lint, test ] 61 | runs-on: ubuntu-latest 62 | # 仅在推送标签时执行 - && - 仅在非 fork 时执行发布 63 | if: ${{ github.event.repository.fork == false && success() && startsWith(github.ref, 'refs/tags/v') }} 64 | steps: 65 | # 1. 检出代码 66 | - name: Checkout code 67 | uses: actions/checkout@v4 68 | 69 | # 2. 创建 Release 和上传源码包 70 | - name: Create Release 71 | uses: softprops/action-gh-release@v2 72 | with: 73 | generate_release_notes: true 74 | env: 75 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 76 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # If you prefer the allow list template instead of the deny list, see community template: 2 | # https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore 3 | # 4 | # Binaries for programs and plugins 5 | *.exe 6 | *.exe~ 7 | *.dll 8 | *.so 9 | *.dylib 10 | 11 | # Test binary, built with `go test -c` 12 | *.test 13 | 14 | # Output of the go coverage tool, specifically when used with LiteIDE 15 | *.out 16 | 17 | # Dependency directories (remove the comment below to include it) 18 | # vendor/ 19 | 20 | # Go workspace file 21 | go.work 22 | go.work.sum 23 | 24 | # env file 25 | .env 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 yangyile-yyle88 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | COVERAGE_DIR ?= .coverage 2 | 3 | # cp from: https://github.com/yyle88/erero/blob/aacef44379ac6c5e3c831d1df6b47de10d731a88/Makefile#L4 4 | test: 5 | @-rm -r $(COVERAGE_DIR) 6 | @mkdir $(COVERAGE_DIR) 7 | make test-with-flags TEST_FLAGS='-v -race -covermode atomic -coverprofile $$(COVERAGE_DIR)/combined.txt -bench=. -benchmem -timeout 20m' 8 | 9 | test-with-flags: 10 | @go test $(TEST_FLAGS) ./... 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![GitHub Workflow Status (branch)](https://img.shields.io/github/actions/workflow/status/yyle88/formatgo/release.yml?branch=main&label=BUILD)](https://github.com/yyle88/formatgo/actions/workflows/release.yml?query=branch%3Amain) 2 | [![GoDoc](https://pkg.go.dev/badge/github.com/yyle88/formatgo)](https://pkg.go.dev/github.com/yyle88/formatgo) 3 | [![Coverage Status](https://img.shields.io/coveralls/github/yyle88/formatgo/master.svg)](https://coveralls.io/github/yyle88/formatgo?branch=main) 4 | ![Supported Go Versions](https://img.shields.io/badge/Go-1.22%2C%201.23-lightgrey.svg) 5 | [![GitHub Release](https://img.shields.io/github/release/yyle88/formatgo.svg)](https://github.com/yyle88/formatgo/releases) 6 | [![Go Report Card](https://goreportcard.com/badge/github.com/yyle88/formatgo)](https://goreportcard.com/report/github.com/yyle88/formatgo) 7 | 8 | # formatgo 9 | 10 | `formatgo` is a Go package that provides utilities for formatting Go source code, whether it's in a byte slice, string, or a file, and even for entire directories containing Go files. 11 | 12 | ## CHINESE README 13 | 14 | [中文说明](README.zh.md) 15 | 16 | ## Installation 17 | 18 | To install the `formatgo` package, you can run the following command: 19 | 20 | ```bash 21 | go get github.com/yyle88/formatgo 22 | ``` 23 | 24 | ## Usage 25 | 26 | The package provides several functions for formatting Go code. Below are the main functions that you can use: 27 | 28 | ### `FormatBytes` 29 | 30 | Formats Go source code from a byte slice. 31 | 32 | ```go 33 | formattedCode, err := formatgo.FormatBytes(code []byte) 34 | ``` 35 | 36 | - `code`: The source code as a byte slice. 37 | - Returns the formatted code as a byte slice or an error if something goes wrong. 38 | 39 | ### `FormatCode` 40 | 41 | Formats Go source code from a string. 42 | 43 | ```go 44 | formattedCode, err := formatgo.FormatCode(code string) 45 | ``` 46 | 47 | - `code`: The source code as a string. 48 | - Returns the formatted code as a string or an error if something goes wrong. 49 | 50 | ### `FormatFile` 51 | 52 | Formats a Go source code file at the given path. 53 | 54 | ```go 55 | err := formatgo.FormatFile(path string) 56 | ``` 57 | 58 | - `path`: The path to the Go source code file. 59 | - Returns an error if the formatting fails. 60 | 61 | ### `FormatRoot` 62 | 63 | Formats all Go source files in the specified root directory and its subdirectories. 64 | 65 | ```go 66 | err := formatgo.FormatRoot(root string) 67 | ``` 68 | 69 | - `root`: The root directory to start formatting files from. 70 | - Returns an error if something goes wrong during the formatting process. 71 | 72 | ## Example 73 | 74 | Here’s a simple example of how to format Go code from a string: 75 | 76 | ```go 77 | package main 78 | 79 | import ( 80 | "fmt" 81 | "github.com/yyle88/formatgo" 82 | ) 83 | 84 | func main() { 85 | code := `package main 86 | 87 | import "fmt" 88 | 89 | func main() {fmt.Println("Hello, world!")}` 90 | 91 | formattedCode, err := formatgo.FormatCode(code) 92 | if err != nil { 93 | fmt.Println("Error formatting code:", err) 94 | return 95 | } 96 | 97 | fmt.Println("Formatted Code:", formattedCode) 98 | } 99 | ``` 100 | 101 | ## License 102 | 103 | `formatgo` is open-source and released under the MIT License. See the LICENSE file for more information. 104 | 105 | --- 106 | 107 | ## Support 108 | 109 | Welcome to contribute to this project by submitting pull requests and reporting issues. 110 | 111 | If you find this package valuable, give me some stars on GitHub! Thank you!!! 112 | 113 | **Thank you for your support!** 114 | 115 | **Happy Coding with `formatgo`!** 🎉 116 | 117 | Give me stars. Thank you!!! 118 | 119 | ## GitHub Stars 120 | 121 | [![starring](https://starchart.cc/yyle88/formatgo.svg?variant=adaptive)](https://starchart.cc/yyle88/formatgo) 122 | -------------------------------------------------------------------------------- /README.zh.md: -------------------------------------------------------------------------------- 1 | # formatgo 2 | 3 | `formatgo` 是一个 Go 包,用于格式化 Go 源代码,无论是字节切片、字符串还是文件,甚至是包含 Go 文件的整个目录。 4 | 5 | ## 英文文档 6 | 7 | [English README](README.md) 8 | 9 | ## 安装 10 | 11 | 你可以通过以下命令安装 `formatgo` 包: 12 | 13 | ```bash 14 | go get github.com/yyle88/formatgo 15 | ``` 16 | 17 | ## 使用方法 18 | 19 | 该包提供了多个函数来格式化 Go 代码,下面是主要的函数及其用法: 20 | 21 | ### `FormatBytes` 22 | 23 | 从字节切片格式化 Go 源代码。 24 | 25 | ```go 26 | formattedCode, err := formatgo.FormatBytes(code []byte) 27 | ``` 28 | 29 | - `code`: Go 源代码(字节切片)。 30 | - 返回值:格式化后的代码(字节切片)或者格式化出错时的错误。 31 | 32 | ### `FormatCode` 33 | 34 | 从字符串格式化 Go 源代码。 35 | 36 | ```go 37 | formattedCode, err := formatgo.FormatCode(code string) 38 | ``` 39 | 40 | - `code`: Go 源代码(字符串)。 41 | - 返回值:格式化后的代码(字符串)或者格式化出错时的错误。 42 | 43 | ### `FormatFile` 44 | 45 | 格式化指定路径下的 Go 源代码文件。 46 | 47 | ```go 48 | err := formatgo.FormatFile(path string) 49 | ``` 50 | 51 | - `path`: Go 源代码文件的路径。 52 | - 返回值:格式化失败时的错误。 53 | 54 | ### `FormatRoot` 55 | 56 | 格式化指定根目录及其子目录下的所有 Go 源代码文件。 57 | 58 | ```go 59 | err := formatgo.FormatRoot(root string) 60 | ``` 61 | 62 | - `root`: 要开始格式化的根目录路径。 63 | - 返回值:格式化过程中发生错误时的错误。 64 | 65 | ## 示例 66 | 67 | 以下是一个简单的例子,演示如何从字符串格式化 Go 代码: 68 | 69 | ```go 70 | package main 71 | 72 | import ( 73 | "fmt" 74 | "github.com/yyle88/formatgo" 75 | ) 76 | 77 | func main() { 78 | code := `package main 79 | 80 | import "fmt" 81 | 82 | func main() {fmt.Println("Hello, world!")}` 83 | 84 | formattedCode, err := formatgo.FormatCode(code) 85 | if err != nil { 86 | fmt.Println("格式化代码时出错:", err) 87 | return 88 | } 89 | 90 | fmt.Println("格式化后的代码:", formattedCode) 91 | } 92 | ``` 93 | 94 | ## 许可证 95 | 96 | `formatgo` 是开源项目,采用 MIT 许可证。详情请查看 LICENSE 文件。 97 | 98 | ## 贡献与支持 99 | 100 | 欢迎通过提交 pull request 或报告问题来贡献此项目。 101 | 102 | 如果你觉得这个包对你有帮助,请在 GitHub 上给个 ⭐,感谢支持!!! 103 | 104 | **感谢你的支持!** 105 | 106 | **祝编程愉快!** 🎉 107 | 108 | Give me stars. Thank you!!! 109 | -------------------------------------------------------------------------------- /format.go: -------------------------------------------------------------------------------- 1 | package formatgo 2 | 3 | import ( 4 | "bytes" 5 | "go/format" 6 | "os" 7 | "path/filepath" 8 | "strings" 9 | 10 | "github.com/yyle88/done" 11 | "github.com/yyle88/erero" 12 | "github.com/yyle88/formatgo/internal/utils" 13 | "golang.org/x/tools/imports" 14 | ) 15 | 16 | // FormatBytesWithOptions formats Go source code from a byte slice. 17 | // Even if an error occurs during formatting, it returns the intermediate code. 18 | // FormatBytesWithOptions 格式化 Go 的源代码(以字节切片形式提供)。 19 | // 即使在格式化期间发生错误,也会返回中间结果代码。 20 | func FormatBytesWithOptions(code []byte, options *Options) ([]byte, error) { 21 | // Step 1: Format source code 22 | // 步骤 1:格式化源代码 23 | if newSource, err := format.Source(code); err != nil { 24 | return code, erero.Wro(err) // Return the original code if an error occurs // 如果发生错误,返回原始代码 25 | } else { 26 | code = newSource // Save the successful intermediate result // 保存格式化后的中间结果 27 | } 28 | 29 | // Step 2: Condense import statements if enabled 30 | // 步骤 2:如果启用,合并导入语句 31 | if options.CondenseImport { 32 | if newSource, err := CleanCodeImportNewlines(code); err != nil { 33 | return code, erero.Wro(err) 34 | } else { 35 | code = newSource // Save the successful intermediate result // 保存格式化后的导入语句中间结果 36 | } 37 | } 38 | 39 | // Step 3: Format imports if enabled 40 | // 步骤 3:如果启用,格式化导入语句 41 | if options.IsFormatImport { 42 | if newSource, err := imports.Process("", code, options.ImportsOptions); err != nil { 43 | return code, erero.Wro(err) 44 | } else { 45 | code = newSource // Save the successful intermediate result // 保存格式化后的导入语句中间结果 46 | } 47 | } 48 | return code, nil 49 | } 50 | 51 | // FormatCodeWithOptions formats Go source code from a string. 52 | // Even if an error occurs during formatting, it returns the intermediate code as a string. 53 | // FormatCodeWithOptions 格式化 Go 的源代码(以字符串形式提供)。 54 | // 即使在格式化期间发生错误,也会返回中间结果代码(字符串形式)。 55 | func FormatCodeWithOptions(code string, options *Options) (string, error) { 56 | newSource, err := FormatBytesWithOptions([]byte(code), options) 57 | if err != nil { 58 | return string(newSource), erero.Wro(err) // Return intermediate result even on error // 即使发生错误,仍然返回中间结果 59 | } 60 | return string(newSource), nil 61 | } 62 | 63 | // FormatFileWithOptions formats a Go source code file. 64 | // It reads the file, formats it, and writes back the result if changes are made. 65 | // FormatFileWithOptions 格式化一个 Go 源代码文件。 66 | // 它会读取文件内容,进行格式化,如果内容有变化则写回结果。 67 | func FormatFileWithOptions(path string, options *Options) error { 68 | source, err := os.ReadFile(path) 69 | if err != nil { 70 | return erero.Wro(err) 71 | } 72 | newSource, err := FormatBytesWithOptions(source, options) 73 | if err != nil { 74 | return erero.Wro(err) 75 | } 76 | // Skip writing if no changes are detected 77 | // 如果没有变化,跳过写入 78 | if bytes.Equal(source, newSource) { 79 | return nil 80 | } 81 | return utils.WriteFileKeepMode(path, newSource) // Write the formatted content 82 | // 写入格式化后的内容 83 | } 84 | 85 | // FormatRootWithOptions formats all Go files in a directory and its subdirectories. 86 | // It recursively processes each directory and applies the provided options. 87 | // FormatRootWithOptions 格式化指定目录及其子目录下的所有 Go 文件。 88 | // 它递归处理每个目录,并根据提供的选项进行格式化。 89 | func FormatRootWithOptions(root string, options *RootOptions) error { 90 | return recursiveFormat(root, 0, options) 91 | } 92 | 93 | // recursiveFormat is a helper function for FormatRootWithOptions. 94 | // It recursively processes directories and files based on the given options. 95 | // recursiveFormat 是 FormatRootWithOptions 的辅助函数。 96 | // 它根据给定的选项递归处理目录和文件。 97 | func recursiveFormat(root string, depth int, options *RootOptions) error { 98 | mapNamePath, err := utils.LsAsMap(root) 99 | if err != nil { 100 | return erero.Wro(err) 101 | } 102 | 103 | for name, path := range mapNamePath { 104 | // Skip hidden directories/files based on depth 105 | // 根据深度跳过隐藏的目录/文件 106 | if strings.HasPrefix(name, ".") { 107 | if depth < options.SkipHiddenDepth { 108 | continue // Skip hidden directories(.git / .idea) // 跳过隐藏的目录(.git / .idea) 109 | } 110 | } 111 | 112 | // Process subdirectories 113 | // 接着处理子目录 114 | if done.VBE(utils.IsRootExists(path)).Done() { 115 | if options.FilterRoot(depth, path, name) { 116 | if err := recursiveFormat(path, depth+1, options); err != nil { 117 | return erero.Wro(err) 118 | } 119 | } 120 | } else if done.VBE(utils.IsFileExists(path)).Done() { 121 | // Check if the file is a Go file or matches the specified suffixes 122 | // 检查文件是否为 Go 文件,或是否与指定的后缀匹配 123 | if filepath.Ext(name) == ".go" || utils.HasAnySuffix(name, options.FileHasSuffixes) { 124 | if options.FilterFile(depth, path, name) { 125 | if err := FormatFileWithOptions(path, options.FileOptions); err != nil { 126 | return erero.Wro(err) 127 | } 128 | } 129 | } 130 | } 131 | } 132 | return nil 133 | } 134 | -------------------------------------------------------------------------------- /format_test.go: -------------------------------------------------------------------------------- 1 | package formatgo 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/require" 7 | ) 8 | 9 | func TestFormatBytesWithOptions(t *testing.T) { 10 | const code = ` 11 | package formatgo 12 | import ( 13 | "github.com/kr/pretty" 14 | 15 | "testing" 16 | ) 17 | 18 | func TestGetImportsOptions(t *testing.T) { 19 | _ ,_ = pretty.Println(NewImportsOptions()) 20 | } 21 | ` 22 | 23 | source, err := FormatBytesWithOptions([]byte(code), NewOptions()) 24 | require.NoError(t, err) 25 | 26 | t.Log(string(source)) 27 | 28 | const want = `package formatgo 29 | 30 | import ( 31 | "testing" 32 | 33 | "github.com/kr/pretty" 34 | ) 35 | 36 | func TestGetImportsOptions(t *testing.T) { 37 | _, _ = pretty.Println(NewImportsOptions()) 38 | } 39 | ` 40 | require.Equal(t, want, string(source)) 41 | } 42 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/yyle88/formatgo 2 | 3 | go 1.22.8 4 | 5 | require ( 6 | github.com/kr/pretty v0.3.1 7 | github.com/stretchr/testify v1.10.0 8 | github.com/yyle88/done v1.0.25 9 | github.com/yyle88/erero v1.0.20 10 | github.com/yyle88/rese v0.0.10 11 | github.com/yyle88/runpath v1.0.23 12 | github.com/yyle88/syntaxgo v0.0.48 13 | github.com/yyle88/zaplog v0.0.22 14 | go.uber.org/zap v1.27.0 15 | golang.org/x/tools v0.30.0 16 | ) 17 | 18 | require ( 19 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect 20 | github.com/kr/text v0.2.0 // indirect 21 | github.com/pkg/errors v0.9.1 // indirect 22 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect 23 | github.com/rogpeppe/go-internal v1.13.1 // indirect 24 | github.com/yyle88/must v0.0.22 // indirect 25 | github.com/yyle88/mutexmap v1.0.13 // indirect 26 | github.com/yyle88/printgo v1.0.5 // indirect 27 | github.com/yyle88/tern v0.0.6 // indirect 28 | go.uber.org/multierr v1.11.0 // indirect 29 | golang.org/x/exp v0.0.0-20250210185358-939b2ce775ac // indirect 30 | golang.org/x/mod v0.23.0 // indirect 31 | golang.org/x/sync v0.11.0 // indirect 32 | gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect 33 | gopkg.in/yaml.v3 v3.0.1 // indirect 34 | ) 35 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= 2 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= 3 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= 5 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 6 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= 7 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 8 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 9 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 10 | github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= 11 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= 12 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 13 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= 14 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 15 | github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= 16 | github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= 17 | github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= 18 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= 19 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 20 | github.com/yyle88/done v1.0.25 h1:zBOFbByEybPited1OZcF+VMaZF5lSTueBgGeTCLH6XA= 21 | github.com/yyle88/done v1.0.25/go.mod h1:ATFPtqXx5TgRuk0abvGQivAA1yupqKAq6gogUNBYb4s= 22 | github.com/yyle88/erero v1.0.20 h1:S561vG3urdQ1pM6Se2/x8OQicrmVxnlWe9J7rC+WPvU= 23 | github.com/yyle88/erero v1.0.20/go.mod h1:nbNNXS09v4YZop/nYswXuxvnga874h6tjYOcDGYKKuA= 24 | github.com/yyle88/must v0.0.22 h1:Ay5TkDOWWsPmvTy8HpzNs0YoymsBgGuljivEMB4lrdE= 25 | github.com/yyle88/must v0.0.22/go.mod h1:grBswgDZIpUOjs4ujCj0WXMGVOU/fL9xjMS3D50pfaU= 26 | github.com/yyle88/mutexmap v1.0.13 h1:wp/6mv/gsC2DSqNbhMYiil4gtnb0sDCIhHHIHK2h0cQ= 27 | github.com/yyle88/mutexmap v1.0.13/go.mod h1:QUYDuARLPlGj414kHewQ5tt8jkDxQXoai8H3C4Gg+yc= 28 | github.com/yyle88/printgo v1.0.5 h1:gmaJKzEkrH6adbgfOfS6xq02CdvsE8QF+uKXXOdVLN8= 29 | github.com/yyle88/printgo v1.0.5/go.mod h1:QZZD92Orn8ddmxF5IOEFvLPPW66UIQtgoLixPdpXuQc= 30 | github.com/yyle88/rese v0.0.10 h1:rMEcybaIe/CNVMmilgor3nMQWB4TcJgXRttvDjKtvLg= 31 | github.com/yyle88/rese v0.0.10/go.mod h1:2jCdwu7qpJDdZqVulM4+zz/qiSxJWbOK/ndzQhg+5G0= 32 | github.com/yyle88/runpath v1.0.23 h1:VEdeaMXfvFY7CuF9Nceuxb6HSNDcmiSSGEf+zT7O900= 33 | github.com/yyle88/runpath v1.0.23/go.mod h1:JRGxn/0Ytg6CvGoE2VrO74oX8Lu4jbOPZDKxr8tzPEg= 34 | github.com/yyle88/syntaxgo v0.0.48 h1:JbyUnpq1pnf/hXgkfQ65bGMzJh/EVOvkXR7TtqjcpgQ= 35 | github.com/yyle88/syntaxgo v0.0.48/go.mod h1:Zx2vsDL+025u78thQwDqM6z33t7/czEuRAOzRvVsGxk= 36 | github.com/yyle88/tern v0.0.6 h1:tCGF8MoNZaAJaWM/kpZMbBkbYtRz9ZmKcMLXGy2qxEQ= 37 | github.com/yyle88/tern v0.0.6/go.mod h1:g9weyOMLtXYyt37EAshZPUTTHdH7WFauuxDi4oPr7/8= 38 | github.com/yyle88/zaplog v0.0.22 h1:hozMmQ0bhXLS6bkR3yHwW5cH8YelK09Df3lhy1k3iMM= 39 | github.com/yyle88/zaplog v0.0.22/go.mod h1:lOdA2Ju4Alify777G8AvdZVqfCPUEpkWjsLgEOkVfS4= 40 | go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= 41 | go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= 42 | go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= 43 | go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= 44 | go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= 45 | go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= 46 | golang.org/x/exp v0.0.0-20250210185358-939b2ce775ac h1:l5+whBCLH3iH2ZNHYLbAe58bo7yrN4mVcnkHDYz5vvs= 47 | golang.org/x/exp v0.0.0-20250210185358-939b2ce775ac/go.mod h1:hH+7mtFmImwwcMvScyxUhjuVHR3HGaDPMn9rMSUUbxo= 48 | golang.org/x/mod v0.23.0 h1:Zb7khfcRGKk+kqfxFaP5tZqCnDZMjC5VtUBs87Hr6QM= 49 | golang.org/x/mod v0.23.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= 50 | golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= 51 | golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 52 | golang.org/x/tools v0.30.0 h1:BgcpHewrV5AUp2G9MebG4XPFI1E2W41zU1SaqVA9vJY= 53 | golang.org/x/tools v0.30.0/go.mod h1:c347cR/OJfw5TI+GfX7RUPNMdDRRbjvYTS0jPyvsVtY= 54 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 55 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= 56 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= 57 | gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= 58 | gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= 59 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 60 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 61 | -------------------------------------------------------------------------------- /import.go: -------------------------------------------------------------------------------- 1 | package formatgo 2 | 3 | import ( 4 | "os" 5 | "strings" 6 | 7 | "github.com/yyle88/erero" 8 | "github.com/yyle88/formatgo/internal/utils" 9 | "github.com/yyle88/syntaxgo/syntaxgo_ast" 10 | "github.com/yyle88/syntaxgo/syntaxgo_astnode" 11 | "golang.org/x/tools/imports" 12 | ) 13 | 14 | // NewImportsOptions returns a new imports.Options with default settings. 15 | // NewImportsOptions 返回一个具有默认设置的 imports.Options。 16 | func NewImportsOptions() *imports.Options { 17 | return &imports.Options{ 18 | TabWidth: 4, // 设置制表符宽度为 4 19 | TabIndent: true, // 启用制表符缩进 20 | Comments: true, // 保留注释 21 | Fragment: true, // 启用代码片段 22 | } 23 | } 24 | 25 | // CleanFileImportNewlines reads a Go source file, condenses the import section 26 | // by removing consecutive empty lines, and writes the result back to the file. 27 | // CleanFileImportNewlines 读取 Go 源代码文件,压缩导入部分 28 | // 通过去除连续的空行并将结果写回文件。 29 | func CleanFileImportNewlines(path string) error { 30 | source, err := os.ReadFile(path) 31 | if err != nil { 32 | return erero.Wro(err) // 返回读取文件时的错误 33 | } 34 | 35 | // Condense the import lines to remove empty lines 36 | // 压缩导入语句以去除空行 37 | newSrc, err := CleanCodeImportNewlines(source) 38 | if err != nil { 39 | return erero.Wro(err) // 返回压缩导入行时的错误 40 | } 41 | 42 | // Write the new source code back to the file 43 | // 将新源代码写回文件 44 | err = utils.WriteFileKeepMode(path, newSrc) 45 | if err != nil { 46 | return erero.Wro(err) // 返回写入文件时的错误 47 | } 48 | 49 | return nil 50 | } 51 | 52 | // CleanCodeImportNewlines processes the source code and condenses consecutive 53 | // empty lines in the import section to a single newline. 54 | // CleanCodeImportNewlines 处理源代码,并将导入部分中的连续空行压缩为单一的换行符。 55 | func CleanCodeImportNewlines(source []byte) ([]byte, error) { 56 | astBundle, err := syntaxgo_ast.NewAstBundleV1(source) 57 | if err != nil { 58 | return nil, erero.Wro(err) // 返回解析 AST 时的错误 59 | } 60 | 61 | astFile, _ := astBundle.GetBundle() 62 | 63 | // If no imports exist, return the source as it is 64 | // 如果没有导入语句,则直接返回原始源代码 65 | if len(astFile.Imports) == 0 { 66 | return source, nil 67 | } 68 | 69 | // Create a new node that covers the range of import statements 70 | // 创建一个新的节点,覆盖所有导入语句的范围 71 | node := syntaxgo_astnode.NewNode( 72 | astFile.Imports[0].Pos(), 73 | astFile.Imports[len(astFile.Imports)-1].End(), 74 | ) 75 | 76 | // Get the text of the import section 77 | // 获取导入部分的文本 78 | oldImports := node.GetText(source) 79 | if oldImports == "" { 80 | return source, nil 81 | } 82 | 83 | // Condense consecutive newlines into a single newline in the import section 84 | // 在导入部分将连续的换行符压缩为一个换行符 85 | newImports := condenseLines(oldImports) 86 | if oldImports == newImports { 87 | return source, nil // No changes made, return the source as it is // 如果没有变化,则返回原始源代码 88 | } 89 | 90 | // Change the import section to the condensed version 91 | // 将导入部分替换为压缩后的版本 92 | return syntaxgo_astnode.ChangeNodeCode(source, node, []byte(newImports)), nil 93 | } 94 | 95 | // condenseLines replaces multiple consecutive newlines with a single newline. 96 | // It iteratively replaces instances of double newlines until only single newlines remain. 97 | // condenseLines 将多个连续的换行符替换为单个换行符。 98 | // 它通过迭代地替换双换行符,直到只剩下单个换行符。 99 | func condenseLines(source string) string { 100 | for origin := ""; origin != source; source = strings.ReplaceAll(source, "\n\n", "\n") { 101 | origin = source 102 | } 103 | return source 104 | } 105 | -------------------------------------------------------------------------------- /import_test.go: -------------------------------------------------------------------------------- 1 | package formatgo 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/kr/pretty" 7 | ) 8 | 9 | func TestGetImportsOptions(t *testing.T) { 10 | _, _ = pretty.Println(NewImportsOptions()) 11 | } 12 | -------------------------------------------------------------------------------- /internal/examples/example1/example1.go: -------------------------------------------------------------------------------- 1 | package example1 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "time" 7 | 8 | "github.com/yyle88/rese" 9 | "github.com/yyle88/runpath" 10 | ) 11 | 12 | // ShowExampleFileCode 显示Example文件的代码 13 | func ShowExampleFileCode() { 14 | since := time.Now() 15 | 16 | sourceCode := GetExampleFileCode() 17 | 18 | fmt.Println(time.Since(since)) 19 | 20 | fmt.Println(string(sourceCode)) 21 | } 22 | 23 | // GetExampleFileCode 获取Example文件的代码 24 | func GetExampleFileCode() []byte { 25 | return rese.V1(os.ReadFile(GetExampleFilePath())) 26 | } 27 | 28 | // GetExampleFilePath 获取Example文件的路径 29 | func GetExampleFilePath() string { 30 | return runpath.Path() 31 | } 32 | -------------------------------------------------------------------------------- /internal/examples/example1/example1_test.go: -------------------------------------------------------------------------------- 1 | package example1 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/require" 7 | "github.com/yyle88/formatgo" 8 | "github.com/yyle88/rese" 9 | ) 10 | 11 | func TestShowExampleFileCode(t *testing.T) { 12 | ShowExampleFileCode() 13 | } 14 | 15 | func TestFormatSrcAndCompare(t *testing.T) { 16 | const code = ` 17 | package example1 18 | 19 | import ( 20 | "fmt" 21 | 22 | "github.com/yyle88/rese" 23 | 24 | "github.com/yyle88/runpath" 25 | 26 | "os" 27 | "time" 28 | ) 29 | 30 | // ShowExampleFileCode 显示Example文件的代码 31 | func ShowExampleFileCode() { 32 | since := time.Now() 33 | 34 | sourceCode := GetExampleFileCode() 35 | 36 | fmt.Println(time.Since(since)) 37 | 38 | fmt.Println(string(sourceCode)) 39 | } 40 | 41 | // GetExampleFileCode 获取Example文件的代码 42 | func GetExampleFileCode() []byte { 43 | return rese.V1(os.ReadFile(GetExampleFilePath())) 44 | } 45 | 46 | // GetExampleFilePath 获取Example文件的路径 47 | func GetExampleFilePath() string { 48 | return runpath.Path() 49 | } 50 | 51 | ` 52 | newCode := rese.C1(formatgo.FormatCode(code)) 53 | 54 | t.Log(newCode) 55 | 56 | expectedCode := string(GetExampleFileCode()) 57 | 58 | t.Log(expectedCode) 59 | 60 | require.Equal(t, expectedCode, newCode) 61 | } 62 | -------------------------------------------------------------------------------- /internal/utils/utils.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "os" 5 | "path/filepath" 6 | "strings" 7 | 8 | "github.com/yyle88/erero" 9 | "github.com/yyle88/zaplog" 10 | "go.uber.org/zap" 11 | ) 12 | 13 | func WriteFileKeepMode(path string, data []byte) error { 14 | return os.WriteFile(path, data, GetFileMode(path)) 15 | } 16 | 17 | func GetFileMode(path string) os.FileMode { 18 | stat, err := os.Stat(path) 19 | if err != nil { 20 | if os.IsNotExist(err) { 21 | return os.FileMode(0644) 22 | } else { 23 | zaplog.LOG.Warn("stat wrong", zap.String("path", path), zap.Error(err)) 24 | return os.FileMode(0644) 25 | } 26 | } 27 | return stat.Mode() 28 | } 29 | 30 | func IsRootExists(path string) (bool, error) { 31 | info, err := os.Stat(path) 32 | if err != nil { 33 | if os.IsNotExist(err) { 34 | return false, nil // 路径不存在 35 | } 36 | return false, erero.Wro(err) // 其他的错误 37 | } 38 | return info.IsDir(), nil 39 | } 40 | 41 | func IsFileExists(path string) (bool, error) { 42 | info, err := os.Stat(path) 43 | if err != nil { 44 | if os.IsNotExist(err) { 45 | return false, nil // 路径不存在 46 | } 47 | return false, erero.Wro(err) // 其他的错误 48 | } 49 | return !info.IsDir(), nil 50 | } 51 | 52 | func LsAsMap(root string) (map[string]string, error) { 53 | names, err := Ls(root) 54 | if err != nil { 55 | return nil, erero.WithMessage(err, "wrong") 56 | } 57 | var mp = make(map[string]string, len(names)) 58 | for _, name := range names { 59 | mp[name] = filepath.Join(root, name) 60 | } 61 | return mp, nil 62 | } 63 | 64 | func Ls(root string) (names []string, err error) { 65 | infos, err := os.ReadDir(root) 66 | if err != nil { 67 | return nil, erero.WithMessage(err, "wrong") 68 | } 69 | names = make([]string, 0, len(infos)) 70 | for _, info := range infos { 71 | names = append(names, info.Name()) 72 | } 73 | return names, nil 74 | } 75 | 76 | func HasAnySuffix(s string, suffixes []string) bool { 77 | for _, suffix := range suffixes { 78 | if strings.HasSuffix(s, suffix) { 79 | return true 80 | } 81 | } 82 | return false 83 | } 84 | -------------------------------------------------------------------------------- /internal/utils/utils_test.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/yyle88/runpath" 7 | ) 8 | 9 | func TestGetFileMode(t *testing.T) { 10 | t.Log(GetFileMode(runpath.Path())) 11 | } 12 | -------------------------------------------------------------------------------- /option.go: -------------------------------------------------------------------------------- 1 | package formatgo 2 | 3 | import ( 4 | "math" 5 | 6 | "github.com/yyle88/zaplog" 7 | "go.uber.org/zap" 8 | "golang.org/x/tools/imports" 9 | ) 10 | 11 | // Options holds configuration options for imports formatting. 12 | // Options 结构体保存了导入格式化的配置选项。 13 | type Options struct { 14 | ImportsOptions *imports.Options // Options for formatting imports // 导入格式化的选项 15 | CondenseImport bool // Whether to condense imports by removing empty lines // 是否压缩导入部分,去除空行 16 | IsFormatImport bool // Whether to format import statements // 是否格式化导入语句 17 | } 18 | 19 | // NewOptions creates and returns a new Options instance with default values. 20 | // NewOptions 创建并返回一个带有默认值的 Options 实例。 21 | func NewOptions() *Options { 22 | return &Options{ 23 | ImportsOptions: NewImportsOptions(), // 使用默认的导入选项创建 24 | CondenseImport: true, // 默认开启导入部分压缩 25 | IsFormatImport: true, // 默认启用导入格式化 26 | } 27 | } 28 | 29 | // RootOptions holds configuration options for the root directory formatting. 30 | // RootOptions 结构体保存了根目录格式化的配置选项。 31 | type RootOptions struct { 32 | FileOptions *Options // File formatting options // 文件格式化选项 33 | FilterRoot func(depth int, path string, name string) bool // Filter to format only directories that match certain criteria // 用于过滤目录名/路径的条件,只有符合条件的目录才会被格式化 34 | FilterFile func(depth int, path string, name string) bool // Filter to format only files that match certain criteria // 用于过滤文件名/路径的条件,只有符合条件的文件才会被格式化 35 | FileHasSuffixes []string // Suffixes of files to be formatted // 要格式化的文件后缀列表 36 | SkipHiddenDepth int // Depth level to skip hidden directories (e.g., .git, .idea) // 在多少层深度内跳过隐藏目录(例如 .git,.idea) 37 | } 38 | 39 | // NewRootOptions creates and returns a new RootOptions instance with default values. 40 | // NewRootOptions 创建并返回一个带有默认值的 RootOptions 实例。 41 | func NewRootOptions() *RootOptions { 42 | return &RootOptions{ 43 | FileOptions: NewOptions(), // 默认使用 NewOptions() 创建 FileOptions 44 | FilterRoot: func(depth int, path string, name string) bool { 45 | // Debug log for root filtering 46 | // 输出根目录过滤的调试日志 47 | zaplog.LOG.Debug("format_root", zap.Int("depth", depth), zap.String("path", path), zap.String("name", name)) 48 | return true // 默认允许所有根目录 49 | }, 50 | FilterFile: func(depth int, path string, name string) bool { 51 | // Debug log for file filtering 52 | // 输出文件过滤的调试日志 53 | zaplog.LOG.Debug("format_file", zap.Int("depth", depth), zap.String("path", path), zap.String("name", name)) 54 | return true // 默认允许所有文件 55 | }, 56 | FileHasSuffixes: []string{ // Default file suffixes to format 57 | ".go", // Go source files 58 | ".GO", // Go source files with uppercase extension 59 | }, 60 | SkipHiddenDepth: math.MaxInt, // Skip hidden directories at all depths (default behavior) 61 | // 跳过所有层级的隐藏目录(默认行为) 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /option_test.go: -------------------------------------------------------------------------------- 1 | package formatgo 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/kr/pretty" 7 | ) 8 | 9 | func TestNewOptions(t *testing.T) { 10 | _, _ = pretty.Println(NewOptions()) 11 | } 12 | -------------------------------------------------------------------------------- /simple.go: -------------------------------------------------------------------------------- 1 | package formatgo 2 | 3 | // FormatBytes formats Go source code from a byte slice. 4 | // FormatBytes 格式化golang的源代码 5 | func FormatBytes(code []byte) ([]byte, error) { 6 | return FormatBytesWithOptions(code, NewOptions()) 7 | } 8 | 9 | // FormatCode formats Go source code from a string. 10 | // FormatCode 格式化源代码字符串 11 | func FormatCode(code string) (string, error) { 12 | return FormatCodeWithOptions(code, NewOptions()) 13 | } 14 | 15 | // FormatFile formats a Go source code file at the given path. 16 | // FormatFile 格式化源代码文件 17 | func FormatFile(path string) error { 18 | return FormatFileWithOptions(path, NewOptions()) 19 | } 20 | 21 | // FormatRoot formats all Go source files in the specified root directory and its subdirectories. 22 | // FormatRoot 格式化整个目录以及其子目录下的所有go文件 23 | func FormatRoot(root string) error { 24 | return FormatRootWithOptions(root, NewRootOptions()) 25 | } 26 | -------------------------------------------------------------------------------- /simple_test.go: -------------------------------------------------------------------------------- 1 | package formatgo 2 | 3 | import ( 4 | "path/filepath" 5 | "runtime" 6 | "strings" 7 | "testing" 8 | 9 | "github.com/stretchr/testify/require" 10 | ) 11 | 12 | func TestFormatCode(t *testing.T) { 13 | const code = ` 14 | package main 15 | 16 | import ( 17 | "fmt" 18 | "strconv" 19 | ) 20 | import "time" 21 | 22 | //这是main函数的注释 23 | func main() { 24 | fmt.Println("abc") //随便打印个字符串 25 | fmt.Println(time.Now()) //随便打印当前时间 26 | fmt.Println(strconv.Itoa(1)) 27 | } 28 | ` 29 | 30 | t.Log(code) 31 | 32 | newCode, err := FormatCode(code) 33 | require.NoError(t, err) 34 | t.Log(newCode) 35 | } 36 | 37 | func TestFormatFile(t *testing.T) { 38 | _, path, _, ok := runtime.Caller(0) 39 | require.True(t, ok) 40 | t.Log(path) 41 | require.True(t, strings.HasSuffix(path, "/formatgo/simple_test.go")) //需要确保就是这个文件 42 | 43 | require.NoError(t, FormatFile(path)) //把该文件格式化 44 | } 45 | 46 | func TestFormatProject(t *testing.T) { 47 | _, path, _, ok := runtime.Caller(0) 48 | require.True(t, ok) 49 | t.Log(path) 50 | require.True(t, strings.HasSuffix(path, "/formatgo/simple_test.go")) 51 | root := filepath.Dir(path) 52 | t.Log(root) 53 | require.True(t, strings.HasSuffix(root, "/formatgo")) //这样99.99%能够确保目录路径是正确的 54 | 55 | require.NoError(t, FormatRoot(root)) //把本项目格式化 56 | } 57 | --------------------------------------------------------------------------------