Help us shape the future of Go! Take the 2026 Go Developer Survey

project

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package project knows about the user's project: where its root is, what dbkit.json says, how to read and write the .env file, how to build a DSN from DB_* variables, and how to scaffold the db/ directory. It uses only the standard library.

Index

Constants

View Source
const (
	// ConfigFile is the project configuration file, kept in the project root.
	ConfigFile = "dbkit.json"
	// DefaultDir is where migrations, factories and seeders live.
	DefaultDir = "db"
	// DefaultEnvFile is the default environment file, relative to the root.
	DefaultEnvFile = ".env"
	// EnvVarEnvFile overrides the environment file path (set by the launcher
	// when it starts the project's runner).
	EnvVarEnvFile = "DBKIT_ENV_FILE"
	// LibraryPath is the import path of this library. Change it in forks.
	LibraryPath = "github.com/saeedjhn/dbkit"
)
View Source
const (
	EnvAppEnv   = "APP_ENV"
	EnvDriver   = "DB_DRIVER"
	EnvHost     = "DB_HOST"
	EnvPort     = "DB_PORT"
	EnvDatabase = "DB_DATABASE"
	EnvUsername = "DB_USERNAME"
	EnvPassword = "DB_PASSWORD"
	EnvSSLMode  = "DB_SSLMODE"
	EnvDSN      = "DB_DSN"
	EnvURL      = "DATABASE_URL"
)

Environment variable names.

Variables

EnvOrder is the order in which env:setup writes new variables.

View Source
var ErrNoProject = errors.New("not inside a Go project: no dbkit.json or go.mod found in this directory or any parent (run `go mod init` first, then `dbkit init`)")

ErrNoProject is returned when no project root can be found.

View Source
var SubDirs = []string{"migrations", "factories", "seeders"}

SubDirs are created inside the db directory.

Functions

func CanonicalDriver

func CanonicalDriver(d string) (string, error)

CanonicalDriver maps aliases to postgres, mysql or sqlite.

func EnsureGitignore

func EnsureGitignore(root string, entries ...string) (bool, error)

EnsureGitignore appends missing lines to root/.gitignore (creating it). It reports whether anything was added.

func ExtractFlag

func ExtractFlag(args []string, name string) (value string, rest []string)

ExtractFlag removes `--name value` or `--name=value` from args and returns the value (the last one wins) and the remaining arguments. It is used by the launcher for global flags that must not reach the project's runner.

func LoadEnvFile

func LoadEnvFile(path string)

LoadEnvFile copies the file's variables into the process environment. Variables that are already set are NOT overwritten, so real environment values (CI, server) win. A missing file is not an error.

func MaskDSN

func MaskDSN(dsn string) string

MaskDSN hides the password in a DSN, for printing.

func ModulePath

func ModulePath(root string) (string, error)

ModulePath returns the module path declared in root/go.mod.

func ParseEnv

func ParseEnv(r io.Reader) (map[string]string, error)

ParseEnv reads KEY=VALUE pairs.

func ReadEnvFile

func ReadEnvFile(path string) (vars map[string]string, exists bool, err error)

ReadEnvFile reads an environment file. A missing file yields an empty map and exists=false.

func RequiresLibrary

func RequiresLibrary(root string) bool

RequiresLibrary reports whether root/go.mod already requires dbkit.

func ResolveEnvFile

func ResolveEnvFile(root string, cfg Config, flagValue string) string

ResolveEnvFile returns the absolute path of the environment file. Precedence: flag value, DBKIT_ENV_FILE, dbkit.json, ".env". Flag and environment values are relative to the current directory; the config value is relative to the project root.

func RunnerArgs

func RunnerArgs(dir string, args []string) []string

RunnerArgs builds the `go run` arguments that start the project's runner.

func SaveConfig

func SaveConfig(root string, c Config) error

SaveConfig writes dbkit.json.

func SetupEnv

func SetupEnv(p *Prompter, current, given map[string]string) (map[string]string, error)

SetupEnv asks for the database settings and returns the variables to write. `given` holds answers already supplied by flags (never asked again); `current` holds the existing file's values (used as defaults).

