generate

package
v0.1.12 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Overview

gen_endpoint.go — `gofasta g endpoint <Resource> <METHOD> <path> [--handler=<name>]`

Adds a single REST endpoint to an existing resource. Patches:

  • app/rest/controllers/<snake>.controller.go — handler method on the controller
  • app/rest/routes/<snake>.routes.go — route registration line
  • app/services/interfaces/<snake>_service.go — service method (unless --no-service)

The handler is wired through gofasta's httputil.Handle adapter so the generated method has the same shape as scaffold-produced handlers. Method names are auto-derived from "<METHOD> /path" when --handler is omitted (e.g. `POST /orders/{id}/archive` → `ArchiveOrder`).

gen_field.go — `gofasta g field <Resource> <name>:<type>`

Adds a single field across the four places that always need to move together for a "just one more column" change:

  1. db/migrations/NNNNNN_add_<field>_to_<plural>.up.sql / .down.sql
  2. app/models/<snake>.model.go (field on the model struct + GORM tag)
  3. (optional) app/dtos/<snake>.dtos.go (Request + Update + Response)

Each downstream surface is opt-out via flags so the user can add a model-only column (--no-dto), a response-only field (--no-update --no-create), etc.

gen_method.go — `gofasta g method <Resource> <Method> [param:type ...]`

Adds a method to an existing service:

  • appends the signature to app/services/interfaces/<snake>_service.go
  • appends an impl stub to app/services/<snake>.service.go

Uses astpatch (dst-based) so the existing file's formatting + comments are preserved through the modify → write-back round trip — no marker comments left behind in user-edited service files.

gen_middleware.go — `gofasta g middleware <METHOD> <path> <middleware-ref>`

Wraps an existing route's handler with a chi middleware. Discovers the route via regex (matches `r.<Verb>("<path>", ...)`), then rewrites the surrounding `.Method(...)` call into `.With(<middleware>).<Method>(...)`. Idempotent — re-running on a route that already includes the same middleware is a no-op.

gen_mock.go — testify/mock generator. Walks Go source for interface declarations, builds a method-by-method mock that satisfies the interface, and writes it to testutil/mocks/<snake>_mock.go.

Two modes:

gofasta g mock <InterfaceName>   — find one interface by exact name
gofasta g mock --all             — refresh every mock under
                                   app/services/interfaces and
                                   app/repositories/interfaces

The generator is purely additive — it never modifies non-mock files. File overwrite of testutil/mocks/<...>_mock.go IS the expected behavior (mocks are derived artifacts); use --check to flag drift without rewriting (suitable for CI).

gen_relation.go — `gofasta g relation <Resource> belongs_to|has_many|has_one <Other>`

Adds an association between two resources:

  • belongs_to <Other> → model gains <Other>ID + *<Other>; FK column added to <Resource>'s table via migration.
  • has_many <Other> → model gains []<Other>; no schema change on <Resource> itself — the FK lives on <Other>'s table (a sibling g relation belongs_to call on <Other> handles that side).
  • has_one <Other> → model gains *<Other>; FK lives on <Other>.

We never assume both sides of the relation need patching — that's a product decision (the user may have a one-way navigation property). Run `g relation` twice, once per side, when bidirectional navigation is desired.

gen_rename.go — `gofasta g rename <Resource>.<OldField> <NewField> [--apply]`

Renames a single field across every place gofasta's layered scaffold touches it:

  • app/models/<snake>.model.go — struct field + GORM column tag
  • app/dtos/<snake>.dtos.go — every DTO that uses the field
  • app/services/<snake>.service.go — receiver-method field references
  • db/migrations/NNNNNN_rename_<old>_to_<new>_on_<plural>.up.sql/.down.sql

Conservative by design — runs in *preview* mode by default so the user can confirm the diff before any disk write. Pass --apply to commit the changes. This keeps the rename safe: cross-file string surgery is inherently risky and the user should see exactly what's about to land.

