Egon Elbre

gorelo

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.

To install the tool:

1
go install github.com/loov/gorelo@latest

Intro #

Let’s say you have a codebase that is just a single package:

1
2
3
4
5
app/
    server.go      — Server, serverOptions, handleRequest, ...
    db.go          — DB, dbOptions, runMigrations, ...
    service.go     — Service, serviceOptions, processJob, ...
    main.go        — wires everything together

With some files:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
package app

type dbOptions struct {
    dsn     string
    maxIdle int
}

type DB struct {
    opts dbOptions
}

func newDB(opts dbOptions) *DB {
    return &DB{opts: opts}
}

func (d *DB) queryRow() error {
    return nil
}

func (d *DB) runMigrations() error {
    return nil
}
1
2
3
module example.com/app

go 1.27.4
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package app

func Run() error {
    db := newDB(dbOptions{
        dsn:     "postgres://localhost/app",
        maxIdle: 4,
    })
    if err := db.runMigrations(); err != nil {
        return err
    }

    server := newServer(serverOptions{
        addr:    ":8080",
        maxConn: 100,
    }, db)

    service := newService(serviceOptions{
        workers: 4,
        retries: 3,
    }, server)

    return service.processJob()
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package app

type serverOptions struct {
    addr    string
    maxConn int
}

type Server struct {
    opts serverOptions
    db   *DB
}

func newServer(opts serverOptions, db *DB) *Server {
    return &Server{opts: opts, db: db}
}

func (s *Server) handleRequest() error {
    return s.db.queryRow()
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package app

type serviceOptions struct {
    workers int
    retries int
}

type Service struct {
    opts   serviceOptions
    server *Server
}

func newService(opts serviceOptions, server *Server) *Service {
    return &Service{opts: opts, server: server}
}

func (s *Service) processJob() error {
    return s.server.handleRequest()
}

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:

gorelo.rules
1
2
3
server/server.go <-
    Server.handleRequest=HandleRequest
    Server.opts=Opts

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
package db

type Options struct {
    DSN     string
    MaxIdle int
}

type DB struct {
    Opts Options
}

func New(opts Options) *DB {
    return &DB{Opts: opts}
}

func (d *DB) QueryRow() error {
    return nil
}

func (d *DB) RunMigrations() error {
    return nil
}
1
2
3
module example.com/app

go 1.27.4
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# 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 <-
    Server
    serverOptions=Options
    newServer=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=HandleRequest
    Server.opts=Opts
    serverOptions.addr=Addr
    serverOptions.maxConn=MaxConn

# --- db package ---

db/db.go <-
    DB
    dbOptions=Options
    newDB=New

db/db.go <-
    DB.queryRow=QueryRow
    DB.runMigrations=RunMigrations
    DB.opts=Opts
    dbOptions.dsn=DSN
    dbOptions.maxIdle=MaxIdle

# --- service package ---

service/service.go <-
    Service
    serviceOptions=Options
    newService=New

service/service.go <-
    Service.processJob=ProcessJob
    Service.opts=Opts
    Service.server=Server
    serviceOptions.workers=Workers
    serviceOptions.retries=Retries
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package app

import (
	"example.com/app/db"
	"example.com/app/server"
	"example.com/app/service"
)

func Run() error {
    db := db.New(db.Options{
        DSN:     "postgres://localhost/app",
        MaxIdle: 4,
    })
    if err := db.RunMigrations(); err != nil {
        return err
    }

    server := server.New(server.Options{
        Addr:    ":8080",
        MaxConn: 100,
    }, db)

    service := service.New(service.Options{
        Workers: 4,
        Retries: 3,
    }, server)

    return service.ProcessJob()
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package server

import (
	"example.com/app/db"
)

type Options struct {
    Addr    string
    MaxConn int
}

type Server struct {
    Opts Options
    db   *db.DB
}

func New(opts Options, db *db.DB) *Server {
    return &Server{Opts: opts, db: db}
}

func (s *Server) HandleRequest() error {
    return s.db.QueryRow()
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package service

import (
	"example.com/app/server"
)

type Options struct {
    Workers int
    Retries int
}

type Service struct {
    Opts   Options
    Server *server.Server
}

func New(opts Options, server *server.Server) *Service {
    return &Service{Opts: opts, Server: server}
}

func (s *Service) ProcessJob() error {
    return s.Server.HandleRequest()
}

Formatting and stubs #

If you wish to automatically format the code with some specific formatter, you can add:

1
@fmt gofmt -w

If you wish to automatically add stubs, in case there are external modules that import your code, then you can add:

1
@stubs=true

Which will then generate stubs like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package app

import (
    "example.com/app/db"
)

//go:fix inline
type DB = db.DB

//go:fix inline
type dbOptions = db.Options

//go:fix inline
func newDB(opts dbOptions) *DB { return db.New(opts) }

For moving whole files you can use:

gorelo.rules
1
server/server.go -> api/server.go

Attaching and detaching methods #

Sometimes a function really wants to be a method, or the other way around:

cart.go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
func total(c *Cart) int {
        sum := 0
        for _, item := range c.Items {
                sum += item.Price * item.Count
        }
        return sum
}

func (c *Cart) receipt() string {
        s := ""
        for _, item := range c.Items {
                s += fmt.Sprintf("%-10s %s\n", item.Name, formatPrice(item.Price*item.Count))
        }
        return s + "total      " + formatPrice(total(c)) + "\n"
}
gorelo.rules
1
2
total=Cart.Total
Cart.receipt=!Receipt -> receipt.go

The first rule turns total into a method, the second one turns receipt into a plain function in receipt.go; the receiver becomes the first argument:

cart.go
1
2
3
4
5
6
7
func (c *Cart) Total() int {
        sum := 0
        for _, item := range c.Items {
                sum += item.Price * item.Count
        }
        return sum
}
receipt.go
1
2
3
4
5
6
7
func Receipt(c *Cart) string {
        s := ""
        for _, item := range c.Items {
                s += fmt.Sprintf("%-10s %s\n", item.Name, formatPrice(item.Price*item.Count))
        }
        return s + "total      " + formatPrice(c.Total()) + "\n"
}

Querying the codebase #

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:

1
2
3
4
5
6
7
$ gorelo grep 'return nil'
2 declarations contain "return nil"

db.go:16  method  DB.queryRow
    17: return nil
db.go:20  method  DB.runMigrations
    21: return nil

Then we have more structural listing gorelo ls:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
$ 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

Collaborating with LLMs #

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$ gorelo cluster
package .  (10 declarations, 21 dependencies)

  Cluster 1  (cohesion: 0.64)
    type    dbOptions                      db.go:3
    type    DB                             db.go:8
    func    newDB                          db.go:12
    func    Run                            main.go:3
    method    .queryRow                     db.go:16
    method    .runMigrations                db.go:20

  Cluster 2  (cohesion: 0.50)
    type    serverOptions                  server.go:3
    type    Server                         server.go:8
    func    newServer                      server.go:13
    method    .handleRequest                server.go:17

  Cluster 3  (cohesion: 0.57)
    type    serviceOptions                 service.go:3
    type    Service                        service.go:8
    func    newService                     service.go:13
    method    .processJob                   service.go:17

  Modularity: 0.23

Guts: github.com/loov/gorelo/mast #

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:

1
2
3
4
type Group struct {
    Name   string
    Kind   ObjectKind // e.g. type, func, var
    Idents []*Ident

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.

Guts: github.com/loov/gorelo/edit #

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.

gorelo.rules
1
2
Request=HTTPRequest
Server.handle=!lookupRoute -> routes.go
before
server.go
func (s *Server) handle(r *Request) string {
	return s.routes[r.Path]
}
after
routes.go
func lookupRoute(s *Server, r *HTTPRequest) string {
	return s.routes[r.Path]
}

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:

    Conclusion #

    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.