layout

package
v0.43.2 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package layout reads and extends a project that follows the structure described by the arkoren-structure skill: one cmd/<process>/main.go per process, run with the App and Compose of its process root internal/bootstrap/<process>; internal/bootstrap holding only providers; one plain-Go internal/<feature> directory per feature, wired by internal/bootstrap/<feature>.go; internal/migrations and internal/platform.

The package analyzes source with go/parser only. It never type-checks, builds, or reaches the network, so it works on a project whose dependencies are not downloaded and reports on code that does not compile yet. The three consumers are `arkoren check` (Project.Check), `arkoren map` (Project.Map) and `arkoren add` (the Add* methods and Project.Apply).

Load a project with Load; a directory that lacks the layout is refused with a usage error that points at the skill.

Index

Constants

View Source
const (
	// RuleFeatureApplication marks feature, child or platform code importing the
	// application package or internal/bootstrap.
	RuleFeatureApplication = "feature-imports-application"
	// RuleBootstrapAction marks an exported function of internal/bootstrap that
	// takes a Composer and returns nothing instead of being a provider.
	RuleBootstrapAction = "bootstrap-action-func"
	// RuleSurfaceImport marks a surface child imported by something other than
	// internal/bootstrap or a test.
	RuleSurfaceImport = "surface-imported-outside-bootstrap"
	// RuleBelowImport marks a child below a feature importing that feature.
	RuleBelowImport = "below-child-imports-feature"
	// RuleDriverImport marks feature or platform code importing a driver or ark/iam.
	RuleDriverImport = "feature-imports-driver"
	// RuleBannedName marks a package path segment that names a role.
	RuleBannedName = "banned-package-name"
	// RuleComposerUse marks Composer.Use called outside a provider or registration function body.
	RuleComposerUse = "composer-use-outside-composition"
	// RuleBootstrapNew marks a bootstrap.New* call outside internal/bootstrap.
	RuleBootstrapNew = "bootstrap-new-outside-bootstrap"
	// RuleComposerSupply marks Composer.Supply called outside a _test.go file.
	RuleComposerSupply = "composer-supply-outside-tests"
)

Rule names reported in Violation.Rule. They are stable identifiers for scripts and agents that filter the check output.

Variables

View Source
var IAMFeatures = []string{"reset", "verification", "two-factor", "tokens", "permissions", "account"}

IAMFeatures lists the values `arkoren add ark iam --with` accepts, in the order the generated code presents them.

View Source
var Surfaces = []string{"web", "jobs", "flow", "tools", "events", "schedules"}

Surfaces lists the child packages that sit above a feature root, in the order flags and providers are presented. Each imports the root and is imported only by internal/bootstrap. The `<feature>test` fixtures package is also above the root but is created by hand, not by `arkoren add`.

Functions

func OAuthProviders added in v0.37.1

func OAuthProviders() []string

OAuthProviders returns the provider names `arkoren add ark oauth` accepts, in the order its usage presents them. The slice is new on every call.

Example:

usage := "PROVIDER: " + strings.Join(layout.OAuthProviders(), ", ")

Types

type Bootstrap

type Bootstrap struct {
	// Providers are the package-level application.Provide variables, grouped
	// by the file that declares them.
	Providers []ProviderFile `json:"providers,omitzero"`
}

Bootstrap is the content of internal/bootstrap.

type Edit

type Edit struct {
	// Path is the slash-separated file path relative to the project root.
	Path string
	// Inserted describes each inserted line, such as a registration call.
	Inserted []string
	// contains filtered or unexported fields
}

Edit is one insertion into an existing file.

type Feature

type Feature struct {
	// Name is the directory name below internal/.
	Name string `json:"name"`
	// Constructors are the exported New* functions of the root package, such
	// as NewStore and NewService.
	Constructors []string `json:"constructors,omitzero"`
	// Above are the children that import the root, with their constructors.
	Above []Surface `json:"above,omitzero"`
	// Below are the children imported by the root.
	Below []string `json:"below,omitzero"`
}

Feature is one internal/<feature> directory.

type FeatureOptions