The substitution is *token-aware* (regex with word boundaries) so we don't accidentally rewrite "Total" inside "TotalCount". The match key is the PascalCase struct-field form; underlying GORM tags and JSON names are rewritten via dedicated rules.

gen_repo_method.go — `gofasta g repo-method <Resource> <Method> [param:type ...]`

The repository-layer twin of `g method`. Same astpatch pattern, different default paths: targets

  • app/repositories/interfaces/<snake>_repository.go
  • app/repositories/<snake>.repository.go

gofasta's scaffold names repository interfaces "<Name>RepositoryInterface" (see internal/generate/templates/repo_interface.go) — we match that convention by default.

stringutil.go — thin delegates over internal/naming, the single source of truth for name derivation. Kept as package-local function names so the many call sites across the generators read naturally.

Index

Constants

This section is empty.

Variables

View Source
var Cmd = &cobra.Command{
	Use:     "generate",
	Short:   "Scaffold resources, models, DTOs, controllers, jobs, and tasks",
	Aliases: []string{"g"},
	Long: `Code generators for every layer of a gofasta project. Every generator
renders from embedded Go templates, writes files under the conventional
paths (app/models/, app/repositories/, app/services/, app/dtos/,
app/rest/controllers/, app/rest/routes/, app/di/providers/, db/migrations/,
app/jobs/, app/tasks/, app/graphql/, templates/emails/), and patches the
dependency-injection container, wire.go, route config, and serve.go so the
new code is wired automatically.

Field syntax is ` + "`name:type`" + `. Supported types: string, text, int, float,
bool, uuid, time. The underlying SQL type is chosen based on the database
driver in config.yaml (postgres, mysql, sqlite, sqlserver, clickhouse).

Generators, by layer:

  scaffold        model + migration + repo + service + DTOs + provider +
                  controller + routes + full auto-wire (optionally GraphQL)
  model           model struct + matching up/down migration
  migration       standalone up/down migration files
  repository      model + migration + repo interface + impl
  service         repo stack + service interface + impl + DTOs + provider
  controller      service stack + REST controller + route file + wiring
  dto             DTO file only
  route           route file only (assumes controller exists)
  provider        Wire provider + container + wire.go patches
  resolver        add a service dependency to an existing GraphQL resolver
  job             cron job file + scheduler registration + schedule config
  task            async task handler wired into the asynq queue
  email-template  HTML email template under templates/emails/

After scaffolding, generators that affect wiring automatically run
` + "`go tool wire`" + ` (and ` + "`go tool gqlgen`" + ` for --graphql) so the project compiles
without manual intervention.`,
}

Cmd is the parent "generate" command, registered on rootCmd by the thin stub.

View Source
var WireCmd = &cobra.Command{
	Use:   "wire",
	Short: "Regenerate Google Wire dependency injection code",
	Long: `Run ` + "`go tool wire ./app/di/`" + ` to regenerate wire_gen.go from the current
provider set. Use this after manually editing app/di/wire.go or a provider
file — ` + "`gofasta g`" + ` commands already run this automatically as their last
step, so you only need it after hand edits.`,
	RunE: func(cmd *cobra.Command, args []string) error {
		return RunWire(ScaffoldData{})
	},
}

WireCmd is a standalone command to regenerate Wire DI code.

Functions

func AutoVerify added in v0.1.9

func AutoVerify() error

AutoVerify runs `go build ./...` in the project root to confirm the just-generated code compiles. Intended as a post-hook after a generator that produces a full compilable unit (scaffold, service, controller). Kept small and shell-based so it is cheap to run; callers that need the full preflight gauntlet should invoke `gofasta verify` instead.

When the build succeeds, returns nil silently. When it fails, returns a structured clierr.Error whose Hint points at common causes agents can act on programmatically (template regression, missing Wire rerun, outdated deps).

func GenController

func GenController(d ScaffoldData) error

