Half a year ago I had to help out a few times to fix Go package structure for some codebases. Of course, partly because of LLMs weren’t guided properly to write readable code… but, some were also written artisanally.
There are of course some tools that help to refactor Go code, such as gopls, gomvpkg, eg and rf. Most reliable refactoring was for me Goland. rf is definitely the best of the bunch. But all of them suffered from the following problems ~6 months back:
I had to refactor things one-by-one.
They tended to break when build tags were involved.
Or missed some specific features I needed.
Of course I could use LLMs to do the refactors, but those approaches are rather slow… and also, I’m not confident enough in LLMs that they do the transformations correctly.
But, I pretty much knew how to solve the problem so I ended up conjuring up github.com/loov/gorelo. I’ll go in some of the interesting details in a bit, but here’s the gist of it.
This project is not large enough to warrant for refactor, but it can allow to demonstrate the main features of gorelo.
The first step is creating a new .rules file, which describes how and what we want to move things. Let’s say we want to move the server type to a new package called server. Then we can write it as:
gorelo.rules
1
2
3
4
5
6
7
8
# move the `Server` type to a new file:
server/server.go<-Server# move `serverOptions` and rename it to `Options`.
server/server.go<-serverOptions=Options# when not using command line you can also point the arrow the other way:
newServer=New->server/server.go
All the methods will follow their types automatically, however if we want to make some methods or fields public during the move; we can do it with this syntax:
It’s somewhat annoying that I wasn’t able to use Server.handleRequest syntax, because filepaths may contain them… I hope I can figure out a better syntax. Maybe rf approach is better?
When the rules file is complete you can check whether the move is valid with:
1
gorelo check gorelo.rules
For example if I would forget making something public that needs to be public I get a complaint:
1
warning: server.go:8: moved decl "Server" references unexported "serverOptions" which is not in the move set
Once you’ve fixed all the check issues, then you can run:
1
gorelo apply gorelo.rules
Of course, it does not guarantee that it will exactly compile; it doesn’t check everything. I usually run git clean and git reset to retry the rules, if something breaks.
In our example application case it would give this output:
# Each group moves declarations to a new subpackage and renames# private identifiers to exported ones so they're accessible# across packages.# --- server package ---server/server.go<-ServerserverOptions=OptionsnewServer=New# Server methods follow automatically.# Options fields are set by main.go, outside the new packages,# so they need to be exported as well.# handleRequest is private and used only internally,# but it calls db.queryRow across the new package boundary,# so it needs to be exported too.server/server.go<-Server.handleRequest=HandleRequestServer.opts=OptsserverOptions.addr=AddrserverOptions.maxConn=MaxConn# --- db package ---db/db.go<-DBdbOptions=OptionsnewDB=Newdb/db.go<-DB.queryRow=QueryRowDB.runMigrations=RunMigrationsDB.opts=OptsdbOptions.dsn=DSNdbOptions.maxIdle=MaxIdle# --- service package ---service/service.go<-ServiceserviceOptions=OptionsnewService=Newservice/service.go<-Service.processJob=ProcessJobService.opts=OptsService.server=ServerserviceOptions.workers=WorkersserviceOptions.retries=Retries
gorelo provides some useful tooling for examining how and where things are being used.
The first basic one is gorelo grep. It searches for a string and prints methods that mention a specific string. It does support globs if you need it. For example:
$ gorelo ls
db.go (package app)type dbOptions 3:6 4 lines
type DB 8:10 3 lines
func newDB 12:14 3 lines
method DB.queryRow 16:18 3 lines
method DB.runMigrations 20:22 3 lines
main.go (package app) func Run 3:23 21 lines
$ gorelo ls DB
db.go (package app)type DB 8:10 3 lines
method DB.queryRow 16:18 3 lines
method DB.runMigrations 20:22 3 lines
$ gorelo ls --detail Server
server.go (package app)type Server 8:11 4 lines 5 refs deps: DB, serverOptions
method Server.handleRequest 17:19 3 lines 1 refs deps: Server
There’s a way to find where a thing is referenced in the codebase with gorelo refs:
1
2
3
4
5
6
7
$ gorelo refs Server
Server (type, server.go:8) server.go:13
server.go:14
server.go:17
service.go:10
service.go:13
For finding what something uses (gorelo deps) and what it is used by (gorelo refs):
1
2
3
4
5
6
7
8
9
10
11
$ gorelo deps Server
Server (type, server.go:8)type DB db.go:8
type serverOptions server.go:3
field opts server.go:9
field db server.go:10
$ gorelo refs Server.db
Server.db (field, server.go:10) server.go:14
server.go:18
There’s also gorelo coverage, which lists all the methods it reaches through a specific func:
1
2
3
4
5
6
7
8
9
10
11
12
$ gorelo coverage -for DB --by-method '*'example.com/app.DB — 2 of 2 methods reached by 5 of 8 entries
queryRow 4 entries db.go:16
Run main.go:3
handleRequest server.go:17
processJob service.go:17
queryRow db.go:16
runMigrations 2 entries db.go:20
Run main.go:3
runMigrations db.go:20
Now the tool has been written to support LLMs doing the refactoring. When something just needs to be made public a LLM should be able to automatically add a new rule for it.
There’s a command gorelo skill to teach your LLM how to use the tool.
One important feature for figuring out how to break the project apart is gorelo cluster. It tries to find coherent clusters in how things are referenced and might be separated into packages:
One of the problems needed solving was build tags. Unfortunately go/types and golang.org/x/tools/go/packages only type-check one build configuration at a time, so references from e.g. _linux.go files are invisible on a Mac. For the tool to work properly, it needs to also rename and move code in files that have build tags.
Of course it would be possible to rewrite the whole ast parsing and logic to handle build tags… but there’s a easier way, it’s hacky, but it’s definitely easier.
Every file is parsed once, regardless of build tags, and then grouped by its build tag. When the groups don’t define the same top-level names, everything is type-checked in a single pass. Otherwise, each build tag is type-checked separately, together with the files without build tags, and the results are combined. Type errors are ignored, because code written for Linux often doesn’t type-check on a Mac.
All of this is done by a package called github.com/loov/gorelo/mast - i.e. “multi-AST”. It contains an additional type, which collects every place a name is defined or used:
Combining the passes needs a trick. Each pass creates new types.Object-s, so they can’t be compared across passes. Instead, groups are keyed by package path, name and receiver type, so Server from the Linux pass and Server from the Windows pass end up in the same group. References to something that was checked in a different pass stay unresolved; at the end they are matched to the package-level name.
This collapsed group from multiple AST-s might end up having multiple type definitions for a single name. And using that Group makes it easy to find all the places something is being used across build tags and rename all of them at once.
Of course, this approach is not perfect and could fail in some specific cases. For more of the details see the documentation.
The other problem I faced was how to do hundreds of edits on the codebase without trampling on edits that change the same thing. For example you might have four edits on the same region: move the method, detach it, rename it, and rename a type it uses.
All four touch the first line of handle. We can still apply them together, borrowing ideas from operational transformations.
For example, you could have a move: [a]bc -> bc[a] and a rename a[b]c -> a[X]c. Then if we know how to modify rename after move has been done or move after rename has been done, we can apply them both as long as the input ranges are properly nested or disjoint. We can simplify further: a move becomes a delete at the source plus an insert at the destination, and the edits inside the move are applied to the inserted text first.
For our example the edits look like this. Toggle them in any order; you end up with the same code, because every edit refers to the original offsets:
Hopefully this tool helps you save some poor codebase from a ragged life. If you have any feature requests feel free to create an issue in github.com/loov/gorelo.