type FeatureOptions struct {
	// Name is the feature and package name: lowercase letters and digits.
	Name string
	// Surfaces are the child packages to create, a subset of web, jobs,
	// flow, tools, events and schedules.
	Surfaces []string
	// Process names the process root internal/bootstrap/<process> whose Compose
	// uses the surface providers.
	// Empty selects "server". It is unused when Surfaces is empty.
	Process string
}

FeatureOptions selects what Project.AddFeature creates.

type IAMOptions added in v0.33.0

type IAMOptions struct {
	// With lists the optional features to enable, a subset of [IAMFeatures]:
	// reset (password reset and registration), verification (email
	// verification), two-factor, tokens, permissions and account (GET
	// /auth/account). Password login is always on. Sign-in clients are not
	// features: add them with [Project.AddOAuth] before or after the module.
	With []string
	// Process names the process root internal/bootstrap/<process> that runs the
	// identity jobs, which send the module's emails. Empty selects "server". It
	// is unused when neither reset nor verification is selected. The identity
	// routes always go into the server process.
	Process string
}

IAMOptions selects what Project.AddIAM creates.

type Map

type Map struct {
	// Module is the module path from go.mod.
	Module string `json:"module"`
	// Processes lists cmd/<process> packages in directory order.
	Processes []Process `json:"processes"`
	// Bootstrap lists the providers of internal/bootstrap.
	Bootstrap Bootstrap `json:"bootstrap"`
	// Features lists internal/<feature> packages in directory order.
	Features []Feature `json:"features,omitzero"`
	// Migrations describes internal/migrations; the zero value means absent.
	Migrations Migrations `json:"migrations,omitzero"`
	// Platform lists internal/platform/<purpose> packages.
	Platform []string `json:"platform,omitzero"`
}

Map is the compact inventory printed by `arkoren map`: what each process uses, which providers bootstrap offers, which constructors and surfaces each feature has, and the migrations. It lists names only, so an agent can orient itself before searching.

func (Map) Text

func (inventory Map) Text() string

Text renders the inventory as a compact listing, one line per fact, for reading in a terminal or an agent's context. The JSON form carries the same content.

type Migrations

type Migrations struct {
	// All is true when an All function is declared.
	All bool `json:"all,omitzero"`
	// IDs are the literal ids passed to NewMigration, in source order.
	IDs []string `json:"ids,omitzero"`
}

Migrations describes internal/migrations.

type Plan

type Plan struct {
	// Create lists new files, relative to the project root. Apply refuses to
	// overwrite an existing path.
	Create []files.File
	// Edit lists existing files changed by inserting lines at one anchor.
	Edit []Edit
	// Requires lists the modules, as module@version, that the new files import
	// and go.mod does not require yet, each pinned by the CLI. Fetch them with
	// go get before go mod tidy, so tidy does not resolve a newer release.
	Requires []string
	// Steps lists what the command could not do itself, such as adding
	// migrations to an existing Migrator or setting environment variables. Each
	// is one imperative sentence; none has a command, because each needs a value
	// or an edit only the reader can make.
	Steps []console.Step
}

Plan is the set of changes one `arkoren add` operation would make: new files and single-point insertions into existing files. Nothing is written until Project.Apply.

type Process

type Process struct {
	// Name is the directory name below cmd/ and internal/bootstrap/.
	Name string `json:"name"`
	// Compose lists the statements of the exported Compose function of the
	// process root internal/bootstrap/<process> in source order, such as
	// "compose.Use(bootstrap.Server)". A statement inside an if carries the
	// condition, as in "compose.Use(bootstrap.MCP) [if compose.App().Debug()]".
	Compose []string `json:"compose,omitzero"`
}

Process is one cmd/<process> package.

type Project

type Project struct {
	// Root is the absolute project directory.
	Root string
	// Module is the module path declared in go.mod.
	Module string
	// contains filtered or unexported fields
}

Project is a loaded project: its module path and the parsed Go files below cmd/ and internal/. It is read-only after Load; the Add* methods return plans instead of changing it.

func Load

func Load(ctx context.Context, dir string) (*Project, error)

Load reads the project in dir. A project conforms when dir holds go.mod, at least one cmd/<process>/main.go and an internal/bootstrap directory; otherwise Load returns a usage error that explains this and names the arkoren-structure skill. Only dir itself is inspected: parent directories are never searched.

Go files below cmd/ and internal/ are parsed, skipping directories whose names start with "." or "_" and testdata. A syntax error in any of them is returned as an error naming the file and line, because the analyses would otherwise silently skip that file.

Example:

project, err := layout.Load(ctx, ".")
if err != nil {
	return err
}
violations := project.Check()

func (*Project) AddFeature

func (project *Project) AddFeature(options FeatureOptions, templates fs.FS) (*Plan, error)

AddFeature plans internal/<name>: the root files (<name>.go, service.go and store.go, plain Go that never imports the application package), one child package per requested surface (a struct built by a New constructor over the Service, with a Register method for its target where one exists; web also gets problems.go mapping the root's ErrNotFound to a problem), and internal/bootstrap/<name>.go with the providers that wire them: <Name>Store, <Name>Service and one <Name><Surface> provider per surface. For each surface it also inserts a compose.Use(bootstrap.<Name><Surface>) line into the Compose of the chosen process, adding the bootstrap import if the file lacks it. Child packages are imported by the bootstrap file with the alias <name><surface>.

Surface stubs compile as generated. The web provider registers its handlers on the shared router under /<name> and the events provider subscribes its listeners. Where a working registration needs a driver the application has not chosen (queue consumer, workflow engine, MCP endpoint, scheduler), the provider builds the surface and leaves a TODO that says what to add. The Store holds no database yet, because the scaffold has no Database provider; a TODO in the store provider says how to add one.

It returns a usage error when the name is invalid or reserved, internal/<name> or internal/bootstrap/<name>.go exists, a bootstrap provider of that name is already declared, a surface is unknown, or the process's Compose cannot be edited. It never changes the project; call Project.Apply on the plan.

Example:

plan, err := project.AddFeature(layout.FeatureOptions{Name: "orders", Surfaces: []string{"web"}}, templates)
if err != nil {
	return err
}
err = project.Apply(ctx, plan)

func (*Project) AddIAM added in v0.33.0

func (project *Project) AddIAM(options IAMOptions, templates fs.FS) (*Plan, error)

AddIAM plans the identity module of ark/iam: internal/bootstrap/iam.go with the IAM, IAMRouter and, when reset or verification is selected, IAMJobs providers; one fragment provider file per selected feature (PasswordReset, EmailVerification, TokenScopes, Roles, AccountView), each returning the construction callback the facade passes to its package; and every shared provider the generated code uses that internal/bootstrap does not declare yet (Database, Cache, Hasher, and as selected LinkSigner, Mailer, Queue, Dispatcher, Consumer, Work, TwoFactorKey), written with local defaults. A provider that already exists, found by name, is left alone and used. A sign-in client that internal/bootstrap already declares (see Project.AddOAuth) is passed to identity.Provider in iam.go.

The module's migrations apply when the server starts. Without a Migrator provider, the plan writes one (migrate.New over Database with the application's migrations.All and IAM.Migrations, plus internal/migrations when it has no All) and a Migrate provider whose Startup callback runs Migrator.Up, which holds the migration lock, so replicas are safe. With a Migrator, the plan inserts IAM.Migrations into it, and only when that is impossible leaves a step.

It inserts compose.Use(bootstrap.Migrate) when the plan writes it and compose.Use(bootstrap.IAMRouter) into the Compose of the server process, and, for the jobs, compose.Use(bootstrap.IAMJobs) and compose.Use(bootstrap.Work) into the Compose of options.Process, skipping providers the Compose already uses. The routes are mounted under /auth. It appends to .env the variables with safe local defaults it lacks (Plan.Edit): DATABASE_URL when it writes the Database provider, the reset and verification page addresses and the declared clients' redirect URLs, derived from HTTP_ADDR, never a secret or a key path. The plan lists the modules it needs with their pinned versions (Plan.Requires) and the steps only the reader can do (Plan.Steps): key files and starting the server.

