betteralign is a tool to detect structs that would use less memory if their fields were sorted and optionally sort such fields.
This is a fork of an official Go fieldalignment tool and vast majority of the alignment code has remained the same. There are however some notable changes:
_generated.go
, _gen.go
, .gen.go
, .pb.go
, .pb.gw.go
) or due to package-level comment containing Code generated by... DO NOT EDIT.
string,_test.go
suffix),betteralign:ignore
,Retaining comments has been done with using DST (Decorated Syntax Tree) with decorating regular AST. Sadly when using DST we cannot use "fix" mode with SuggestedFixes, but we have to print whole DST to retain decorations.
In case you are wondering why DST and not AST, in general sense AST does not associate comments to nodes, but it holds fixed offsets. Original fieldalignment tool just erases all struct/field/floating comments due to this issue and while there is a CL with a possible fix, it's still a work in progress as of this time.
Note, this is a single-pass analysis tool and sorting all structs optimally might require more than one pass.
Let us also mention original projects handling this task and without which this derivative work wouldn't exist in the first place:
There are two ways of installing betteralign:
Download your preferred flavor from the releases page and install manually, typically to /usr/local/bin/betteralign
go install github.com/dkorunic/betteralign/cmd/betteralign@latest
betteralign: find structs that would use less memory if their fields were sorted
Usage: betteralign [-flag] [package]
Flags:
-apply
apply suggested fixes
-generated_files
also check and fix generated files
-test_files
also check and fix test files
To get all recommendations on your project:
betteralign ./...
To automatically fix your project files, while ignoring test and generated files:
betteralign -apply ./...
It is possible to include generated files and test files by enabling generated_files
and/or test_files
flags.