GenController writes a REST controller file for the scaffolded resource.

func GenControllerTestFile added in v0.1.9

func GenControllerTestFile(d ScaffoldData) error

GenControllerTestFile writes a starter _test.go file alongside the generated controller. The file compiles out of the box (so the scaffold's post-gen `go build` / `go test` passes) and contains smoke tests plus a skipped TODO placeholder. Developers and AI agents fill in real behavior tests on top of the stubs.

Separate from GenController so callers can include or exclude it — we currently add it to every flow that produces a controller.

func GenDTOs

func GenDTOs(d ScaffoldData) error

GenDTOs writes DTO structs for the scaffolded resource.

func GenDTOsTestFile added in v0.1.11

func GenDTOsTestFile(d ScaffoldData) error

GenDTOsTestFile writes the executable DTO mapper test alongside every generated DTOs file. Tests are real assertions, not TODO stubs — see templates.DTOsTest for the contract.

func GenEmailTemplate

func GenEmailTemplate(d ScaffoldData) error

GenEmailTemplate generates an HTML email template file in templates/emails/. Unlike other generators, this writes raw HTML (not Go-template-executed) because the output itself contains Go template directives for the email renderer.

func GenEndpoint added in v0.1.11

func GenEndpoint(d EndpointData) error

GenEndpoint is the entry point invoked by the Cobra command.

func GenErrors added in v0.1.11

func GenErrors(d ScaffoldData) error

GenErrors writes the per-resource sentinel-errors file for the scaffolded resource. Path is layout-dependent — layered puts it under app/services/, feature puts it under app/<resource>/.

func GenField added in v0.1.11

func GenField(d FieldData) error

GenField is the entry point invoked by the Cobra command.

func GenGraphQL

func GenGraphQL(d ScaffoldData) error

GenGraphQL writes a GraphQL schema fragment for the scaffolded resource.

func GenInputs added in v0.1.11

func GenInputs(d ScaffoldData) error

GenInputs writes the per-resource domain-inputs file for the scaffolded resource. Contains CreateXInput, UpdateXPatch (with AsMap), and ListXFilter. Path is layout-dependent.

func GenInputsTestFile added in v0.1.11

func GenInputsTestFile(d ScaffoldData) error

GenInputsTestFile writes the executable inputs test alongside every generated inputs file (AsMap negative-space + AsRepoFilter empty-map).

func GenJob

func GenJob(d ScaffoldData) error

GenJob generates a cron job file in app/jobs/ AND a sibling _test.go with executable behavior tests (Name(), Run happy path, Run respects ctx cancellation).

func GenMethod added in v0.1.11

func GenMethod(d MethodData) error

GenMethod is the entry point invoked by the Cobra command.

func GenMiddleware added in v0.1.11

func GenMiddleware(d MiddlewareData) error

GenMiddleware is the entry point invoked by the Cobra command.

func GenMigration

func GenMigration(d ScaffoldData) error

GenMigration writes up + down SQL migration files for the scaffolded resource.

func GenMock added in v0.1.11

func GenMock(interfaceName string, opts GenMockOpts) error

GenMock is the main entry point. Resolves the interface (or every interface in --all mode), then writes / checks the mock file(s).

func GenModel

func GenModel(d ScaffoldData) error

GenModel writes a GORM model file for the scaffolded resource.

func GenRelation added in v0.1.11

func GenRelation(d RelationData) error

GenRelation is the entry point invoked by the Cobra command.

func GenRename added in v0.1.11

func GenRename(d RenameData) error

GenRename is the entry point invoked by the Cobra command.

func GenRepo

func GenRepo(d ScaffoldData) error

GenRepo writes the repository implementation file for the scaffolded resource.

func GenRepoInterface

func GenRepoInterface(d ScaffoldData) error

GenRepoInterface writes the repository interface file for the scaffolded resource.

func GenRepoMethod added in v0.1.11

func GenRepoMethod(d MethodData) error

GenRepoMethod is a thin wrapper that fills in repo-specific defaults and delegates to the shared GenMethod implementation. Keeping it as a separate entry point makes the CLI command surface explicit even though the implementation is identical.

func GenRepoTestFile added in v0.1.11

func GenRepoTestFile(d ScaffoldData) error

GenRepoTestFile writes the testcontainers-backed repository test alongside every generated repo. Covers FindByID, Create, UpdateIfVersionMatches (incl. atomicity-under-race), SoftDeleteIfDeletable, List pagination.

func GenResolver

func GenResolver(d ScaffoldData) error

GenResolver patches the GraphQL resolver to add a new service dependency.

func GenResolverFile added in v0.1.11

func GenResolverFile(d ScaffoldData) error

GenResolverFile writes a fully-implemented per-resource resolver file at app/graphql/resolvers/<snake>.resolvers.go.

Runs right after GenGraphQL (the schema fragment) and BEFORE RunGqlgen: gqlgen's follow-schema layout maps the fragment 1:1 to this file and preserves any method bodies it finds, so pre-writing the implementations is what prevents gqlgen's stock panic("not implemented") stubs from ever landing in the project.

WriteTemplate skips existing files, so re-running a generator never clobbers user edits. The template itself branches on layout — the file path is the same in both layouts (gqlgen owns the resolvers dir) but the symbol qualifiers differ; WriteTemplate's auto-featurize gate only covers app/<snake>/ paths, so it does not apply here.

func GenRoutes

func GenRoutes(d ScaffoldData) error

GenRoutes writes the route-registration file for the scaffolded resource.

func GenSvc

func GenSvc(d ScaffoldData) error

GenSvc writes the service implementation file for the scaffolded resource.

func GenSvcInterface

func GenSvcInterface(d ScaffoldData) error

GenSvcInterface writes the service interface file for the scaffolded resource.

func GenSvcTestFile added in v0.1.11

func GenSvcTestFile(d ScaffoldData) error

GenSvcTestFile writes the executable service test alongside every generated service file. Inline mock repository; covers Get, Update, Archive sentinel paths + happy paths.

func GenTask

func GenTask(d ScaffoldData) error

GenTask generates an async task handler file in app/tasks/ AND a sibling _test.go with executable behavior tests (Handle valid + invalid payloads; Enqueue round-trips through a captured queue).

func GenWireProvider

func GenWireProvider(d ScaffoldData) error

GenWireProvider writes a Wire provider file for the scaffolded resource. Layered puts it under app/di/providers/; feature puts it inside the per-resource directory at app/<resource>/wire.go.

func GeneratorMarkers added in v0.1.11

func GeneratorMarkers() map[string][]string

GeneratorMarkers maps project files to the scaffold marker comments the `gofasta g` patchers anchor on. The refactor preflight consumes this to warn when a marker was removed: the refactor itself succeeds without them (its transforms are AST-anchored), but every future `gofasta g scaffold` on the project would fail to patch that file.

func GetDryRun added in v0.1.9

func GetDryRun() bool

GetDryRun reports whether dry-run mode is currently active.

func PatchContainer

func PatchContainer(d ScaffoldData) error

PatchContainer adds repo/service/controller fields to app/di/container.go. Field type qualifiers depend on the project layout — in layered mode the fields reference repoInterfaces/svcInterfaces/controllers, in feature mode they reference the per-feature package alias.

func PatchGqlgenAutobind added in v0.1.11

func PatchGqlgenAutobind(d ScaffoldData) error

PatchGqlgenAutobind adds the new resource's feature package to gqlgen.yml's autobind list, so gqlgen binds the schema types against the hand-written DTOs in app/<snake>/ instead of regenerating duplicates. Feature layout only — the layered autobind entry (<mod>/app/dtos) already covers every resource's DTOs.

func PatchJobConfig

func PatchJobConfig(d ScaffoldData) error

PatchJobConfig adds the job schedule to config.yaml.

func PatchJobRegistry

func PatchJobRegistry(d ScaffoldData) error

PatchJobRegistry adds the new job to the registry in cmd/serve.go.

func PatchResolver

func PatchResolver(d ScaffoldData) error

PatchResolver adds a service field and constructor param to app/graphql/resolvers/resolver.go. The service-interface qualifier depends on the project layout — in layered mode the interface lives in svcInterfaces, in feature mode it lives in the per-feature package (referenced via `<snake>pkg`), same branching as PatchContainer / PatchWireFile.

func PatchRouteConfig

func PatchRouteConfig(d ScaffoldData) error

PatchRouteConfig adds controller to RouteConfig and registers routes in app/rest/routes/index.routes.go.

func PatchServeFile

func PatchServeFile(d ScaffoldData) error

PatchServeFile adds the controller to RouteConfig initialization in cmd/serve.go.

func PatchWireFile

func PatchWireFile(d ScaffoldData) error

PatchWireFile adds the provider set to wire.Build in app/di/wire.go. Provider reference depends on layout: `providers.<Name>Set` in layered, `<snake>pkg.<Name>Set` in feature.

func PrintPlanText added in v0.1.9

func PrintPlanText(w io.Writer)

PrintPlanText writes a human-friendly summary of the recorded plan to w. Used by dry-run subcommands for the default (non-JSON) output.

func RunGqlgen

func RunGqlgen(_ ScaffoldData) error

RunGqlgen regenerates the GraphQL code from schema files.

func RunSteps

func RunSteps(d ScaffoldData, steps []Step) error

RunSteps executes a sequence of steps, stopping at the first error.

func RunWire

func RunWire(_ ScaffoldData) error

RunWire regenerates the Wire dependency injection code.

func ScaffoldPlan added in v0.1.11

func ScaffoldPlan(l layout.Layout, includeGraphQL bool) (created, patched []string)

ScaffoldPlan reports which files `g scaffold` creates and patches for a layout, without touching disk. It MUST stay in lockstep with scaffoldSteps — TestScaffoldPlan_MatchesScaffoldSteps enforces the 1:1 mapping, so a new step added there without a path here fails `go test`. `gofasta facts` publishes these lists; documentation tables are generated from them.

func SetDryRun added in v0.1.9

func SetDryRun(enabled bool)

SetDryRun turns plan-only mode on or off. When on, every filesystem write in the generate package is recorded instead of executed; when off, the package operates normally.

func WriteTemplate

func WriteTemplate(path, name, tmpl string, data ScaffoldData) error

WriteTemplate renders a Go template and writes it to path. Skips when the file already exists. In dry-run mode (see planner.go) the render still happens — so template errors surface identically — but the file is recorded in the plan instead of written to disk.

When the project's layout is feature, the rendered Go source is piped through featurize so per-resource symbols collapse and the package decl matches the destination directory. Non-.go paths (SQL migrations, .gql schemas, HTML email templates) pass through unchanged because featurize only operates on parseable Go source.

Types

type EndpointData added in v0.1.11

type EndpointData struct {
	Resource    string // PascalCase ("Order")
	Snake       string // snake_case ("order")
	HTTPMethod  string // "GET" | "POST" | "PUT" | "DELETE" | "PATCH"
	Path        string // chi-style path with optional placeholders, e.g. "/orders/{id}/archive"
	HandlerName string // PascalCase ("ArchiveOrder"). Auto-derived when empty.
	WithService bool   // also append a matching method to the service interface + impl

	ControllerFile  string
	RoutesFile      string
	ServiceFile     string // the interface file
	ServiceImplFile string // the impl file gaining the stub
}

EndpointData is the resolved input for the endpoint generator.

type Field

type Field struct {
	Name      string // PascalCase: ProductName
	JSONName  string // camelCase: productName
	SnakeName string // snake_case: product_name
	GoType    string // Go type: string
	GormType  string // GORM tag: gorm:"not null"
	GQLType   string // GraphQL type: String
	SQLType   string // SQL type (generic): VARCHAR(255) NOT NULL
	// Per-driver SQL types (populated by field parser based on DBDriver)
	SQLTypePostgres   string
	SQLTypeMySQL      string
	SQLTypeSQLite     string
	SQLTypeSQLServer  string
	SQLTypeClickHouse string
}

Field represents a single field in a resource (parsed from "name:type" CLI args).

func ParseFields

func ParseFields(args []string) []Field

ParseFields converts CLI args like "name:string price:float" into typed Fields.

func (Field) SampleJSON added in v0.1.11

func (f Field) SampleJSON() string

SampleJSON returns a JSON literal for this field's type, used by the generated controller tests to build request bodies that survive the pointer-field Create DTO (a `{}` body would leave every required pointer nil, and ToCreateInput's deref would panic once the noop validator lets it through).

