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 replacement for the wire command. It reads your existing wire.go files and writes wire_gen.go.

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 [1]func()
	cleanup := func() {
		for _, f := range cleanups {
			if f != nil {
				defer f()
			}
		}
	}
	v1 := NewDSN(ctx)
	v2, cleanupV2, err := NewSQLStore(v1)
	if err != nil {
		return nil, nil, err
	}
	cleanups[0] = 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.

Providers are called in dependency order, as in google/wire: starting from the injector's result, each provider's dependencies are built first, in the order of its parameters. Reorder a constructor's parameters to change the order of independent providers; their names do not matter.

If a provider fails, the cleanup functions of everything built so far run in reverse order (LIFO) before the error is returned. The cleanup returned by the injector also runs them in reverse order. A nil cleanup is skipped, and a cleanup that panics does not prevent the remaining ones from running.

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 injectors: run knit gen -mode=wire ./... wherever you ran wire. The output is a regular wire_gen.go. Unlike wire, knit does not copy other declarations from wire.go into the output, so move providers and anything your regular code uses to a file without the wireinject tag.

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
Providers declared in a file with the inject build tag Move them to a file without the tag
Unexported providers of another package Export the provider

Command reference

knit gen [flags] [packages...]   generate code (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
-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. knit refuses to overwrite an output file that is not marked as generated, and reports generated files left in packages that no longer declare injectors.

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