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:
- skips over generated files, either files with known "generated" suffix (
_generated.go
,_gen.go
,.gen.go
,.pb.go
,.pb.gw.go
) or due to package-level comment containingCode generated by... DO NOT EDIT.
string, - skips over test files (files with
_test.go
suffix), - skips over structs marked with comment
betteralign:ignore
, - doesn't lose comments (field comments, doc comments, floating comments or otherwise) but the comment position heuristics is still work in progress,
- does very reliable atomic file I/O with strong promise not to corrupt and/or lose contents upon rewrite (not on Windows platform),
- has more thorough testing in regards to expected optimised vs golden results,
- integrates better with environments with restricted CPU and/or memory resources (Docker containers, K8s containers, LXC, LXD etc).
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:
- maligned from Matthew Dempsky
- structslop from orijtech
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.