It returns a usage error for an unknown feature (a sign-in provider such as google points to `add ark oauth`), for a provider the module declares that internal/bootstrap already declares, for an existing target file, or when a process has no Compose to edit. It never changes the project.

Example:

plan, err := project.AddIAM(layout.IAMOptions{With: []string{"reset", "tokens"}}, templates)

func (*Project) AddMigration

func (project *Project) AddMigration(name string, templates fs.FS) (*Plan, error)

AddMigration plans internal/migrations/<sequence>_<name>.go and registers the migration in All. The sequence is four digits, one more than the highest numbered file already in the directory, so files sort in running order. The migration id is the name with hyphens; the exported variable is its CamelCase form. The stub extracts its schema-builder operations into exported variables beside the migration: a name starting with "create" creates (and on Down drops) the table named by the remaining words, any other name alters that table with an empty change that fails until a TODO is resolved.

If internal/migrations declares All, the new variable is appended to the slice literal it returns. Otherwise migrations.go is created with All; an existing migrations.go without All is refused. A migration with the same id or identifier is refused.

Example:

plan, err := project.AddMigration("create_orders", templates)

func (*Project) AddOAuth added in v0.33.0

func (project *Project) AddOAuth(providers []string, templates fs.FS) (*Plan, error)

AddOAuth plans the OAuth sign-in clients of ark/oauth for providers, each one of google, github, microsoft, apple or oidc: internal/bootstrap/<provider>.go with a provider named for it (Google, GitHub, Microsoft, Apple, OIDC) that builds the client from its environment, registers its startup and returns it; the OAuthKey provider once, unless internal/bootstrap declares one; and, for GitHub, the GitHubSignUp settings fragment that lets a first GitHub login create a user. The other providers log in existing users only.

When internal/bootstrap declares the IAM provider, the plan inserts identity.Provider(compose.Use(<Client>)[, compose.Use(<Client>SignUp)]) into the callback IAM passes to iam.New, and leaves a step only when that is impossible. Without IAM, only the client is added and a step says to run `arkoren add ark iam`, which wires every client declared by then. It appends to .env each client's <PROVIDER>_REDIRECT_URL, the callback below the /auth mount on the address of HTTP_ADDR, when .env lacks it; secrets, key paths and client IDs are left to the reader and listed in the steps.

It returns a usage error for no provider, an unknown or repeated one, or a client internal/bootstrap already declares. It never changes the project.

Example:

plan, err := project.AddOAuth([]string{"google", "github"}, templates)

func (*Project) AddProcess

func (project *Project) AddProcess(name string, templates fs.FS) (*Plan, error)

AddProcess plans a new process: cmd/<name>/main.go, which runs the process root's App and Compose with application.Run, and the process root internal/bootstrap/<name> with app.go (an App provider that names the service <project>-<name> and uses bootstrap.LogHandler) and compose.go (an empty exported Compose). <project> is the last element of the module path, without a trailing major-version element such as v2, so the name is the same every time the command runs. The name is lowercase words of letters and digits joined by hyphens; the package name drops the hyphens. Neither directory may exist, and internal/bootstrap must declare the LogHandler provider that `arkoren new` generates.

Example:

plan, err := project.AddProcess("worker", templates)

func (*Project) AddProvider

func (project *Project) AddProvider(name string, templates fs.FS) (*Plan, error)

AddProvider plans internal/bootstrap/<name>.go: an exported provider named for its resource (name "mail-queue" declares MailQueue) initialized with application.Provide. The stub builds an empty placeholder value and a TODO explains how to replace it. The name may use hyphens or underscores between words. The file and the exported identifier must not already exist in internal/bootstrap.

Example:

plan, err := project.AddProvider("database", templates)

func (*Project) Apply

func (project *Project) Apply(ctx context.Context, plan *Plan) error

Apply writes a plan: new files first, created exclusively so an existing path is never replaced, then the edits of existing files. Creating before editing means a collision stops the operation before any user code is touched.

Each edit is rechecked against the content it was planned from and refused if the file changed since, so Apply never overwrites concurrent work. An edit replaces the file through a temporary file in the same directory and keeps its permissions; symlinks and non-regular files are refused. A failure partway can leave earlier new files in place; the error names the failing path.

Example:

if err := project.Apply(ctx, plan); err != nil {
	return err
}

func (*Project) Check

func (project *Project) Check() []Violation

Check reports every violation of the structure skill's mechanical rules, sorted by file and line. An empty result means the project conforms.

Rules:

  • feature packages (root, children above and below) and internal/platform never import arkoren.dev/core/application or internal/bootstrap, so they stay plain Go that takes its dependencies as arguments;
  • an exported function of the internal/bootstrap package with a *application.Composer parameter and no result is a mistake: bootstrap exports providers (each returning a component or a construction callback for one) and constructors that return a value;
  • a surface child (web, jobs, flow, tools, events, schedules, <feature>test) is imported only by internal/bootstrap, including its process roots; _test.go files may import any child, since fixtures exist for tests;
  • a child below a feature never imports that feature;
  • feature and platform packages never import arkoren.dev/driver/... or arkoren.dev/ark/iam: only bootstrap wires vendors;
  • no package path below cmd/ or internal/ contains a banned role name such as util, common, models or handlers;
  • Composer.Use is called only directly in the body of a function that declares a *application.Composer parameter (a provider's build function, a process root's Compose, a New*(compose, ...) constructor), never inside a method, nor inside a closure the function creates, because a closure runs after composition (handlers, Startup and Run callbacks). The one exception is a construction callback, a function literal whose parameter is an Arkoren construction draft (*application.Builder, *iam.Builder, *password.Builder: a pointer to a type named ...Builder in an arkoren.dev package). Those callbacks run once, synchronously, while the constructor they are passed to runs, so Use inside them is still composition;
  • Composer.Supply, which replaces a provider's value, is called only in _test.go files;
  • bootstrap.New* functions are called only from internal/bootstrap.

The Use and Supply rules are a syntactic heuristic: they recognize a call whose receiver is a parameter declared as *application.Composer. A Composer stored in a struct field or passed on to another function is not followed.

Example:

for _, violation := range project.Check() {
	fmt.Printf("%s:%d: %s\n", violation.File, violation.Line, violation.Message)
}

func (*Project) Map

func (project *Project) Map() Map

Map builds the project inventory from source alone. Test files are ignored. Names follow directory order, so the result is deterministic.

Example:

inventory := project.Map()
fmt.Print(inventory.Text())

func (*Project) NeedsTidy added in v0.30.0

func (project *Project) NeedsTidy(plan *Plan) (bool, error)

NeedsTidy reports whether the Go files plan creates import a package from a module that go.mod does not require yet, so the project builds only after `go mod tidy`. Standard-library packages (no dot in the first path element) and the project's own packages never need a requirement. A requirement marked `// indirect` counts: it already pins the module and its checksums.

Example:

if needed, err := project.NeedsTidy(plan); err == nil && needed {
	// run go mod tidy in project.Root
}

type ProviderFile added in v0.32.0

type ProviderFile struct {
	// File is the file name inside internal/bootstrap.
	File string `json:"file"`
	// Names are the provider variables in source order.
	Names []string `json:"providers"`
}

ProviderFile lists the providers one bootstrap file declares.

type Surface

type Surface struct {
	// Name is the child directory name, such as web.
	Name string `json:"name"`
	// Constructors are its exported New* functions, such as NewHandlers.
	Constructors []string `json:"constructors,omitzero"`
}

Surface is a child package above a feature root.

type Violation

type Violation struct {
	// File is the slash-separated path relative to the project root.
	File string `json:"file"`
	// Line is the 1-based line of the offending import, call or package.
	Line int `json:"line"`
	// Rule is one of the Rule constants.
	Rule string `json:"rule"`
	// Message explains the violation and names the fix.
	Message string `json:"message"`
}

Violation is one broken layout rule at a source position.

Jump to

Keyboard shortcuts

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