func UpdateEnvFile

func UpdateEnvFile(path string, kv map[string]string, order []string) error

UpdateEnvFile sets the given keys in the file, keeping every other line (comments, unrelated variables) untouched. Missing keys are appended in `order` (then alphabetically). The file is created with mode 0600.

func ValidateDir

func ValidateDir(dir string) error

ValidateDir checks that dir is a clean, relative, forward-slash path without "..", so it can be used both on disk and in an import path.

func WriteRunner

func WriteRunner(root, module, dir string) error

WriteRunner (re)writes <dir>/main.go.

Types

type Config

type Config struct {
	// Dir holds migrations/, factories/ and seeders/ (relative to the root).
	Dir string `json:"dir"`
	// EnvFile is the environment file (relative to the root, or absolute).
	EnvFile string `json:"envFile"`
}

Config is the content of dbkit.json.

func LoadConfig

func LoadConfig(root string) (Config, error)

LoadConfig reads dbkit.json from root. A missing file yields the defaults.

func MoveDir

func MoveDir(root string, cfg Config, newDir string) (Config, error)

MoveDir moves the db directory to newDir, regenerates the runner and updates dbkit.json.

func (Config) WithDefaults

func (c Config) WithDefaults() Config

WithDefaults fills empty fields.

type DBConfig

type DBConfig struct {
	Driver, Host, Port, Database, Username, Password, SSLMode string
	// DSN, when set (DB_DSN or DATABASE_URL), wins over the split fields.
	DSN string
}

DBConfig is the database configuration as read from DB_* variables.

func DBConfigFromEnv

func DBConfigFromEnv(get func(string) string) DBConfig

DBConfigFromEnv reads the DB_* variables through get (os.Getenv or a map).

func (DBConfig) HasConnectionParts

func (c DBConfig) HasConnectionParts() bool

HasConnectionParts reports whether any split field (besides the driver) is set.

func (DBConfig) Resolve

func (c DBConfig) Resolve() (driver, dsn string, err error)

Resolve returns the canonical driver name and the DSN.

type InitOptions

type InitOptions struct {
	Root    string // project root (must contain go.mod)
	Dir     string // default "db"
	EnvFile string // default ".env"
	Force   bool   // overwrite the runner (<dir>/main.go) if it exists
}

InitOptions configure Init.

type InitResult

type InitResult struct {
	Created []string
	Skipped []string
	Module  string
	Config  Config
}

InitResult lists what happened, as paths relative to the root.

func Init

func Init(o InitOptions) (InitResult, error)

Init scaffolds the db directory, the runner, dbkit.json and .env.example, and makes sure the env file is git-ignored. It never overwrites existing files unless Force is set (and then only the runner).

type Prompter

type Prompter struct {
	In          *bufio.Reader
	Out         io.Writer
	Interactive bool
	// ReadPassword reads a hidden line (the launcher plugs in x/term). When
	// nil the password is read as a normal visible line.
	ReadPassword func() (string, error)
}

Prompter asks questions on a terminal. When Interactive is false it never blocks: every question returns its default (used for CI and --yes).

func NewPrompter

func NewPrompter(in io.Reader, out io.Writer) *Prompter

NewPrompter creates an interactive prompter.

func (*Prompter) Ask

func (p *Prompter) Ask(question, def string) (string, error)

Ask asks a free-text question. An empty answer returns def.

func (*Prompter) Choose

func (p *Prompter) Choose(question string, options []string, def string) (string, error)

Choose asks the user to pick one of options (by name or number).

func (*Prompter) Confirm

func (p *Prompter) Confirm(question string, def bool) (bool, error)

Confirm asks a yes/no question.

func (*Prompter) Secret

func (p *Prompter) Secret(question string) (string, error)

Secret asks for a password without echo (when ReadPassword is set).

type Root

type Root struct {
	Path      string // absolute path of the project root
	HasConfig bool   // dbkit.json exists there
}

Root is a located project.

func FindRoot

func FindRoot(start string) (Root, error)

FindRoot walks up from start. A directory containing dbkit.json wins; otherwise the nearest directory containing go.mod is used.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL