Skip to content
withnicPublic

About

Lightweight compile-time dependency injection code generator for Go, in the style of google/wire (with a wire-compatible mode).

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

knit

CI Go Reference OpenSSF Scorecard License: MIT

English | 日本語

knit is a lightweight, compile-time dependency injection code generator for Go, in the style of google/wire (now archived).

You list your constructors once; knit works out the order to call them in and writes plain, readable Go code that wires everything together, including cleanup functions and error handling. There is no reflection and no runtime container.

  • Native mode (default): declare injectors with knit.Build / knit.NewSet / knit.Bind. No dependency on google/wire.
  • wire mode (-mode=wire): a drop-in replacement for the wire command. It reads your existing wire.go files and writes the same wire_gen.go.
  • Dependency graph: every run also writes .knit/di-graph.json, a machine-readable record of what each injector depends on (for tooling such as test impact analysis).

Install

knit requires Go 1.26 or later.

# Command-line tool
go install github.com/withnic/knit/cmd/knit@latest

# Or pin it as a tool dependency of your module and run it with `go tool knit`
go get -tool github.com/withnic/knit/cmd/knit@latest

# Marker package used in your injector declarations (native mode)
go get github.com/withnic/knit@latest

Prebuilt binaries for Linux, macOS and Windows are attached to each GitHub release.

Quick start

1. Write ordinary constructors (providers).

package app

type Store interface{ Get() string }

type SQLStore struct{ /* ... */ }

func (s *SQLStore) Get() string { /* ... */ }

func NewDSN(ctx context.Context) DSN { /* ... */ }

// A provider may return a cleanup function and/or an error.
func NewSQLStore(dsn DSN) (*SQLStore, func(), error) { /* ... */ }

func NewServer(s Store) *Server { /* ... */ }

2. Declare an injector in a file guarded by the knitinject build tag (for example knit.go). The body is a single knit.Build call listing what the injector may use.

//go:build knitinject

package app

import (
	"context"

	"github.com/withnic/knit"
)

var StoreSet = knit.NewSet(NewDSN, NewSQLStore, knit.Bind(new(Store), new(*SQLStore)))

func InitializeServer(ctx context.Context) (*Server, func(), error) {
	panic(knit.Build(StoreSet, NewServer))
}

3. Generate.

knit gen ./...

knit writes knit_gen.go next to the declaration:

// Code generated by knit. DO NOT EDIT.

//go:build !knitinject

package app

import (
	"context"
)

// Injectors from knit.go:

func InitializeServer(ctx context.Context) (*Server, func(), error) {
	var cleanups []func()
	cleanup := func() {
		for i := len(cleanups) - 1; i >= 0; i-- {
			cleanups[i]()
		}
	}
	v1 := NewDSN(ctx)
	v2, cleanupV2, err := NewSQLStore(v1)
	if err != nil {
		return nil, nil, err
	}
	cleanups = append(cleanups, cleanupV2)
	v3 := NewServer(v2)
	return v3, cleanup, nil
}

4. Use it like any other function.

srv, cleanup, err := app.InitializeServer(ctx)
if err != nil {
	return err
}
defer cleanup()

Tip: add //go:generate go tool knit gen to a file in your module and regenerate with go generate ./....

Concepts

Declaration Meaning
Provider A top-level function returning (T), (T, error), (T, func()) or (T, func(), error). Its parameters are its dependencies.
knit.Build(...) Marks the enclosing function as an injector. Its parameters are inputs, its first result is the value to build, and it may also return func() and/or error.
knit.NewSet(...) Groups providers, other sets and bindings into a reusable package-level variable. Sets may be nested and may live in other packages.
knit.Bind(new(Iface), new(*Impl)) Satisfies requests for an interface with a concrete type that some provider builds.

If a provider fails, the cleanup functions of everything built so far run in reverse order (LIFO) before the error is returned.

Generated code is deterministic: the same input always produces byte-identical output. Errors explain the full dependency chain:

failed to resolve provider for injector 'InitializeUserService':
  service.UserService -> repo.UserRepository -> *db.Pool (provider not found)

Modes

The two modes differ only in the marker package, the build tag and the output file name. Each mode ignores the other's declarations.

knit (default) wire (-mode=wire)
Marker package github.com/withnic/knit github.com/google/wire
Declarations knit.Build / knit.NewSet / knit.Bind wire.Build / wire.NewSet / wire.Bind
Injector file tag //go:build knitinject //go:build wireinject
Generated file knit_gen.go wire_gen.go

Migrating from google/wire

Keep your code as is: run knit gen -mode=wire ./... wherever you ran wire. The output is a regular wire_gen.go.

Switch to native mode:

  1. Change the build tag of your injector files from wireinject to knitinject.
  2. Replace the import github.com/google/wire with github.com/withnic/knit, and wire. with knit..
  3. Delete the old wire_gen.go files, then run knit gen ./....
  4. Run go mod tidy to drop google/wire.

Not supported

knit deliberately supports a small subset of wire. These features are rejected with an error that suggests the alternative:

wire feature Use instead
wire.Struct An explicit NewXxx constructor
wire.Value, wire.InterfaceValue A one-line ProvideXxx function
wire.FieldsOf A one-line getter function
Variadic parameters (...T) An explicit slice type ([]T) or a dedicated provider
Method or generic providers and injectors A plain top-level function

Command reference

knit gen [flags] [packages...]   generate code and .knit/di-graph.json (packages default to ./...)
knit version                     print the version
Flag Default Description
-mode knit knit or wire
-out knit_gen.go / wire_gen.go Name of the generated file in each package directory
-graph-out .knit/di-graph.json Output path of the dependency graph; empty to skip
-dry-run false Print the generated code instead of writing files

Exit codes: 0 success, 1 analysis or generation error, 2 usage error.

Files whose content has not changed are not rewritten. The format of di-graph.json is described in docs/02_data_models.md (Japanese).

Contributing

Bug reports and pull requests are welcome. Development tasks run through the Makefile (make help lists them):

make check      # go.mod tidy, formatting, lint, unit tests
make test-all   # all tests including end-to-end tests

Design documents are in docs/ (Japanese).

License

MIT

About

Lightweight compile-time dependency injection code generator for Go, in the style of google/wire (with a wire-compatible mode).

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages