Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ require github.com/spf13/cobra v1.10.2

require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/spf13/pflag v1.0.9 // indirect
)
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
Expand Down
2 changes: 2 additions & 0 deletions internal/app/bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ func NewDefaultRegistry() (*command.Registry, error) {
command.NewNewCommand(),
command.NewGenerateCommand(),
command.NewDestroyCommand(),
command.NewDBCreateCommand(),
command.NewDBDropCommand(),
} {
if err := reg.Register(cmd); err != nil {
return nil, err
Expand Down
16 changes: 16 additions & 0 deletions internal/app/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,22 @@ func (e *Executor) executeOp(ctx context.Context, op plan.Operation, flags comma
}

return Entry{Status: "ERROR", Message: fmt.Sprintf("%s is non-empty", op.Path)}, conflictError{message: fmt.Sprintf("conflict: target directory %s is non-empty (use --force)", op.Path)}
case plan.OpEnsureExists:
exists, err := e.fs.Exists(op.Path)

if err != nil {
return Entry{Status: "ERROR", Message: fmt.Sprintf("CHECK %s", op.Path)}, err
}

if !exists {
msg := op.Message
if msg == "" {
msg = fmt.Sprintf("required path %s not found", op.Path)
}
return Entry{Status: "ERROR", Message: msg}, conflictError{message: msg}
}

return Entry{Status: "INFO", Message: fmt.Sprintf("found %s", op.Path)}, nil
case plan.OpMkdir:
perm := op.Perm
if perm == 0 {
Expand Down
15 changes: 13 additions & 2 deletions internal/cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ func newRootCommand(executor *app.Executor, registry *command.Registry, stdout,
module := ""
skipGit := false
skipTidy := false
dsn := ""
env := ""

cobraCmd := &cobra.Command{
Use: spec.Use,
Expand All @@ -82,10 +84,14 @@ func newRootCommand(executor *app.Executor, registry *command.Registry, stdout,
RunE: func(c *cobra.Command, args []string) error {
params := map[string]string{}

if spec.ID == "new" {
switch spec.ID {
case "new":
params["module"] = module
params["skip-git"] = fmt.Sprintf("%t", skipGit)
params["skip-tidy"] = fmt.Sprintf("%t", skipTidy)
case "db:create", "db:drop":
params["dsn"] = dsn
params["env"] = env
}

input := command.Input{
Expand All @@ -110,11 +116,16 @@ func newRootCommand(executor *app.Executor, registry *command.Registry, stdout,
},
}

if spec.ID == "new" {
switch spec.ID {
case "new":
cobraCmd.Flags().StringVar(&module, "module", "", "Explicit Go module path")
cobraCmd.Flags().BoolVar(&skipGit, "skip-git", false, "Skip git init")
cobraCmd.Flags().BoolVar(&skipTidy, "skip-tidy", false, "Skip go mod tidy")
case "db:create", "db:drop":
cobraCmd.Flags().StringVar(&dsn, "dsn", "", "Database connection string")
cobraCmd.Flags().StringVar(&env, "env", "", "Environment to use")
}

root.AddCommand(cobraCmd)
}

Expand Down
37 changes: 37 additions & 0 deletions internal/domain/command/builtin.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package command
import (
"context"

"goforge/internal/domain/db"
"goforge/internal/domain/generate/newapp"
"goforge/internal/domain/plan"
)
Expand Down Expand Up @@ -66,3 +67,39 @@ func NewDestroyCommand() Command {

return NewStatic(spec, nil, planner)
}

func NewDBCreateCommand() Command {
spec := Spec{
ID: "db:create",
Use: "db:create",
Short: "Create database",
}

validate := func(input Input) error {
return db.ValidateCreate(input.Args, input)
}

planner := func(ctx context.Context, input Input) (plan.Plan, error) {
return db.PlanCreate(ctx, input.Args, input)
}

return NewStatic(spec, validate, planner)
}

func NewDBDropCommand() Command {
spec := Spec{
ID: "db:drop",
Use: "db:drop",
Short: "Drop database",
}

validate := func(input Input) error {
return db.ValidateDrop(input.Args, input)
}

planner := func(ctx context.Context, input Input) (plan.Plan, error) {
return db.PlanDrop(ctx, input.Args, input)
}

return NewStatic(spec, validate, planner)
}
97 changes: 97 additions & 0 deletions internal/domain/db/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package db

import (
"fmt"
"goforge/internal/domain/params"
"net/url"
"os"
"path"
"path/filepath"
"strings"

"github.com/pelletier/go-toml/v2"
)

type Config struct {
DSN string `json:"dsn"`
AdminDSN string
DatabaseName string
Skip bool
Force bool
}

func ParseConfig(p params.Params) (Config, error) {
dsn := strings.TrimSpace(p.Param("dsn"))

if dsn == "" {
env := strings.TrimSpace(p.Param("env"))

if env == "" {
env = "development"
}

fileDSN, err := loadDSNFromConfig(env)

if err != nil {
return Config{}, err
}

dsn = fileDSN
}

u, err := url.Parse(dsn)

if err != nil {
return Config{}, fmt.Errorf("invalid DSN: %w", err)
}

if u.Scheme != "postgres" && u.Scheme != "postgresql" {
return Config{}, fmt.Errorf("unsupported DSN scheme %q (only postgres/postgresql supported)", u.Scheme)
}

dbName := strings.TrimPrefix(path.Clean(u.Path), "/")
if dbName == "" || dbName == "." {
return Config{}, fmt.Errorf("dsn must include target database name in path")
}

adminURL := *u
adminURL.Path = "/postgres"

return Config{
DSN: dsn,
AdminDSN: adminURL.String(),
Skip: p.BoolParam("skip"),
Force: p.BoolParam("force"),
DatabaseName: dbName,
}, nil
}

func loadDSNFromConfig(env string) (string, error) {
configPath := filepath.Join("config", "database.toml")

data, err := os.ReadFile(configPath)

if err != nil {
return "", err
}

var configByEnv map[string]Config

if err := toml.Unmarshal(data, &configByEnv); err != nil {
return "", err
}

dbConfig, ok := configByEnv[env]

if !ok {
return "", fmt.Errorf("no database config found for env %s", env)
}

dsn := dbConfig.DSN

if dsn == "" {
return "", fmt.Errorf("no database DSN found for env %s", env)
}

return dsn, nil
}
70 changes: 70 additions & 0 deletions internal/domain/db/planner.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package db

import (
"context"
"fmt"
"goforge/internal/domain/params"
"goforge/internal/domain/plan"
)

func ValidateCreate(args []string, p params.Params) error {
if len(args) != 0 {
return fmt.Errorf("db:create does not accept positional arguments")
}

_, err := ParseConfig(p)

return err
}

func ValidateDrop(args []string, p params.Params) error {
if len(args) != 0 {
return fmt.Errorf("db:create does not accept positional arguments")
}

_, err := ParseConfig(p)

return err
}

func PlanCreate(_ context.Context, _ []string, p params.Params) (plan.Plan, error) {
cfg, err := ParseConfig(p)

if err != nil {
return plan.Plan{}, err
}

ops := []plan.Operation{
{Type: plan.OpEnsureExists, Path: "config/database.toml", Message: "missing config/database.toml"},
}

create := fmt.Sprintf("CREATE DATABASE \"%s\";", cfg.DatabaseName)
ops = append(ops, plan.Operation{Type: plan.OpRun, Cmd: []string{"psql", cfg.AdminDSN, "-v", "ON_ERROR_STOP=1", "-c", create}})

return plan.Plan{
CommandID: "db:create",
Description: "Create database",
Ops: ops,
}, nil
}

func PlanDrop(ctx context.Context, args []string, p params.Params) (plan.Plan, error) {
cfg, err := ParseConfig(p)

if err != nil {
return plan.Plan{}, err
}

ops := []plan.Operation{
{Type: plan.OpEnsureExists, Path: "config/database.toml", Message: "missing config/database.toml"},
}

drop := fmt.Sprintf("DROP DATABASE IF EXISTS \"%s\";", cfg.DatabaseName)
ops = append(ops, plan.Operation{Type: plan.OpRun, Cmd: []string{"psql", cfg.AdminDSN, "-v", "ON_ERROR_STOP=1", "-c", drop}})

return plan.Plan{
CommandID: "db:drop",
Description: "Drop database",
Ops: ops,
}, nil
}
Loading
Loading