func (Field) SampleLiteral added in v0.1.11

func (f Field) SampleLiteral() string

SampleLiteral returns a Go literal suitable as a test-fixture value for this field's type. Used by the generated test templates so fixtures exercise real column values instead of leaving a TODO. uuid/time literals assume the rendering template already imports github.com/google/uuid and time (repotest and svctest both do).

type FieldData added in v0.1.11

type FieldData struct {
	Resource           string // PascalCase ("Order")
	LowerName          string // camelCase ("order", "apiKey") — allowlist var prefix
	Snake              string // snake_case ("order")
	PluralSnake        string // snake_case plural ("orders")
	PluralName         string // PascalCase plural ("Orders") — List<Plural>Filter
	Field              Field  // parsed name:type with GORM + SQL tags resolved
	WithDTO            bool   // include DTO/inputs/allowlist/SDL patches (default true)
	WithCreate         bool   // include TCreate<R>Dto + Create<R>Input (default true)
	WithUpdate         bool   // include TUpdate<R>Dto/GraphQLInput + Update<R>Patch (default true)
	WithResponse       bool   // include the <R> response DTO + FromModel (default true)
	ModelFile          string
	DTOFile            string
	InputsFile         string
	SvcFile            string
	RepoFile           string
	RepoTestFile       string
	ControllerTestFile string
	SchemaFile         string // app/graphql/schema/<snake>.gql (empty file = no GraphQL)
	MigrationDir       string
	MigrationVer       string // 6-digit version prefix; computed by default
	DBDriver           string
}

