Dependency wiring in plain Go, generated from one small config file.
You already write the functions that create your database, your logger, your cache. tack finds them, matches them to the methods of an interface, and writes the constructor that ties everything together. The result is ordinary Go you can read top to bottom.
- One config file, one command. Describe the interface, run
tack, commit the result. - Plain output. A constructor, a struct, and accessor methods. No reflection, no runtime magic.
- Cleanup built in. Every resource you open is closed in reverse order, including when a later step fails.
- Clear errors. A missing or ambiguous provider names the exact method and type, and config problems are reported with their field path.
- Deterministic. Same config and source, same output. Review it like any other code.
Status: early. Config parsing and validation,
tack.yamldiscovery, provider matching, code generation and thetackcommand are implemented. No version is tagged yet, so@latestinstalls the newest commit ofmain.
- Install
- Quickstart
- How providers are found
- Several implementations of one interface
- Testing
- Config reference
- Errors
- Running tack
- Limitations
- Development
- License
Requires Go 1.27 or later.
go install github.com/benipranata/tack/cmd/tack@latest1. Declare what you need as an interface. Each method names a dependency by its return type and takes no arguments.
// internal/app/service.go
package app
import (
"database/sql"
"log/slog"
)
type Service interface {
DB() *sql.DB
Logger() *slog.Logger
}2. Write providers you probably already have. Every provider has the same signature:
func Provide…(ctx context.Context) (T, func(), error)| Return value | Meaning |
|---|---|
T |
The type one interface method returns, such as *sql.DB for DB(). tack matches it exactly. |
func() |
The cleanup, called when the service is closed. Return nil if there is nothing to close. |
error |
Return it to stop wiring. Everything created so far is cleaned up first. |
The function name is free; Provide… is only a convention. For example:
// internal/providers/providers.go
package providers
import (
"context"
"database/sql"
"log/slog"
"os"
)
func ProvideDB(ctx context.Context) (*sql.DB, func(), error) {
db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
if err != nil {
return nil, nil, err
}
return db, func() { db.Close() }, nil
}
func ProvideLogger(ctx context.Context) (*slog.Logger, func(), error) {
return slog.New(slog.NewJSONHandler(os.Stdout, nil)), nil, nil
}3. Point tack at them in tack.yaml, at your module root:
prefix: New
providers:
- internal/providers
targets:
- package: internal/app
interface: Service4. Run it.
tacktack writes internal/app/service_gen.go:
// Code generated by tack. DO NOT EDIT.
package app
import (
"context"
"database/sql"
"fmt"
"log/slog"
"example.com/myapp/internal/providers"
)
func NewService(ctx context.Context) (Service, func(), error) {
var cleanups []func()
cleanup := func() {
for i := len(cleanups) - 1; i >= 0; i-- {
cleanups[i]()
}
}
db, dbCleanup, err := providers.ProvideDB(ctx)
if err != nil {
cleanup()
return nil, nil, fmt.Errorf("ProvideDB: %w", err)
}
if dbCleanup != nil {
cleanups = append(cleanups, dbCleanup)
}
logger, loggerCleanup, err := providers.ProvideLogger(ctx)
if err != nil {
cleanup()
return nil, nil, fmt.Errorf("ProvideLogger: %w", err)
}
if loggerCleanup != nil {
cleanups = append(cleanups, loggerCleanup)
}
return &service{
db: db,
logger: logger,
}, cleanup, nil
}
type service struct {
db *sql.DB
logger *slog.Logger
}
func (s *service) DB() *sql.DB { return s.db }
func (s *service) Logger() *slog.Logger { return s.logger }5. Use it.
svc, closeFn, err := app.NewService(ctx)
if err != nil {
log.Fatal(err)
}
defer closeFn()
rows, err := svc.DB().QueryContext(ctx, "select 1")
svc.Logger().Info("ready")Add a method to Service, add a provider, run tack again. That is the whole workflow.
tack matches by type, not by name. For every method on your interface, it looks for a provider returning exactly that type, searching in this order and using the first layer that has one:
- the output's own
providerpackage (if set) - the global
providerspackages - the output package
Providers in the first two layers must be exported. The output package is searched last and may also use unexported providers.
If nothing matches, or two providers in the same layer return the same type, tack stops and tells you
which method and which type. To resolve an ambiguity, move one provider to a different layer or give
the output its own provider package.
An output's provider also works on its own, to override a few dependencies and keep the rest shared:
prefix: New
providers:
- internal/providers
targets:
- package: internal/cache
interface: Cache
output:
- provider: internal/providers/redisA function counts as a provider only if it is not generic and has exactly this shape:
func(context.Context) (T, func(), error).
Methods that return the same type get the same value: the provider runs once and each of those methods returns
that one instance. Primary() *sql.DB and Replica() *sql.DB share a single connection. To get two, give
them different types, such as type Replica struct{ *sql.DB } with its own provider.
Give a target more than one output. Each gets its own name, package, file, and, if you want,
its own provider.
prefix: New
providers:
- internal/providers # shared by every output: logger, config, ...
targets:
- package: internal/state
interface: State
output:
- name: NewProdState
package: internal/state/prod
provider: internal/providers/prod
- name: NewStagingState
package: internal/state/staging
provider: internal/providers/stagingNewProdState takes what it needs from internal/providers/prod first and falls back to the shared
providers for everything else. NewStagingState does the same with internal/providers/staging.
Two outputs in the same package need different names and different filenames. The config reference has the full rules.
Turn on test and tack writes a test double next to each constructor, so a fake is a one-line swap.
prefix: New
test: true
providers:
- internal/providers
targets:
- package: internal/app
interface: Servicetack writes internal/app/service_test_gen.go with a fields struct and a constructor.
Every method of the interface becomes a field:
svc := app.NewServiceTest(t, app.NewServiceTestFields{
DB: fakeDB,
Logger: slog.Default(),
})Forget a dependency and the test fails right away, naming the missing field. tack can only tell when the
value is nil: pointers, interfaces, funcs, maps, slices and channels. A value type such as an int or a
struct cannot be told apart from its zero value, so a forgotten one is not reported.
The file name does not end in _test.go, on purpose: that way other packages can import the double
in their own tests. It also means the double is compiled into the package, so it imports testing.
test is off by default. Set it once at the top to cover every output, or on a single output to
override the global setting either way:
test: true
targets:
- package: internal/state
interface: State
output:
- name: NewProdState
filename: prod_gen.go
- name: NewStagingState
filename: staging_gen.go
test: false # no test double for this oneSwitch test off again and tack removes the generated test file for you.
prefix: New # optional; the generated function is prefix + interface + suffix (NewService)
suffix: State # optional; appended to the interface name (RedisState, or NewRedisState with a prefix)
test: false # optional; also generate test doubles, default false
providers: # optional; packages searched for providers
- internal/providers
targets: # at least one
- package: internal/app # package that holds the interface
interface: Service # interface name
output: # optional; defaults to one output
- name: NewService # optional; function name
package: internal/app # optional; defaults to the target's package
filename: service_gen.go # optional; defaults to <lowercase interface>_gen.go
provider: internal/other # optional; searched before the global providers
test: true # optional; overrides the global test settingFor completion, inline docs and validation in your editor, point the YAML language server at the
JSON Schema with a comment on the first line of tack.yaml:
# yaml-language-server: $schema=https://raw.githubusercontent.com/benipranata/tack/main/tack.schema.json
prefix: New
providers:
- internal/providers
targets:
- package: internal/app
interface: ServiceAll package paths are relative to your module root. ./internal/app/ and internal/app mean the same thing.
Absolute paths and paths that leave the module (../x) are rejected. Unknown keys are rejected too, so a
typo fails loudly instead of being ignored.
Defaults and rules
| Field | Default | Rule |
|---|---|---|
name |
prefix + interface + suffix |
A valid Go identifier. With neither prefix nor suffix the default equals the interface name, which collides when the output is in the same package, so set a prefix, a suffix or a name. |
package |
the target's package | The directory may not exist yet. Then its last element becomes the package name, so it must be a valid Go identifier (prod, not my-pkg). |
filename |
<lowercase interface>_gen.go |
A file name, not a path. Must end in .go and not in _test.go. |
test |
the global test |
With test on, the output also claims <name>Test, <name>TestFields, and a …_test_gen.go file. |
An unexported interface gets an unexported constructor: redis with prefix: New gives newRedis, and with
suffix: State gives redisState. The test double adds Test to the final name, so suffix: State on Redis
gives RedisState and RedisStateTest.
One package, several outputs
Within one package, no two outputs may share a name or a file, and that includes the test double names and files.
A test double file is reserved even when test is off, because tack removes it then.
The generated struct is named after the output: NewService gives service, NewSvc gives svc, and a name without a
New prefix is used with its first letter lowered.
tack does not check these struct names. Two outputs in one package whose names differ only in that prefix or in the case of the first letter, such as
NewSvcandnewSvc, both generatesvcand the package fails to compile. Give them names that stay different.
tack validates in two steps and reports all problems of a step together, each prefixed with the field it belongs to. First the config:
targets[0].output[0].name: "Service" collides with the interface; set a prefix, a suffix or a name
targets[1].interface: required
Then, once the config is valid, your code. Interface problems name the method, and provider problems name the method and the type:
targets[0].interface: method Close must take no arguments and return one value
targets[1].interface: type "Cache" not found in package example.com/myapp/internal/cache
targets[0].output[0]: Logger(): no provider returns *slog.Logger
targets[0].output[0]: Logger(): *slog.Logger is provided by providers.ProvideLogger, other.ProvideLogger
tack # generate for every target in tack.yaml
tack -config path/to/tack.yamlRun tack from any directory inside your module. It walks up to find the nearest tack.yaml and stops
at the module root (go.mod). The tack.yaml must sit next to go.mod, because
every package path in it is relative to that directory.
tack only writes files that changed, and writes each one atomically. It refuses to overwrite or remove a
file that was not generated by tack (one that lacks the // Code generated by tack. DO NOT EDIT. first line),
and in that case it writes nothing at all.
A generated file that no longer compiles, such as one left stale after you changed the interface, does not stop tack from regenerating it.
A common setup is to run it from go generate:
//go:generate tack- Every interface method must take no arguments and return exactly one value.
- A type is matched exactly. A provider returning
*sql.DBdoes not satisfy a method returningsql.DBTX. - Within one layer, only one provider may return a given type. Use
provideron an output to pick one. - Providers must not be generic.
- The interface must not be generic. Name an instantiation instead:
type IntRepo = Repo[int]. - A test double reports a missing dependency only when its type can be
nil. - tack only writes the files the config names. If you remove an output, or change its
filenameorpackage, the file it generated before stays where it is: delete it yourself. The one exception is the test double of an output whosetestsetting you switch off. - An interface with an unexported method can only be implemented in its own package, so an output in another package is rejected.
go test -cover ./...| Package | Responsibility |
|---|---|
cmd/tack |
The command. Kept thin. |
internal/discover |
Finds tack.yaml. |
internal/config |
Parses and validates tack.yaml. |
internal/load |
Type-checks the packages and binds each interface method to a provider. |
internal/render |
Renders the bound outputs to Go source from embedded templates. |
internal/generate |
Runs the whole pipeline and writes the files safely. |