Skip to content

Commit dfe9025

Browse files
feat: add variables and when conditions (#79)
* feat: add variables and when conditions Adds the variable core resource and when conditions on resources, templates and variables. - variable block (name, valueType text | number | boolean | enum | multiEnum, description, options, default, sensitive, when). Asked on every run and never saved. - ${{ name }} references in resource parameters, defaults and the variables passed to templates. Exact references keep their type, $${{ }} escapes. References without a declaration are asked as text and shown as a plan warning. - when: keys are variable names; value = equals (multiEnum: includes), list = one of, { not } = opposite, any = alternatives. Conditions may only reference declared variables. - Variables are scoped to their file. Templates are expanded in rounds: the variables of a file are asked first, templates whose when doesn't match are never loaded, and values can be passed to a template's variables. - --var name=value / template.name=value on plan, apply, destroy, refresh, import and test. Values are forwarded to the codify test VM and accepted from the dashboard through the private values file (never logged). GET /capabilities tells the dashboard that variables are supported. - Refresh and import resolve the variables of the project file, skip resources whose when doesn't match, match with values and keep the references and when in the file. - Sensitive variables are masked in the plan. - Prompts for the default (Ink), plain, json and stub reporters. Uses @codifycli/schemas from the codify-schemas branch until 1.5.0 is published. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016QnBk5xkqnrsLyn9Eco1yn * chore: point the lockfile to the rebased codify-schemas branch Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016QnBk5xkqnrsLyn9Eco1yn * chore: use @codifycli/schemas 1.5.0 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016QnBk5xkqnrsLyn9Eco1yn * feat: show the label of variables when asking for them Variables get an optional label again (codify-schemas 1.6.0): the question shown when asking for the value. The name stays the identifier used by references, conditions and --var, and is shown next to the label. The description is the help text under it. Uses the codify-schemas branch until 1.6.0 is published. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016QnBk5xkqnrsLyn9Eco1yn * chore: use @codifycli/schemas 1.6.0 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016QnBk5xkqnrsLyn9Eco1yn * test: wait for the enum variable prompt before pressing enter The select registers its input handler after it renders. On slow CI machines enter was written before that and dropped, so the test saw the previous answer. Wait for the prompt and send enter until it is handled. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016QnBk5xkqnrsLyn9Eco1yn --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent fd61aed commit dfe9025

59 files changed

Lines changed: 1933 additions & 72 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CLAUDE.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,19 @@ Parse → TemplateExpander.expand() → PluginManager.initialize() → os/distro
226226
- `codify apply <template>` is a project with a single template declaration (the resolver's fetched template is seeded into the loader).
227227
- `import`/`refresh`/`edit` do not expand templates: template blocks are left untouched in files.
228228

229+
## Variables and Conditions Architecture
230+
231+
`{ "type": "variable", "name": "siteType", "valueType": "enum", "options": [...], "default"?, "label"?, "description"?, "sensitive"?, "when"? }` is a core config block (`ConfigType.VARIABLE`, `src/entities/variable-config.ts`, validated against `VariableSchema`). It is never sent to a plugin. `valueType` is `text` (default), `number`, `boolean`, `enum` or `multiEnum`. Values are asked on every run and never saved. `name` is the identifier (`[\w-]+`) used by references, conditions and `--var`; `label` (any text, defaults to the name) is the question shown when asking and `description` the help text under it, so wording can change without breaking references.
232+
233+
- **References**: `${{ name }}` in resource parameters, in variable defaults and in the `variables` passed to templates (`src/variables/substitution.ts`). A string that is exactly one reference gets the typed value (number, boolean, list); otherwise the value is interpolated as text. `$${{ name }}` is an escaped literal. Not allowed in `template.source`. A reference without a variable block is an implicit `text` variable: it is asked as well and shown as a plan warning (`Project.implicitVariables`).
234+
- **Conditions** (`when` on resources, templates and variables, `src/variables/condition.ts`): keys are variable names and must all match. A value means equals (multiEnum: includes), a list means one of, `{ "not": ... }` the opposite, `any` is a list of alternatives. A variable without a value (its own `when` didn't match) never matches. Conditions may only reference declared variables (`VariableError` otherwise). `os`/`distro` stay separate fields.
235+
- **`VariableResolver.resolveScope()`** (`src/variables/variable-resolver.ts`) handles one file: validates, orders the variables (stable sort on `when`/`default` dependencies, cycles are errors), asks for each one (`Reporter.promptVariable`, asked again with `error` until valid), removes declarations whose `when` doesn't match, asks for implicit variables, then replaces the references (`ResourceConfig.setParameter`, `TemplateConfig.resolvedVariables`). Parameters that use a `sensitive` variable go into `ResourceConfig.sensitiveParameterKeys` and are masked in the plan.
236+
- **Scopes**: variables are scoped to their file. `TemplateExpander.flatten()` resolves a file's scope before expanding its templates, so the questions come in rounds and templates whose `when` doesn't match are never loaded. A template's scope is labelled by its declaration name or the last part of its source (`astro-blog`, repeated labels get `-2`). Qualified names (`astro-blog.projectName`) are used by `--var` and in prompts. A template included again with different `resolvedVariables` is expanded again (`instanceKey`).
237+
- **Values instead of asking**: values passed by the template declaration > `--var name=value` / `--var template.name=value` (`src/common/variable-flags.ts`) > the values file (`CODIFY_PARAMETER_VALUES_FILE`, now `{ parameters, variables }`, the old list format is still read). `codify test` expands templates on the host and forwards every value to the VM. `codify connect` writes the `variables` of the request body to the values file (`src/connect/variable-values.ts`), never on the command line or in logs. `GET /capabilities` tells the dashboard that the CLI supports variables.
238+
- **Pipeline**: `PluginInitOrchestrator` resolves variables right after parsing, before plugin initialization: `expandTemplates` (plan, apply, destroy, test) uses the expander, `resolveVariables` (import, refresh) uses `TemplateExpander.resolveProjectVariables()` for the project file only. Resources removed by a condition prune `dependsOn` like the os filter (`Project.removeConditionalDeclarations`).
239+
- **Import / refresh write-back**: refresh imports only the resources whose `when` matches, with their values. `ImportOrchestrator.updateExistingFiles` passes the resolved project to `FileModificationCalculator` for its own file, so matching uses values while the file is written from its contents: `${{ }}` references and core properties (`name`, `dependsOn`, `os`, `distro`, `when`) are kept (`src/generators/preserve-existing-values.ts`). Block positions are counted from the file, so variable blocks count.
240+
- `validate` and `init` do not resolve variables.
241+
229242
## Plugin Error Handling Architecture
230243

231244
Plugin errors flow as structured `PluginErrorData` over IPC and are caught as `PluginError` instances on the CLI side:

‎package-lock.json‎

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
"dependencies": {
77
"@assistant-ui/ai-sdk": "^0.0.18",
88
"@assistant-ui/react-ink": "^0.0.54",
9-
"@codifycli/schemas": "1.4.1",
9+
"@codifycli/schemas": "1.6.0",
1010
"@homebridge/node-pty-prebuilt-multiarch": "npm:node-pty@1.2.0-beta.15",
1111
"@mischnic/json-sourcemap": "^0.1.1",
1212
"@oclif/core": "^4.0.8",

‎src/commands/apply.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { autoApproveAllFlag, isAutoApproveAll } from '../common/approval-flags.j
55
import { BaseCommand } from '../common/base-command.js';
66
import { ApplyOrchestrator } from '../orchestrators/apply.js';
77
import { MissingParametersResolver } from '../common/resolve-missing-parameters.js';
8+
import { loadVariableValues, varFlag } from '../common/variable-flags.js';
89

910
export default class Apply extends BaseCommand {
1011
static description =
@@ -28,6 +29,7 @@ For more information, visit: https://codifycli.com/docs/commands/apply
2829
`
2930

3031
static flags = {
32+
'var': varFlag,
3133
'sudoPassword': Flags.string({
3234
optional: true,
3335
description: 'Automatically use this password for any handlers that require elevated permissions.',
@@ -77,6 +79,7 @@ For more information, visit: https://codifycli.com/docs/commands/apply
7779
autoApproveAll: isAutoApproveAll(flags, raw),
7880
allowSleep: flags['allow-sleep'],
7981
presetParameterValues: await MissingParametersResolver.loadPresetValues(),
82+
variableValues: await loadVariableValues(flags),
8083
// secure: flags.secure,
8184
}, this.reporter);
8285

‎src/commands/destroy.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import chalk from 'chalk';
44
import { BaseCommand } from '../common/base-command.js';
55
import { DestroyOrchestrator } from '../orchestrators/destroy.js';
66
import { autoApproveAllFlag, isAutoApproveAll } from '../common/approval-flags.js';
7+
import { loadVariableValues, varFlag } from '../common/variable-flags.js';
78

89
export default class Destroy extends BaseCommand {
910
static strict = false;
@@ -28,6 +29,7 @@ For more information, visit: https://codifycli.com/docs/commands/destory`
2829
]
2930

3031
static flags = {
32+
'var': varFlag,
3133
'sudoPassword': Flags.string({
3234
optional: true,
3335
description: 'Automatically use this password for any handlers that require elevated permissions.',
@@ -58,6 +60,7 @@ For more information, visit: https://codifycli.com/docs/commands/destory`
5860
.map((r) => r.input);
5961

6062
await DestroyOrchestrator.run({
63+
variableValues: await loadVariableValues(flags),
6164
verbosityLevel: flags.debug || flags.verbose ? 3 : 0,
6265
typeIds: args,
6366
path: flags.path,

‎src/commands/import.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import fs from 'node:fs/promises';
55
import { BaseCommand } from '../common/base-command.js';
66
import { ImportOrchestrator } from '../orchestrators/import.js';
77
import { Shell, ShellUtils } from '../utils/shell.js';
8+
import { loadVariableValues, varFlag } from '../common/variable-flags.js';
89

910
export default class Import extends BaseCommand {
1011
static strict = false;
@@ -40,6 +41,7 @@ For more information, visit: https://codifycli.com/docs/commands/import`
4041
]
4142

4243
static override flags = {
44+
'var': varFlag,
4345
'updateExisting': Flags.boolean({
4446
description: 'Force the CLI to try to update an existing file instead of prompting the user with the option of creating a new file',
4547
}),
@@ -59,6 +61,7 @@ For more information, visit: https://codifycli.com/docs/commands/import`
5961
const cleanedArgs = await this.cleanupZshStarExpansion(args);
6062

6163
await ImportOrchestrator.run({
64+
variableValues: await loadVariableValues(flags),
6265
verbosityLevel: flags.debug ? 3 : 0,
6366
typeIds: cleanedArgs,
6467
path: resolvedPath,

‎src/commands/plan.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { Args } from '@oclif/core';
55
import { MissingParametersResolver } from '../common/resolve-missing-parameters.js';
66

77
import { autoApproveAllFlag } from '../common/approval-flags.js';
8+
import { loadVariableValues, varFlag } from '../common/variable-flags.js';
89

910
export default class Plan extends BaseCommand {
1011
static description =
@@ -28,6 +29,7 @@ For more information, visit: https://codifycli.com/docs/commands/plan`
2829
]
2930

3031
static flags = {
32+
'var': varFlag,
3133
'auto-approve-all': autoApproveAllFlag,
3234
}
3335

@@ -53,6 +55,7 @@ For more information, visit: https://codifycli.com/docs/commands/plan`
5355
secureMode: (flags as { secure?: boolean }).secure,
5456
autoApproveTemplateCommands: flags['auto-approve-all'],
5557
presetParameterValues: await MissingParametersResolver.loadPresetValues(),
58+
variableValues: await loadVariableValues(flags),
5659
}, this.reporter);
5760

5861
process.exit(0);

‎src/commands/refresh.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import fs from 'node:fs/promises';
33
import { BaseCommand } from '../common/base-command.js';
44
import { Shell, ShellUtils } from '../utils/shell.js';
55
import { RefreshOrchestrator } from '../orchestrators/refresh.js';
6+
import { loadVariableValues, varFlag } from '../common/variable-flags.js';
67

78
export default class Refresh extends BaseCommand {
89
static strict = false;
@@ -23,6 +24,10 @@ For more information, visit: https://codifycli.com/docs/commands/refresh`
2324
'<%= config.bin %> <%= command.id %> \\*'
2425
]
2526

27+
static flags = {
28+
'var': varFlag,
29+
}
30+
2631
public async run(): Promise<void> {
2732
const { raw, flags } = await this.parse(Refresh)
2833

@@ -35,10 +40,11 @@ For more information, visit: https://codifycli.com/docs/commands/refresh`
3540
const cleanedArgs = await this.cleanupZshStarExpansion(args);
3641

3742
await RefreshOrchestrator.run({
43+
variableValues: await loadVariableValues(flags),
3844
verbosityLevel: flags.debug ? 3 : 0,
3945
typeIds: cleanedArgs,
4046
path: resolvedPath,
41-
secureMode: flags.secure,
47+
secureMode: (flags as { secure?: boolean }).secure,
4248
}, this.reporter)
4349

4450
process.exit(0)

‎src/commands/test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import os from 'node:os';
66
import { BaseCommand } from '../common/base-command.js';
77
import { ctx } from '../events/context.js';
88
import { TestOrchestrator } from '../orchestrators/test.js';
9+
import { loadVariableValues, varFlag } from '../common/variable-flags.js';
910

1011
export default class Test extends BaseCommand {
1112
static description =
@@ -23,6 +24,7 @@ For more information, visit: https://codifycli.com/docs/commands/apply
2324
`
2425

2526
static flags = {
27+
'var': varFlag,
2628
'sudoPassword': Flags.string({
2729
optional: true,
2830
description: 'Automatically use this password for any handlers that require elevated permissions.',
@@ -64,6 +66,7 @@ For more information, visit: https://codifycli.com/docs/commands/apply
6466
flags.operatingSystem === 'linux' ? OS.Linux : hostSystem;
6567

6668
await TestOrchestrator.run({
69+
variableValues: await loadVariableValues(flags),
6770
path: flags.path ?? args.pathArgs,
6871
verbosityLevel: flags.debug ? 3 : 0,
6972
vmOs: osFlag,

‎src/common/errors.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,22 @@ export class TemplateError extends CodifyError {
373373
}
374374
}
375375

376+
/** An invalid variable declaration, reference, condition or value. */
377+
export class VariableError extends CodifyError {
378+
name = 'VariableError'
379+
// Where the error is. Ex: 'codify.jsonc' or 'template @codify/astro-blog'
380+
location: string;
381+
382+
constructor(location: string, message: string) {
383+
super(message);
384+
this.location = location;
385+
}
386+
387+
formattedMessage(): string {
388+
return `Variable error (${this.location}): ${this.message}`;
389+
}
390+
}
391+
376392
export class TemplateCommandsDeclinedError extends CodifyError {
377393
name = 'TemplateCommandsDeclinedError'
378394

0 commit comments

Comments
 (0)