FieldData is the resolved input for the field generator.

type FieldType added in v0.1.11

type FieldType struct {
	Key     string   // canonical spelling used in "name:type" args
	Aliases []string // accepted alternative spellings
	GoType  string
	// GormType is the full struct-tag literal (backquoted in templates).
	GormType          string
	GQLType           string
	SQLTypePostgres   string
	SQLTypeMySQL      string
	SQLTypeSQLite     string
	SQLTypeSQLServer  string
	SQLTypeClickHouse string
}

FieldType describes one supported "name:type" field kind: the Go/GORM/ GraphQL representations plus the column type for every supported SQL driver. The registry below is the single source of truth for supported types — ParseFields resolves against it, and `gofasta facts` exposes it so documentation tables can be generated instead of hand-maintained.

func SupportedFieldTypes added in v0.1.11

func SupportedFieldTypes() []FieldType

SupportedFieldTypes returns the registry in display order. The slice is a copy so callers cannot mutate the source of truth.

type GenMockOpts added in v0.1.11

type GenMockOpts struct {
	// Check, when true, doesn't write — it returns CodeMockDrift if the
	// generated content differs from the on-disk file.
	Check bool
	// All, when true, walks both interface dirs and regenerates every
	// mock. Interface argument is ignored.
	All bool
}

