# Writing generators

Give every new component, package or service the same start, with templates the whole team runs through axle generate.

A generator is a folder of templates that [`axle generate`](https://axlers.dev/docs/reference/generate.md) fills in. Keeping one in the repository means every new component, package or service starts the way the team agreed, with its tests and settings, instead of being copied from whichever one was nearest.

## A first generator

List the generator in the root `axle.toml`, under the name you'll run it by:

```toml
[generators.component]
path = "tools/generators/component"
```

The name can't be `package`, `app`, `ci`, `move` or `remove`, which are built in, or have a `:` in it.

In that folder, `generator.toml` says what the generator is for, where its files go and which values it needs:

```toml
description = "A React component with a test"
destination = "{{ folder(package) }}/src/components"

[variables.name]
prompt = "The component's name"
pattern = "[A-Z][A-Za-z0-9]*"

[variables.package]
prompt = "Which package"
choices = "packages"
```

The templates go in `files/`, laid out as they'll be written:

```text
tools/generators/component/
├── generator.toml
└── files/
    └── {{ kebab(name) }}/
        ├── {{ kebab(name) }}.tsx
        └── {{ kebab(name) }}.test.tsx
```

with `{{ kebab(name) }}.tsx` holding:

```tsx
export function {{ pascal(name) }}({ children }: { children: React.ReactNode }) {
    return <div className="{{ kebab(name) }}">{children}</div>
}
```

Then `axle generate component DatePicker --set package=web` writes `packages/web/src/components/date-picker/date-picker.tsx` and its test, and `axle generate` lists the generator with its description.

## Placeholders

`{{ name }}` is a variable's value, in file names, folder names, the files themselves and `destination`. A filter changes how it's written, and filters can wrap each other, as in `{{ upper(snake(name)) }}`:

| Filter   | `DatePicker` becomes | `user-profile` becomes |
| -------- | -------------------- | ---------------------- |
| `kebab`  | `date-picker`        | `user-profile`         |
| `snake`  | `date_picker`        | `user_profile`         |
| `camel`  | `datePicker`         | `userProfile`          |
| `pascal` | `DatePicker`         | `UserProfile`          |
| `upper`  | `DATEPICKER`         | `USER-PROFILE`         |
| `lower`  | `datepicker`         | `user-profile`         |

Words are split at spaces, punctuation and changes from lower to upper case, so `HTMLParser` is `html-parser` in kebab case.

`folder` turns a package's name into its folder, so `{{ folder(package) }}` is `apps/web` for the package `@acme/web` in `apps/web`. Use it with a variable whose `choices` are `"packages"`, since a package's name and folder often differ.

Only a variable's name, a filter around one, or a quoted text counts as a placeholder; any other text between `{{` and `}}` stays as it is, so JSX such as `style={{ margin: 0 }}` needs nothing. To write a placeholder itself into a file, quote the braces: `{{ "{{" }} name }}` is written as `{{ name }}`. A placeholder for a variable the generator doesn't have, or a filter that doesn't exist, is a [mistake](https://axlers.dev/docs/messages/generator-has-a-mistake.md) that names the file and line, and nothing is written.

A template whose name ends in `.template` loses that ending, so `package.json.template` is written as `package.json`. That keeps the generator's own folder from looking like a package, or a test file, to the tools that read the repository.

## Variables

Each `[variables.<name>]` table is one value the generator needs, asked for in the order they're listed. A variable's name has letters, digits and `_`, and doesn't start with a digit.

| Key       | Meaning                                                                                                        |
| --------- | -------------------------------------------------------------------------------------------------------------- |
| `prompt`  | the question asked in a terminal; the variable's name when it's left out                                       |
| `pattern` | a [regular expression](https://docs.rs/regex/latest/regex/#syntax) the whole value must match                  |
| `choices` | a list of the values allowed, such as `["css", "none"]`, or `"packages"` for the name of any workspace package |
| `default` | the value used when none is given; a terminal offers it, so pressing Enter takes it                            |

`destination` in `generator.toml` is the folder the files go in, relative to the repository root, and may use placeholders. Left out, the files go in the root. `--folder` on the command line puts them somewhere else.

## Generators in TypeScript

When templates aren't enough, such as for a file that depends on the other packages, a generator can have `generator.ts`, or `generator.js` or `generator.mjs`, instead of `files/`. Its default export gets the values and the workspace's packages, and returns each file's path, relative to `destination`, with its contents:

```ts
interface Input {
    variables: Record<string, string>
    projects: { name: string; path: string }[]
}

export default function ({ variables, projects }: Input): Record<string, string> {
    const imports = projects.map((project) => `import '${project.name}'`).join('\n')
    return { [`${variables.name}.ts`]: `${imports}\n` }
}
```

Axle runs it with Node.js, from the generator's folder, so Node 22.18 or later is needed for TypeScript. It can be `async`, and anything it prints is ignored. It has 30 seconds, and when it throws, takes longer or returns something else, `axle generate` stops with [`generator-failed`](https://axlers.dev/docs/messages/generator-failed.md) and what it printed on standard error. The files it returns are written the same way as templates: never over a file that's there, and only inside the repository.

## Generators in a plugin

A plugin ships generators in the folder its `axle-plugin.toml` names with `generators`. Each folder in it with a `generator.toml` is a generator, listed as `<plugin>:<folder>` and written the same way as the repository's own. [Writing a plugin](https://axlers.dev/docs/extending-axle/writing-a-plugin.md#generators) shows how to add them.
