iferrfmt is a command-line tool written in Go that reformats error handling code in Go source files.
The tool automates the refactoring of error handling patterns. It scans Go source files or directories, identifies assignments involving error variables followed by an if statement that checks if the error is non-nil, and modifies the code to use a standardized variable name (err). This helps maintain consistent error handling throughout the codebase.
- Directory Traversal: Recursively walks through a directory, processing all
.gofiles while skipping thevendordirectory. - File Processing: If a file path is provided and it ends with
.go, that file is processed directly. - AST Manipulation: Utilizes Go’s AST (Abstract Syntax Tree) to:
- Detect error assignments with a single error-type variable.
- Replace specific error variable names with
err. - Update subsequent
ifstatements that check the error value.
- Formatting: Rewrites the file with the updated code formatting if any changes are made.
Build the tool:
go build main.goRun the tool by providing either a file or a directory:
./iferrfmt <path-or-file>- When a directory is specified, all Go files in that directory (and its subdirectories, excluding
vendor) will be processed. - When a file is specified, only that file will be processed.
Suppose you have a Go source file with non-standard error handling:
_, err := someFunc()
// some other code
if err != nil {
// handle error
}After running iferrfmt, the code will be reformatted to:
if _, err := someFunc(); err != nil {
// handle error
}-
If no path or file is provided, the tool prints a usage message:
Usage: iferrfmt <path-or-file> -
Standard error reporting is done to
stderrif file I/O or parsing issues occur.
Refer to the LICENSE file for license details.