GenMockOpts tweaks generator behavior at runtime.

type MethodData added in v0.1.11

type MethodData struct {
	Resource   string  // PascalCase ("Order")
	Snake      string  // snake_case ("order")
	MethodName string  // PascalCase ("Archive")
	Args       []Field // parsed name:type pairs (may be empty)
	// InterfaceName is "<Resource>Service" by default; callers can pass a
	// different interface (e.g. "OrderRepository" for g repo-method).
	InterfaceName string
	// ImplStructName is the receiver type for the impl file; default is
	// the lowercase of Resource + "Service" (e.g. "orderService").
	ImplStructName string
	// InterfaceFile / ImplFile let callers override the default paths
	// when generating for repositories instead of services.
	InterfaceFile string
	ImplFile      string
	// Returns is the method's result list (e.g. ["*models.Order",
	// "error"]). Defaults to ["error"]. The stub returns zero values
	// for every non-error result; a trailing error gets the
	// "not implemented" sentinel.
	Returns []string
	// ReceiverName is the impl stub's receiver identifier. It must match
	// what the scaffold already uses on the target struct — revive's
	// receiver-naming rule fails the project's own lint when one method
	// of a type names its receiver differently from the rest. Services
	// use "s" (the default); repositories use "r" (set by GenRepoMethod).
	ReceiverName string
}

MethodData is the resolved input for the method generator.

type MiddlewareData added in v0.1.11

type MiddlewareData struct {
	HTTPMethod string // "GET" | "POST" | ...
	Path       string // chi-style path
	// Middleware is the literal Go expression spliced into .With(...).
	// Role checks need the full chain: "auth.JWTAuth(jwtSvc),
	// auth.RequireRole(\"admin\")" — RequireRole alone 401s every
	// request because only JWTAuth puts claims into the context.
	Middleware string
	RoutesFile string // optional override; default scans every *.routes.go
	RoutesDir  string // default app/rest/routes
}

MiddlewareData is the resolved input.

type MockData added in v0.1.11

type MockData struct {
	// Interface name as written in source (e.g. "OrderService").
	Interface string
	// Source file the interface was found in. Used to compute the mock's
	// package import (we re-import the interfaces package so the mock can
	// satisfy it).
	SourcePath string
	// ModulePath is the project's Go module path, read from go.mod once.
	ModulePath string
	// PackageImport is the import path of the interface's package
	// (e.g. "irodata/app/services/interfaces").
	PackageImport string
	// PackageAlias is the local name to use for that import inside the
	// mock file (e.g. "ifaces"). Computed so that two imports with the
	// same final segment don't collide.
	PackageAlias string
	// OutPath is where the mock will land.
	OutPath string
	// Methods is the resolved method set.
	Methods []MockMethod
	// ExtraImports are packages referenced by the methods (e.g. "context")
	// that aren't the interface's own package. Each is "alias -> path".
	ExtraImports []MockImport
}

MockData is what GenMock needs to produce one mock file.

type MockImport added in v0.1.11

type MockImport struct {
	Alias string
	Path  string
}

MockImport pairs an alias with an import path.

type MockMethod added in v0.1.11

type MockMethod struct {
	Name       string
	Params     []MockParam
	Returns    []MockParam
	HasContext bool // first param is a context.Context — convention helps test-style choices.
}

MockMethod is one method's compiled signature, ready for templating.

type MockParam added in v0.1.11

type MockParam struct {
	Name string
	Type string
}

MockParam is one parameter or return. Name may be empty (return values commonly are). TypeExpr is the AST-printed type literal.

type PlannedAction added in v0.1.9

type PlannedAction struct {
	Kind   string `json:"kind"`
	Path   string `json:"path"`
	Size   int    `json:"size"`
	Detail string `json:"detail,omitempty"`
}

PlannedAction is one recorded action. Kind is "create" or "patch"; Path is the file path relative to the project root; Size is the content size in bytes; Diff is an optional short human-readable description of the change for patch actions.

func Plan added in v0.1.9

func Plan() []PlannedAction

Plan returns a copy of every recorded action, sorted by path for deterministic output. Does not clear the internal buffer — callers can call Plan multiple times (e.g., once for --json output, once for the human summary) and see the same content.

type RelationData added in v0.1.11

type RelationData struct {
	Resource string       // PascalCase parent ("Order")
	Other    string       // PascalCase related ("Customer")
	Kind     RelationKind // belongs_to | has_many | has_one

	ResourceModel string // path override
	OtherModel    string // path override
	MigrationDir  string
	MigrationVer  string
}

RelationData is the resolved input.

type RelationKind added in v0.1.11

type RelationKind string

RelationKind enumerates the supported gorm/sql relationship shapes.

const (
	RelationBelongsTo RelationKind = "belongs_to"
	RelationHasMany   RelationKind = "has_many"
	RelationHasOne    RelationKind = "has_one"
)

Relation kinds the generator accepts as the second positional argument. Each maps to a distinct GORM tag layout + (for `belongs_to`) a paired FK migration on the parent table.

type RenameData added in v0.1.11

type RenameData struct {
	Resource string // PascalCase ("Order")
	OldField string // PascalCase ("Total")
	NewField string // PascalCase ("AmountCents")
	Apply    bool   // false = preview only (default); true = write to disk
}

RenameData is the resolved input.

type ScaffoldData

type ScaffoldData struct {
	Name              string // PascalCase: Product
	LowerName         string // camelCase: product
	SnakeName         string // snake_case: product
	PluralName        string // PascalCase plural: Products
	PluralSnake       string // snake_case plural: products
	PluralLower       string // camelCase plural: products
	Fields            []Field
	MigrationNum      string
	IncludeController bool
	IncludeGraphQL    bool
	IncludeSwagger    bool
	Schedule          string // cron expression for job generator
	DBDriver          string // database driver from config (postgres, mysql, sqlite, sqlserver, clickhouse)
	ModulePath        string // Go module path read from go.mod (e.g., "github.com/myorg/myapp")
	Layout            layout.Layout
}

ScaffoldData holds all computed names and fields for template rendering.

func BuildScaffoldData

func BuildScaffoldData(name string, fields []Field) ScaffoldData

BuildScaffoldData converts a resource name and fields into fully computed ScaffoldData.

func (ScaffoldData) HasTimeField added in v0.1.10

func (s ScaffoldData) HasTimeField() bool

HasTimeField reports whether any field on this resource is `time.Time`. Used by templates that must emit `import "time"` only when needed — otherwise gofmt/imports complains about an unused import.

func (ScaffoldData) HasUUIDField added in v0.1.11

func (s ScaffoldData) HasUUIDField() bool

HasUUIDField is HasTimeField's twin for `uuid.UUID` fields — gates the github.com/google/uuid import in templates that don't otherwise import it (model, inputs).

func (ScaffoldData) L added in v0.1.11

func (s ScaffoldData) L() layout.Layout

L returns the layout for this scaffold operation, defaulting to layered when ScaffoldData was constructed without one. Production callers go through BuildScaffoldData which always sets Layout; this defaulting exists so test code that constructs ScaffoldData literals (and any future caller that does the same) keeps working without every test having to set the field. The default matches the historical behavior — every gen_*.go used to hardcode the layered paths.

type Step

type Step struct {
	Label string
	Fn    func(ScaffoldData) error
}

Step is a single unit of work in a generator pipeline.

Directories

Path Synopsis
Package astpatch is the shared AST helper that powers gofasta's modify-aware generators: g method, g field, g endpoint, g middleware, g repo-method, g relation, g rename.
Package astpatch is the shared AST helper that powers gofasta's modify-aware generators: g method, g field, g endpoint, g middleware, g repo-method, g relation, g rename.

Jump to

Keyboard shortcuts

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