diff --git a/.agents/skills/cli-commands/SKILL.md b/.agents/skills/cli-commands/SKILL.md new file mode 100644 index 0000000000..ea5399e6a6 --- /dev/null +++ b/.agents/skills/cli-commands/SKILL.md @@ -0,0 +1,83 @@ +--- +name: cli-commands +description: Guidelines for NativeScript CLI commands. Use whenever adding or editing an `ns` command, its options, params, providers, help page, registration or tests, and when reviewing such a change. Covers defineCommand, `extends Command(...)` and running one command from another. +--- + +# Commands + +`defining-commands.md` is the authority. Read the section for whatever you use. +Built-in commands have all been migrated: do not add an `ICommand` class. When editing +a command, apply these rules to what you change and leave the rest. + +## 1. Choose the form + +- **`defineCommand({ … })`** by default: a few services and a short handler. +- **`class X extends Command({ … })`** when the command has internal structure: + state shared by `canExecute` and `run`, several private steps, or enough + collaborators that fields read better. Converting an existing command needs a + reason of that kind; both forms are supported and behave the same. Do not + convert one because you are nearby. + +Where a sibling command disagrees with the rules below, follow the rules. Look at a +command of the same shape before writing one: `lib/commands/clean.ts`, +`lib/commands/platform-clean.ts` (class), `lib/commands/install.ts` (process-level +options), `lib/commands/run.ts` (several platforms). + +## 2. Rules + +- **Options**: declare with `booleanOption()`, `stringOption()` and the rest, and + read them from `ctx.options` or `this.options`, never from `$options`. Extract a + shared schema with `satisfies CommandOptionsSchema`, not a type annotation. +- **Process-level options** (`--path`, `--log`, …) are not redeclared. List + `CliOptions`: `options: [CliOptions, { … }]`. +- **Options a service also reads** belong in an option group, which the command lists; see + the cli-options skill. +- **Services**: `inject(Token)` at the top of the handler, or in fields in the class + form. After an `await`, use `ctx.injector.get(Token)`. Never build a shared + "services" object, and do not pass one to helpers: each helper injects or receives + what it uses. +- **A project**: `providers: [provideProject()]` instead of checking by hand. +- **Arguments**: declare `params`. `canExecute` adds checks; it does not replace + the `params` policy. +- **Failing**: `ctx.fail(message)` or `this.context.fail(message)`. +- **Another command**: `CommandsService.runCommand(...)`, awaited. It parses the + same command line; it takes no options of its own, so pass data to services + directly when their values must differ. +- **Platform families**: one definition registered per platform with a provider for + the platform, not subclasses. +- **Help** lives in `docs/man_pages//`, in a file named after the command with + `|` as `-` (`config|get` is `config/config-get.md`). Copy a sibling's layout, header + included, and add the command to the area's other "Related Commands" tables. A + definition's `description` is not shown there. Pages are copied by the build. Do + not rename a command without moving its page. +- **`--json`**: declare `json: booleanOption()`, print one JSON document and nothing + else, through the same logger the command's other output uses. +- Hooks fire as `before-` and `after-`, so a name is public behaviour. + +## 3. Register + +In `lib/bootstrap.ts`, with the type argument and a lazy `require`: + +```ts +registerBuiltInCommand< + typeof import("./commands/clean").cleanCommandDefinition +>("clean", () => require("./commands/clean").cleanCommandDefinition); +``` + +Never import the command module at the top of the bootstrap except as a type. + +## 4. Test + +Build the command with `createCommandFromDefinition(definition, injector)` and stub +its services on a `Yok` test injector (see `test/commands/provide-project.ts`). Option +values come from the stub: `injector.register("options", { json: true })`. Cover the +arguments policy, a refused `canExecute` and each option that changes behaviour. + +```sh +npx tsc --noEmit -p tsconfig.json +npm run build && npx vitest run +node bin/ns --help +node bin/ns --path --profileDir --disableAnalytics +``` + +Also run it outside a project when it needs one, and with a stray argument. diff --git a/.agents/skills/cli-dependency-injection/SKILL.md b/.agents/skills/cli-dependency-injection/SKILL.md new file mode 100644 index 0000000000..75c5b994d3 --- /dev/null +++ b/.agents/skills/cli-dependency-injection/SKILL.md @@ -0,0 +1,91 @@ +--- +name: cli-dependency-injection +description: Guidelines for dependency injection in the NativeScript CLI. Use whenever adding or editing a class, service, controller or helper under lib/ that takes dependencies, registers with the injector, declares a contract or token, or is resolved by name, and when reviewing such a change. Covers inject(), @Contract, @LegacyContract, InjectionToken, providers and how far to modernize code you are already touching. +--- + +# Dependency injection + +`dependency-injection.md` at the repository root is the authority on the API. These +are the rules for using it here. + +The CLI is moving from string-based injection (`$name` parameters, `resolve("name")`) to +typed tokens, **a little at a time, in code that is being changed anyway**. Both reach the +same instance, so a class may mix them for as long as it needs to. + +## New code + +- Depend on a token: `private fs = inject(FileSystem)`, or + `inject(Token)` at the top of a command handler. Add no `$` parameter and no string + lookup for a service that has a token. +- A new service declares `@Contract()` in `lib/contracts/internal/`, with no name, an + implementation called `*Impl`, and a lazy registration in the bootstrap: + `injector.register(provideLazy(Thing, () => require("./path").ThingImpl))`. +- A value that is not a class takes an `InjectionToken`; give it a `factory` if it can + provide itself. +- Do not bundle services into one object that is passed around. + +## Internal and public contracts + +| | Internal | Public | +|---|---|---| +| Lives in | `lib/contracts/internal/` | `lib/contracts/`, exported from `index.ts` | +| For | the CLI's own plumbing | extension and hook authors | +| Its shape | may change in any release | covered by semver | +| Changing a member | change it, and its callers | additive only; deprecate before removing | +| Documentation | optional | JSDoc on every member, and a row in `dependency-injection.md` | +| Mentions in signatures | anything | public contracts and published types only | + +- **Internal is the default.** Making a contract public, or exporting anything new from + `nativescript/contracts`, is a maintainer's decision: ask first, with the author's use + case. Expose the smallest useful shape. Moving an internal contract out later is easy; + taking a public one back is a breaking change. +- `lib/common/contracts/` holds the injector facade's own contracts. Those exported + through `lib/contracts/index.ts` are public; the rest are internal. +- **A name does not make a contract public.** `@LegacyContract({ name })` keeps a string + spelling working. Hooks may still resolve an internal service by that string, so do not + drop or change the name, but its members carry no promise. +- A public contract is named today, because an extension with its own copy of the CLI + cannot resolve one without a name. +- Changing the interface of an internal service is the moment to give it a contract. + Changing a public contract is an API change: say so in the pull request. + +## Code you are already changing + +| You are | Do | +|---|---| +| adding a dependency to a class | `inject()` the new one; leave the others | +| changing a class whose dependencies have tokens | move them if every condition below holds | +| changing a service's interface | give it an internal contract, if it has none | +| changing a public contract | additive changes only, or ask | +| fixing a bug, or touching one line | leave the injection alone | +| not otherwise changing a file | leave it alone | + +Move dependencies only when all of these hold: + +- the class is constructed by the injector everywhere: no `new X(...)`, no + `resolve(X, { $name })`, no subclass that calls `super($name)` +- tests cover what you touch, or you add them +- no open pull request changes the same lines +- the move is small next to your change; put it in its own commit and mention it in + the pull request + +When one does not hold, leave the class as it is and finish your change. Do not widen it. + +## Traps + +- `provide(Token, Impl)` while `Impl` still takes `$` parameters builds it with + `undefined`, silently. Keep `register("name", Impl)` until none are left. +- `inject()` ignores `resolve(X, { $name: stub })` overrides, silently. +- `inject()` throws outside a field initializer, constructor or factory, and after an + `await`. For a late lookup hold `inject(Injector)`. +- Parameter names of `@hook` methods are the hook's payload. Never rename them, and keep + `$hooksService` on such a class. +- A registered string name is public: hooks resolve it, and `@exported` methods do on + every call. Keep it, with `@LegacyContract({ name })`. +- A class with `@performanceLog` methods keeps its class name. +- Importing an implementation in the bootstrap or a contract defeats lazy loading. + +## Recipes + +- [Moving a class to tokens](references/moving-a-class-to-tokens.md) +- [Giving a service a contract](references/giving-a-service-a-contract.md) diff --git a/.agents/skills/cli-dependency-injection/references/giving-a-service-a-contract.md b/.agents/skills/cli-dependency-injection/references/giving-a-service-a-contract.md new file mode 100644 index 0000000000..152d73ee96 --- /dev/null +++ b/.agents/skills/cli-dependency-injection/references/giving-a-service-a-contract.md @@ -0,0 +1,112 @@ +# Giving a service a contract + +Read the "Tokens", "Internal contracts" and "Registering" +sections of `dependency-injection.md` first. The worked example is +`lib/contracts/internal/os-info.ts` with `lib/common/os-info.ts`. + +## 1. Survey + +For a service registered as `thing`: + +```sh +rg -n '"\$?thing"|\$thing\b' lib test # registration, lookups, stubs +rg -n 'interface IThing\b' lib # the declared shape +rg -n '\bThing\b' lib test # imports, subclasses, new Thing() +``` + +List the open pull requests that touch a file: + +```sh +R=NativeScript/nativescript-cli +for n in $(gh pr list -R $R --state open --limit 200 --json number -q '.[].number'); do + gh api --paginate "repos/$R/pulls/$n/files" -q ".[].filename" | sed "s|^|$n |" +done | grep -F lib/services/thing.ts +``` + +If one changes the service's shape, pick another service or ask. + +## 2. Classify + +| Kind | What to do | +|---|---| +| Class with one interface | this recipe | +| Interface shared by several registrations (package managers, platform services, log filters) | one token class per registration, merged with the interface: `@LegacyContract({ name }) export abstract class X {}` plus `export interface X extends IShared {}`; leave the interface alone | +| Value that is not a class (a module, a function) | `InjectionToken`, not a contract | +| `shared: false` registration | keep it transient: `{ provide: Token, useClass: Impl, shared: false }` | +| Class that does not satisfy its interface | stop and report; fix conformance in its own change | +| Nothing uses it | stop and report; hooks can still resolve it by name | + +## 3. Choose the decorator and the place + +- **`@LegacyContract({ name })`** when the service already has a string name. Hooks + and `$` parameters resolve it, so the name stays exactly as registered. +- **`@Contract()`** when it never had one, and for new services. Without a name it + cannot be resolved by string, or through an extension's own copy of the CLI. +- **`lib/contracts/internal/`** is the default; the skill says what separates it from a + public contract. A test fails if a class in it is exported from + `nativescript/contracts`. + +A contract file imports only the decorator and types. It must stay free of side +effects, so it never imports `lib/common/yok` or an implementation. + +## 4. Edit + +1. Declare the contract with the members of the interface, moving their JSDoc. + Correct JSDoc that does not describe the member. For an inherited interface + such as `EventEmitter`, merge it: + `export interface Thing extends NodeJS.EventEmitter {}` next to the class. +2. Make the interface an alias: + `/** @deprecated Kept so existing annotations compile; use the {@link Thing} contract. */` + `interface IThing extends Thing {}`, with an `import type` at the top of the + declaration file. A `.d.ts` without any `import` or `export` is ambient, and + the import turns it into a module: wrap **everything** in it in + `declare global { … }`, as `lib/definitions/prompter.d.ts` does. +3. Rename the class to `ThingImpl implements Thing` and fix imports of the class, + tests included. A class with `@performanceLog` methods keeps its name: the + decorator reports it. The old class export disappears for deep `require()`s; + say so in the pull request. +4. Register it: + - no `$` constructor parameters left: `injector.register(provide(Thing, ThingImpl))` + - any left: keep `injector.register("thing", ThingImpl)`. With `provide()` they + are **silently `undefined`**, because the class is built with no arguments. +5. Leave the `injector.require("thing", "./path")` line in the bootstrap. Never + import an implementation there: modules must stay lazy. A service with no + string name is registered there with + `injector.register(provideLazy(Thing, () => require("./path").ThingImpl))`, + and its module registers nothing. +6. Leave the service's own `$` parameters, and its consumers, unless you are + changing them anyway; then see + [moving a class to tokens](moving-a-class-to-tokens.md). Both spellings reach the same instance, so + consumers can move before or after. + +Keep `@exported` and `@hook` usages and their names unchanged. + +## 5. Verify + +```sh +npx tsc --noEmit -p tsconfig.json +npx tsc -p tsconfig.release.json --noEmit +npm run build && npx vitest run +``` + +Add a test to `test/contracts.ts`: for a service registered with `provide()`, that the +class, the name and the `$`-spelling resolve to one instance, as `OsInfo` does. With +a by-name registration that needs stubs, assert `getContractName(Thing)` instead. + +Check the real registration, and that it is still lazy (both lines must print as +shown): + +```sh +node -e ' +require("./dist/lib/bootstrap"); +const { injector } = require("./dist/lib/common/yok"); +const { Thing } = require("./dist/lib/contracts/internal/thing"); +const loaded = () => Object.keys(require.cache).some((k) => k.endsWith("services/thing.js")); +console.log(loaded()); // false +const a = injector.get(Thing); +console.log(loaded(), a === injector.resolve("$thing")); // true true +process.exit();' +``` + +Report the decorator and folder you chose and why, the consumers left on strings, +and any open pull request that overlaps. diff --git a/.agents/skills/cli-dependency-injection/references/moving-a-class-to-tokens.md b/.agents/skills/cli-dependency-injection/references/moving-a-class-to-tokens.md new file mode 100644 index 0000000000..0932410305 --- /dev/null +++ b/.agents/skills/cli-dependency-injection/references/moving-a-class-to-tokens.md @@ -0,0 +1,78 @@ +# Moving a class to tokens + +For a class you are already changing. Uses tokens that exist; see +[giving a service a contract](giving-a-service-a-contract.md) for a missing one. + +## 1. Pick the replacements + +For every dependency of the file: + +| Today | Replacement | +|---|---| +| `private $fs: IFileSystem` and a contract exists | field `private fs = inject(FileSystem)` | +| `$injector` | `inject(Injector)` | +| `inject("logger")` | `inject(Logger)` | +| `injector.get("logger")`, `injector.resolve("logger")` | `.get(Logger)` on the same injector: do not turn it into `inject()`, it may run after an `await` | +| `$x`, `inject("x")` or `get("x")` with no contract for `x` | leave it, or give `x` a contract first | +| `$options` | leave it; see the cli-options skill | +| a runtime value (`device`, `identifier`) | leave it as a constructor parameter | + +Find the tokens with +`rg -A1 'Contract\(|new InjectionToken' lib/contracts lib/common/contracts`. Import +a token from the module that declares it, never through `lib/contracts/index.ts`. +Check the file against the open pull requests, as the contract recipe shows. + +A partly migrated class is fine: `$` parameters and `inject()` fields reach the +same instance. + +## 2. Check for these before editing + +1. **`new X(...)`**: `rg 'new X\(' lib test`. `inject()` throws outside an injection + context, so such a call has to become `injector.resolve(X)` or + `runInInjectionContext(injector, () => new X(...))`. +2. **Per-call overrides**: search `rg 'resolve\(X,' lib test`. `resolve(X, { $logger: stub })` + reaches `$` parameters only. `inject()` ignores it *silently* and gets the registered service. Change + it to `createInstance(X, [{ provide: Logger, useValue: stub }])`, or leave that + dependency as a parameter. A runtime value passed this way keeps working. +3. **Subclasses**: `rg 'extends X\b' lib test`, and the class's own base. When a base + constructor loses a parameter, every `super(...)` call changes in the same + commit. +4. **Use after an `await`, or later in a method**: `inject()` is valid only in field + initializers, constructors and factories. For a late or conditional lookup, + hold `inject(Injector)` and call `get()`. A cycle between two services is + broken the same way; keep an existing late `$injector.resolve` late. +5. **`@hook` methods**: never rename a parameter of the method. Parameter names are + the hook's payload. Keep `$hooksService` (or `$injector`) as it is: without + it the decorator falls back to the process-wide injector and the test's stub + is bypassed. +6. **`@exported` classes**: the registered name must not change. It is resolved on + every public API call. +7. **Tests that assign `service.$x = stub`**: they stop having an effect. Register + the stub on the test injector instead. + +## 3. Edit + +- Field initializers run before the constructor body, so a field can be used there. +- In services the field has no `$`: `private osInfo = inject(OsInfo)`. In commands + keep the `$` the file already uses. +- Delete the interface import the parameter used, if nothing else needs it. +- Do not touch registrations, do not rename the class, and do not reformat lines + you did not change. +- Fields resolve after `$` parameters. If a constructor has side effects, check that + the order in which its dependencies are built does not matter. +- `service.$x` is gone for anyone reading it from outside: search for it. +- Behaviour must not change. Bugs noticed on the way are reported, not fixed. + +## 4. Verify + +```sh +npx tsc --noEmit -p tsconfig.json +npm run build && npx vitest run +``` + +Tests run from `dist/`, so always build first. Then check the class itself: resolve it +from `dist/lib/bootstrap` and call what you touched, or run a command that reaches +it with `node bin/ns`. If it has no tests and needs a device, add a small unit test +of the method you touched, and say what was not exercised. + +Report what moved, what stayed on strings and why. diff --git a/.agents/skills/cli-options/SKILL.md b/.agents/skills/cli-options/SKILL.md new file mode 100644 index 0000000000..547963f4e8 --- /dev/null +++ b/.agents/skills/cli-options/SKILL.md @@ -0,0 +1,64 @@ +--- +name: cli-options +description: Guidelines for command-line options in the NativeScript CLI. Use whenever adding or changing an option, reading $options, ctx.options or an option group, or passing option values to a service, and when reviewing such a change. Covers defineOptions groups, CliOptions, data objects and how far to modernize code you are already touching. +--- + +# Command-line options + +`defining-commands.md` ("Options", "Option groups", "Injecting a group") is the authority. + +Services are moving off the process-wide `$options` object, **in code that is being changed +anyway**. Add no new `$options.x` read. + +## Where a value comes from + +Use the first that fits: + +1. `path`, `log`, `verbose`, `version`, `profileDir`, `analyticsClient`, `config`: + `inject(CliOptions)`. `help` stays on `$options`. +2. In a command: `ctx.options` or `this.options`. +3. A method that receives an object built for the operation (`buildData`, `prepareData`, + `liveSyncInfo`, `projectData`, …): a typed field on it. +4. Called by the command itself: a parameter. +5. Otherwise an option group: `defineOptions({ … })` in `lib/option-groups/`, injected. + +Anything a watcher or device callback reads, or a nested command may want to change, +belongs in 3 or 4. + +## Code you are already changing + +| You are | Do | +|---|---| +| adding an option | declare it on the command; give services its value by the order above | +| adding a read to a service | use the order above, even if its other reads use `$options` | +| changing the code around a `$options` read | move that read, if the checks below pass | +| fixing a bug, or touching one line | leave it | + +Before moving a read to a group: + +- every command that supports the option and reaches the read lists the group +- no command writes the option (the recipe has the search and the known writers) +- nothing calls the method before the command line is parsed, such as from a + `before-resolveCommand` hook + +If one fails, use a data object or leave the read. List the moved options in the pull +request: a hook that assigned to `$options` no longer affects them. That is intended. +Hooks change an operation through its payload. + +## Rules for groups + +- A command **lists** the group: `options: [Group, { … }]`. Spreading `...Group.schema` does + not count. A group the typed command does not list reads as its defaults, which is what + keeps two options with one spelling apart. +- One group per meaning. `--sdk` is a simulator version for one command and an Android + target for another, so it is two groups. A command cannot list two groups that share a + spelling; put an option several topics need into a group of its own. +- Keep the object and read it inside methods. Destructuring it in a field or + constructor reads too early and throws. +- A group is read-only, holds the typed command's values, and nothing changes them later: + no hook, no command run in process, no assignment to `$options`. In a library process it + reads as its defaults. Do not mutate an object value such as `env`. +- Never redeclare a `CliOptions` spelling. List `CliOptions` on the command instead. +- In tests, register the value under the group. + +Recipe: [moving reads off `$options`](references/moving-reads-off-options.md). diff --git a/.agents/skills/cli-options/references/moving-reads-off-options.md b/.agents/skills/cli-options/references/moving-reads-off-options.md new file mode 100644 index 0000000000..18373b2ae0 --- /dev/null +++ b/.agents/skills/cli-options/references/moving-reads-off-options.md @@ -0,0 +1,93 @@ +# Moving reads off `$options` + +For reads in code you are already changing. Read "Option groups", +"Injecting a group" and "Process-level options" in `defining-commands.md` first. +The worked example is `lib/helpers/android-bundle-validator-helper.ts` with +`lib/option-groups/android-bundle-options.ts`. + +## 1. Choose where each value comes from + +Use the order in the skill. A group is for values that would otherwise be threaded +through callers that do not use them. + +## 2. Stop before a group if the option is written + +A group is read-only and fixed when the typed command is parsed, so it does not see +assignments to `$options`. Check with: + +```sh +rg -n -t ts '\$options\.(argv\.)?\w+(\.\w+)?\s*=[^=>]|\.\.\.(this\.)?\$options\.argv' lib +``` + +The second pattern finds commands that copy the whole command line with one value +changed (`{ ...$options.argv, watch: false }`). Known writers: + +| Option | Writer | +|---|---| +| `platformOverride`, `watch` | `lib/commands/open.ts` | +| `env` | `lib/commands/test.ts` | +| `hostProjectPath`, `hostProjectModuleName` | `lib/commands/embedding/embed.ts` | +| `release`, `provision` | `lib/commands/appstore-upload.ts` | + +Change the writer to pass the value before moving a reader to a group. A data object +is fine as long as it is filled in after the write. Also leave `$options.argv` +(whole-line reads) and `$options.options` alone. + +**Hooks** that assign to `$options` stop affecting a moved option. That is intended: a hook +changes an operation through its payload. When hooks have a reason to change the value +(SDK versions, build settings), prefer a data object they receive. Name the moved options +in the pull request. + +**Early reads**: a group also throws when a method runs before the command line is +parsed, for example from a `before-resolveCommand` hook. A service such code may +call keeps `$options`, or uses `CliOptions`. + +A command run in process does not change a group. A command that dispatches +another, or needs a service to act on different values, passes them as parameters. + +## 3. Edit + +1. Declare the group in `lib/option-groups/-options.ts`. One group per topic + shared by its readers, not one per service, and only options that the same + commands declare: a command that uses a group declares all of it. One spelling with + two meanings (`sdk`) needs two groups. + + ```ts + export const AndroidBundleOptions = defineOptions({ aab: booleanOption() }); + ``` + + Copy the type, alias, default and sensitivity from the commands that declare the + option and from the table in `lib/options.ts`. A group's `default` is only used + when the typed command does not give the option a value. +2. List the group in **every command that supports the option** and can reach the read: + `options: [Group, { … }]`. Do not spread `...Group.schema`: an unlisted group reads as + its defaults. Remove the option from the command's inline schema. Many options are + declared by no command and only sit in the table in `lib/options.ts`; find the commands + by following the read to its callers. Never redeclare a `CliOptions` spelling. +3. In the service: `private options = inject(AndroidBundleOptions)`, then + `this.options.aab` **inside methods**. Do not destructure or read it in a field or + constructor: services are often built before the command line is parsed, and + reading that early throws. +4. Remove the `$options` parameter when nothing else in the class uses it. If the + class is constructed with `new` or has subclasses, see the + cli-dependency-injection skill. +5. Do not mutate an object value such as `env`; the contents are shared. +6. Leave `$options` and `IOptions` registered and typed: hooks and plugins use them. + +## 4. Verify + +In tests, provide the value: +`injector.register({ provide: Group, useValue: { aab: true } })`. Without it, reading the +group off a stub registered as `"options"` throws `readGroupOption is not a function`. + +```sh +npx tsc --noEmit -p tsconfig.json +npm run build && npx vitest run +``` + +Run the real command with and without the flag, in a scratch project: +`node bin/ns --path --profileDir --disableAnalytics`. +When that needs a device or an SDK, resolve the service from `dist/lib/bootstrap` instead +and say so. Watch for a value memoised by `@cache()`. + +Report which rule each read used, which reads stayed and why. diff --git a/.claude/skills/cli-commands b/.claude/skills/cli-commands new file mode 120000 index 0000000000..8c8ab61937 --- /dev/null +++ b/.claude/skills/cli-commands @@ -0,0 +1 @@ +../../.agents/skills/cli-commands \ No newline at end of file diff --git a/.claude/skills/cli-dependency-injection b/.claude/skills/cli-dependency-injection new file mode 120000 index 0000000000..6a48b89294 --- /dev/null +++ b/.claude/skills/cli-dependency-injection @@ -0,0 +1 @@ +../../.agents/skills/cli-dependency-injection \ No newline at end of file diff --git a/.claude/skills/cli-options b/.claude/skills/cli-options new file mode 120000 index 0000000000..7b24bbadf7 --- /dev/null +++ b/.claude/skills/cli-options @@ -0,0 +1 @@ +../../.agents/skills/cli-options \ No newline at end of file diff --git a/defining-commands.md b/defining-commands.md index 6f3e4e0398..6a7a397e48 100644 --- a/defining-commands.md +++ b/defining-commands.md @@ -204,8 +204,9 @@ export default defineCommand({ ``` `ctx.options` is typed as the merged values of every part. The class form -takes the same list, and types `this.options` the same way. A command that -keeps a single schema object can spread a group's: `...WidgetOptions.schema`. +takes the same list, and types `this.options` the same way. List +the group itself: spreading `...WidgetOptions.schema` declares the options, but the +command does not list the group, so services reading it get the defaults. A group has no name: the exported object is the token, so declare it once and import it wherever it is listed or injected. @@ -235,16 +236,20 @@ class WidgetRenderer { fine; reading a property that early throws `The option 'compact' was read before the command line was parsed`. So keep the object and read it in the method that needs it. Do not destructure it in a field or a constructor. +- **Only a command that lists the group gives it values.** When the typed command + does not list it, every option reads as the group's `default`. Two groups may + therefore use one spelling for different things: each gets a value only from the + commands that list it. - **The values never change.** They are fixed when the typed command is parsed, - are read-only, and are the same in every later callback. Assigning to the - options service does not change them. + are read-only, and are the same in every later callback. Nothing that assigns to + the options service changes them, hooks included; a hook changes an operation + through its payload. - **A command run in process does not change them.** Its own `ctx.options` holds its own values and defaults; a service still reads the typed command's. A command that needs a service to act on other values passes them to it. -- **An option that was not given** reads as the group's `default`. When the - typed command declares the option, its declaration decides. +- **An option that was not given** reads as the group's `default`. - **A process that uses the CLI as a library** has no typed command, so reading - never throws and returns the options service's current value. + never throws and returns the defaults. Prefer a parameter when the method already receives a data object that can carry the value; inject a group where passing it would mean threading it @@ -261,6 +266,10 @@ identical spec: the same type, `default`, `alias` and `hasSensitiveValue`. `description` is not compared. An alias may not equal another option's name or alias. +Two groups listed by one command may not share a spelling at all, whatever their +specs: both would read the same value. Put an option several groups need into a +group of its own. + `defineCommand` and `Command()` check this when they are called, and `defineOptions` checks it within its own schema. The message names both declarations: diff --git a/lib/commands/build.ts b/lib/commands/build.ts index d39e5218e0..472ad19f8e 100644 --- a/lib/commands/build.ts +++ b/lib/commands/build.ts @@ -19,6 +19,7 @@ import { IMigrateController } from "../definitions/migrate"; import { booleanOption, CommandName, + CommandOptionsInput, CommandOptionsSchema, defineCommand, stringOption, @@ -33,18 +34,20 @@ import { ProjectData } from "../contracts/project-data"; */ type BuildPlatform = "iOS" | "Android" | "visionOS"; -const buildCommandOptions = { - ...platformSigningOptions, - watch: booleanOption({ default: false }), - hmr: booleanOption({ default: false }), - force: booleanOption(), - release: booleanOption(), - ...AndroidBundleOptions.schema, - keyStorePath: stringOption(), - keyStorePassword: stringOption(), - keyStoreAlias: stringOption(), - keyStoreAliasPassword: stringOption(), -} satisfies CommandOptionsSchema; +const buildCommandOptions = [ + AndroidBundleOptions, + { + ...platformSigningOptions, + watch: booleanOption({ default: false }), + hmr: booleanOption({ default: false }), + force: booleanOption(), + release: booleanOption(), + keyStorePath: stringOption(), + keyStorePassword: stringOption(), + keyStoreAlias: stringOption(), + keyStoreAliasPassword: stringOption(), + } satisfies CommandOptionsSchema, +] satisfies CommandOptionsInput; const defineBuildCommand = ( name: TName, diff --git a/lib/commands/debug.ts b/lib/commands/debug.ts index d950b442a6..eea9a72d66 100644 --- a/lib/commands/debug.ts +++ b/lib/commands/debug.ts @@ -4,6 +4,7 @@ import { booleanOption, CommandContext, CommandName, + CommandOptionsInput, CommandOptionsSchema, defineCommand, stringOption, @@ -38,22 +39,24 @@ import { ProjectData } from "../contracts/project-data"; /** Which `$devicePlatformsConstants` entry a command debugs. */ type DebugPlatform = "iOS" | "Android" | "visionOS"; -const debugCommandOptions = { - ...platformSigningOptions, - force: booleanOption(), - release: booleanOption(), - ...AndroidBundleOptions.schema, - start: booleanOption(), - emulator: booleanOption(), - forDevice: booleanOption(), - inspector: booleanOption(), - device: stringOption(), - timeout: stringOption(), - keyStorePath: stringOption(), - keyStorePassword: stringOption(), - keyStoreAlias: stringOption(), - keyStoreAliasPassword: stringOption(), -} satisfies CommandOptionsSchema; +const debugCommandOptions = [ + AndroidBundleOptions, + { + ...platformSigningOptions, + force: booleanOption(), + release: booleanOption(), + start: booleanOption(), + emulator: booleanOption(), + forDevice: booleanOption(), + inspector: booleanOption(), + device: stringOption(), + timeout: stringOption(), + keyStorePath: stringOption(), + keyStorePassword: stringOption(), + keyStoreAlias: stringOption(), + keyStoreAliasPassword: stringOption(), + } satisfies CommandOptionsSchema, +] satisfies CommandOptionsInput; type DebugCommandContext = CommandContext; diff --git a/lib/commands/deploy.ts b/lib/commands/deploy.ts index 204f536d12..3273e631a3 100644 --- a/lib/commands/deploy.ts +++ b/lib/commands/deploy.ts @@ -13,6 +13,7 @@ import { hasValidAndroidSigning } from "../common/helpers"; import { IMigrateController } from "../definitions/migrate"; import { booleanOption, + CommandOptionsInput, CommandOptionsSchema, defineCommand, stringOption, @@ -21,18 +22,20 @@ import { AndroidBundleOptions } from "../option-groups/android-bundle-options"; import { inject } from "../common/di"; import { ProjectData } from "../contracts/project-data"; -const deployCommandOptions = { - ...platformSigningOptions, - watch: booleanOption({ default: false }), - hmr: booleanOption({ default: false }), - force: booleanOption(), - release: booleanOption(), - ...AndroidBundleOptions.schema, - keyStorePath: stringOption(), - keyStorePassword: stringOption(), - keyStoreAlias: stringOption(), - keyStoreAliasPassword: stringOption(), -} satisfies CommandOptionsSchema; +const deployCommandOptions = [ + AndroidBundleOptions, + { + ...platformSigningOptions, + watch: booleanOption({ default: false }), + hmr: booleanOption({ default: false }), + force: booleanOption(), + release: booleanOption(), + keyStorePath: stringOption(), + keyStorePassword: stringOption(), + keyStoreAlias: stringOption(), + keyStoreAliasPassword: stringOption(), + } satisfies CommandOptionsSchema, +] satisfies CommandOptionsInput; export const deployCommandDefinition = defineCommand({ name: "deploy", diff --git a/lib/commands/run.ts b/lib/commands/run.ts index e872529ad1..b9653a7148 100644 --- a/lib/commands/run.ts +++ b/lib/commands/run.ts @@ -4,6 +4,7 @@ import { booleanOption, CommandContext, CommandName, + CommandOptionsInput, CommandOptionsSchema, defineCommand, stringOption, @@ -29,16 +30,18 @@ import { import { platformSigningOptions, provideProject } from "./command-base"; import { ProjectData } from "../contracts/project-data"; -const runCommandOptions = { - ...platformSigningOptions, - force: booleanOption(), - release: booleanOption(), - ...AndroidBundleOptions.schema, - keyStorePath: stringOption(), - keyStorePassword: stringOption(), - keyStoreAlias: stringOption(), - keyStoreAliasPassword: stringOption(), -} satisfies CommandOptionsSchema; +const runCommandOptions = [ + AndroidBundleOptions, + { + ...platformSigningOptions, + force: booleanOption(), + release: booleanOption(), + keyStorePath: stringOption(), + keyStorePassword: stringOption(), + keyStoreAlias: stringOption(), + keyStoreAliasPassword: stringOption(), + } satisfies CommandOptionsSchema, +] satisfies CommandOptionsInput; type RunCommandContext = CommandContext; diff --git a/lib/commands/test.ts b/lib/commands/test.ts index 7a37453900..34da74965d 100644 --- a/lib/commands/test.ts +++ b/lib/commands/test.ts @@ -6,6 +6,7 @@ import { import { booleanOption, CommandContext, + CommandOptionsInput, CommandOptionsSchema, defineCommand, stringOption, @@ -32,32 +33,34 @@ import { provideProject } from "./command-base"; /** The platform spelling the test services receive, verbatim. */ type TestPlatform = "android" | "iOS" | "visionOS"; -const testCommandOptions = { - // The CLI-wide default is true; unit testing has always opted out of it. - hmr: booleanOption({ default: false }), - force: booleanOption(), - // Watch mode keeps the run alive waiting for changes; CI runs must - // execute once and exit, so --watch defaults to off there. The schema is - // module-level, so the environment is read lazily at command resolution. - watch: { - type: "boolean", - get default(): boolean { - return !isCIEnvironment(); +const testCommandOptions = [ + AndroidBundleOptions, + { + // The CLI-wide default is true; unit testing has always opted out of it. + hmr: booleanOption({ default: false }), + force: booleanOption(), + // Watch mode keeps the run alive waiting for changes; CI runs must + // execute once and exit, so --watch defaults to off there. The schema is + // module-level, so the environment is read lazily at command resolution. + watch: { + type: "boolean", + get default(): boolean { + return !isCIEnvironment(); + }, }, - }, - justlaunch: booleanOption(), - debugBrk: booleanOption(), - device: stringOption(), - emulator: booleanOption(), - forDevice: booleanOption(), - sdk: stringOption(), - release: booleanOption(), - ...AndroidBundleOptions.schema, - keyStorePath: stringOption(), - keyStorePassword: stringOption(), - keyStoreAlias: stringOption(), - keyStoreAliasPassword: stringOption(), -} satisfies CommandOptionsSchema; + justlaunch: booleanOption(), + debugBrk: booleanOption(), + device: stringOption(), + emulator: booleanOption(), + forDevice: booleanOption(), + sdk: stringOption(), + release: booleanOption(), + keyStorePath: stringOption(), + keyStorePassword: stringOption(), + keyStoreAlias: stringOption(), + keyStoreAliasPassword: stringOption(), + } satisfies CommandOptionsSchema, +] satisfies CommandOptionsInput; type TestCommandContext = CommandContext; diff --git a/lib/common/define-command.ts b/lib/common/define-command.ts index 2c727dedf9..7aa30ee425 100644 --- a/lib/common/define-command.ts +++ b/lib/common/define-command.ts @@ -103,7 +103,11 @@ export type OptionsGroupSource = "commandLine" | "startup"; /** What a group reads its values from; the options service implements it. */ export interface OptionValueReader { - readGroupOption(optionName: string, source: OptionsGroupSource): any; + readGroupOption( + group: OptionsGroup, + optionName: string, + source: OptionsGroupSource, + ): any; } const spellingOf = (optionName: string): string => @@ -114,7 +118,9 @@ const spellingOf = (optionName: string): string => * group under `options` and the parser fills it; a service injects the group * and reads the parsed values, typed from the same declaration. The group is * its own token and provides itself at the root, so it can be injected at any - * time; its values can be read once the command line is parsed. + * time; its values can be read once the command line is parsed. Only a command + * that lists the group gives it values: two groups may use one spelling, so a + * group the typed command does not list reads as its defaults. */ export class OptionsGroup< TSchema extends CommandOptionsSchema = CommandOptionsSchema, @@ -125,7 +131,10 @@ export class OptionsGroup< public readonly schema: TSchema, source: OptionsGroupSource = "commandLine", ) { - super({ factory: () => createGroupValues(schema, source) }); + // `this` does not exist until super() returns; the factory runs later. + let group: OptionsGroup; + super({ factory: () => createGroupValues(group, source) }); + group = this; } public toString(): string { @@ -136,9 +145,10 @@ export class OptionsGroup< // Getters rather than values: a service built before the command line is // parsed may hold the group, and reads it afterwards. function createGroupValues( - schema: TSchema, + group: OptionsGroup, source: OptionsGroupSource, ): Readonly> { + const { schema } = group; const injector = getCurrentInjector(); const values: any = {}; for (const optionName of Object.keys(schema)) { @@ -147,7 +157,7 @@ function createGroupValues( get: () => { const value = injector .get("options") - .readGroupOption(optionName, source); + .readGroupOption(group, optionName, source); return value === undefined ? schema[optionName].default : value; }, }); @@ -217,14 +227,19 @@ const sameOptionSpec = (a: CommandOptionSpec, b: CommandOptionSpec): boolean => * Merges what `options` declares into one schema. A spelling — a name or an * alias — may be declared once, or again with the same spec; two specs for one * spelling would leave the parser with one meaning and the other declaration - * silently wrong, so that is reported instead. + * silently wrong, so that is reported instead. So are two groups that share a + * spelling, even with the same spec: they would both read one value. */ export function resolveCommandOptions( options: CommandOptionsInput | undefined, report: (problem: string) => never, inlineSource: string = "the command's own options", ): ResolvedCommandOptions { - const parts: { source: string; schema: CommandOptionsSchema }[] = []; + const parts: { + source: string; + schema: CommandOptionsSchema; + isGroup?: boolean; + }[] = []; const groups = new Set>(); const list: ReadonlyArray | CommandOptionsSchema> = options === undefined @@ -240,6 +255,7 @@ export function resolveCommandOptions( parts.push({ source: String(part), schema: part.schema, + isGroup: true, }); } } else { @@ -251,10 +267,19 @@ export function resolveCommandOptions( const schema: CommandOptionsSchema = Object.create(null); const owners: IDictionary<{ optionName: string; source: string }> = Object.create(null); - for (const { source, schema: partSchema } of parts) { + const groupOwners = new Map(); + for (const { source, schema: partSchema, isGroup } of parts) { for (const optionName of Object.keys(partSchema)) { const spec = partSchema[optionName]; const existing = schema[optionName]; + if (isGroup && groupOwners.has(optionName)) { + report( + `option '--${optionName}' is declared by two option groups, ${groupOwners.get(optionName)} and ${source}; a command gives one spelling to one group`, + ); + } + if (isGroup) { + groupOwners.set(optionName, source); + } if (existing && !sameOptionSpec(existing, spec)) { report( `option '--${optionName}' is declared by ${owners[optionName].source} and by ${source} with different specs`, diff --git a/lib/common/definitions/commands.d.ts b/lib/common/definitions/commands.d.ts index c72e3f52cd..db528b002c 100644 --- a/lib/common/definitions/commands.d.ts +++ b/lib/common/definitions/commands.d.ts @@ -16,6 +16,8 @@ interface ICommand extends ICommandOptions { /** @deprecated Declared here, referenced nowhere. */ completionData?: string[]; dashedOptions?: IDictionary; + /** The option groups the command lists. */ + optionGroups?: readonly object[]; isHierarchicalCommand?: boolean; /** diff --git a/lib/common/services/command-definition-adapter.ts b/lib/common/services/command-definition-adapter.ts index 77ecd9b9e0..288102b59d 100644 --- a/lib/common/services/command-definition-adapter.ts +++ b/lib/common/services/command-definition-adapter.ts @@ -535,6 +535,7 @@ export function createCommandFromDefinition< return { allowedParameters: [], dashedOptions, + optionGroups: parts.filter(isOptionsGroup), ...(definition.disableAnalytics === undefined ? {} : { disableAnalytics: definition.disableAnalytics }), diff --git a/lib/common/services/commands-service.ts b/lib/common/services/commands-service.ts index 04ab1b8c71..25d9d3ec15 100644 --- a/lib/common/services/commands-service.ts +++ b/lib/common/services/commands-service.ts @@ -263,13 +263,47 @@ export class CommandsService this.$options.validateOptions( dashedOptions, command && allowsUnknownOptions(command), - !this.isExecutingInProcess, + this.isExecutingInProcess + ? undefined + : (command && command.optionGroups) || [], ); + } else if (!this.isExecutingInProcess) { + this.recordSubcommandOptions(commandName, commandArguments); } return this.canExecuteResolvedCommand(commandName, commandArguments); } + /** + * A parent's hooks run before the subcommand is dispatched and its options + * are validated, and may reach a service that reads an option group. The + * parser is put back: what the subcommand declares is not in force yet. + */ + private recordSubcommandOptions( + parentName: string, + commandArguments: string[], + ): void { + const subcommand = this.$injector.buildHierarchicalCommand( + parentName, + commandArguments, + ); + const command = + subcommand && this.$injector.resolveCommand(subcommand.commandName); + if (!command || command.isHierarchicalCommand) { + return; + } + + const restoreOptions = this.saveOptions(); + try { + this.$options.recordCommandLine( + command.dashedOptions, + command.optionGroups || [], + ); + } finally { + restoreOptions(); + } + } + public async tryExecuteCommand( commandName: string, commandArguments: string[], @@ -542,6 +576,16 @@ export class CommandsService }; } + /** Returns a function that puts the parser back to its state now. */ + private saveOptions(): () => void { + const declaredOptions = { ...this.$options.options }; + const parsedArgv = this.$options.argv; + return (): void => { + this.$options.options = declaredOptions; + this.$options.argv = parsedArgv; + }; + } + /** * Merging a command's options into the parser rewrites the values the host * process is still running on: a declared default replaces the CLI-wide one @@ -549,12 +593,7 @@ export class CommandsService * done. An in-process dispatch has to put the parser back where it found it. */ private primeOptions(command: ICommand): () => void { - const declaredOptions = { ...this.$options.options }; - const parsedArgv = this.$options.argv; - const restore = (): void => { - this.$options.options = declaredOptions; - this.$options.argv = parsedArgv; - }; + const restore = this.saveOptions(); // validateOptions merges the command's declarations into the live table // before it can throw, so a failed priming has to be undone here. diff --git a/lib/declarations.d.ts b/lib/declarations.d.ts index d991028f54..d3ff82085f 100644 --- a/lib/declarations.d.ts +++ b/lib/declarations.d.ts @@ -615,13 +615,21 @@ interface IOptions ITypingsOptions { argv: IYargArgv; /** - * @param isCommandLine The options are those of the command the user typed, - * so option groups take their values from this parse. + * @param commandLineGroups Given for the command the user typed: the option + * groups it lists, which take their values from this parse. */ validateOptions( commandSpecificDashedOptions?: IDictionary, allowUnknownOptions?: boolean, - isCommandLine?: boolean, + commandLineGroups?: readonly object[], + ): void; + /** + * Parses the options of the command the user typed and fixes the values its + * option groups read, without validating anything. + */ + recordCommandLine( + commandSpecificDashedOptions: IDictionary, + commandLineGroups: readonly object[], ): void; options: IDictionary; shorthands: string[]; diff --git a/lib/options.ts b/lib/options.ts index 3395c70f01..1453e8e937 100644 --- a/lib/options.ts +++ b/lib/options.ts @@ -16,6 +16,7 @@ import { CliOptions } from "./common/contracts/cli-options"; import { COMMAND_LINE_EXPECTED } from "./common/contracts/command-line-expected"; import { compileOptionsSchema, + OptionsGroup, OptionsGroupSource, OptionValueReader, } from "./common/define-command"; @@ -33,6 +34,7 @@ export class Options implements OptionValueReader { private initialArgv: yargs.Arguments; private startupArgv: yargs.Arguments; private commandLineArgv: yargs.Arguments; + private commandLineGroups: ReadonlySet; private commandLineExpected = inject(COMMAND_LINE_EXPECTED); public argv: yargs.Arguments; public options: IDictionary; @@ -266,7 +268,7 @@ export class Options implements OptionValueReader { public validateOptions( commandSpecificDashedOptions?: IDictionary, allowUnknownOptions?: boolean, - isCommandLine?: boolean, + commandLineGroups?: readonly object[], ): void { this.setupOptions(commandSpecificDashedOptions); @@ -326,22 +328,42 @@ export class Options implements OptionValueReader { } } - if (isCommandLine && !this.commandLineArgv) { + if (commandLineGroups) { + this.fixCommandLine(commandLineGroups); + } + } + + public recordCommandLine( + commandSpecificDashedOptions: IDictionary, + commandLineGroups: readonly object[], + ): void { + this.setupOptions(commandSpecificDashedOptions); + this.fixCommandLine(commandLineGroups); + } + + private fixCommandLine(groups: readonly object[]): void { + if (!this.commandLineArgv) { this.commandLineArgv = _.cloneDeep(this.argv); + this.commandLineGroups = new Set(groups); } } /** - * The value an option group reads. A process that runs a command line gets - * the values of the command the user typed, fixed from the moment they are - * parsed; a library process never parses one and reads the live table. + * The value an option group reads: that of the command the user typed, fixed + * when it was parsed. Undefined, so that the group reads its default, when + * that command does not list the group, and in a process that uses the CLI + * as a library and has no typed command. */ - public readGroupOption(optionName: string, source: OptionsGroupSource): any { + public readGroupOption( + group: OptionsGroup, + optionName: string, + source: OptionsGroupSource, + ): any { if (source === "startup") { return this.startupArgv[optionName]; } if (!this.commandLineExpected) { - return this.getOptionValue(optionName); + return undefined; } if (!this.commandLineArgv) { throw new Error( @@ -349,7 +371,9 @@ export class Options implements OptionValueReader { `Inject the option group and read it when it is needed.`, ); } - return this.commandLineArgv[optionName]; + return this.commandLineGroups.has(group) + ? this.commandLineArgv[optionName] + : undefined; } // The name every spelling of an option collapses to. Unknown options keep diff --git a/test/commands-service.ts b/test/commands-service.ts index 028624ed20..d7ae01858c 100644 --- a/test/commands-service.ts +++ b/test/commands-service.ts @@ -9,7 +9,7 @@ interface ITestSetup { validatedWith: { called: boolean; allowUnknown?: boolean; - isCommandLine?: boolean; + commandLineGroups?: readonly object[]; }; } @@ -18,7 +18,7 @@ function createTestInjector(command: ICommand): ITestSetup { const validatedWith: { called: boolean; allowUnknown?: boolean; - isCommandLine?: boolean; + commandLineGroups?: readonly object[]; } = { called: false, }; @@ -37,11 +37,11 @@ function createTestInjector(command: ICommand): ITestSetup { validateOptions: ( dashedOptions: any, allowUnknown?: boolean, - isCommandLine?: boolean, + commandLineGroups?: readonly object[], ): void => { validatedWith.called = true; validatedWith.allowUnknown = allowUnknown; - validatedWith.isCommandLine = isCommandLine; + validatedWith.commandLineGroups = commandLineGroups; }, }); injector.register("staticConfig", {}); @@ -92,9 +92,9 @@ function createDispatchInjector(command: ICommand): { validateOptions( dashedOptions: any, allowUnknown?: boolean, - isCommandLine?: boolean, + commandLineGroups?: readonly object[], ): void { - record.commandLineParses += isCommandLine ? 1 : 0; + record.commandLineParses += commandLineGroups ? 1 : 0; record.primedWith.push({ dashedOptions, allowUnknown }); // The real parser merges the command's declarations into the shared // table and re-parses, replacing both. @@ -193,7 +193,20 @@ describe("commands-service", () => { await (service).tryExecuteCommandAction("info", []); assert.isTrue(validatedWith.called); - assert.isTrue(validatedWith.isCommandLine); + assert.deepEqual(validatedWith.commandLineGroups, []); + }); + + it("passes the option groups the typed command lists", async () => { + const group = {}; + const { injector, validatedWith } = createTestInjector({ + ...baseCommand, + optionGroups: [group], + }); + const commandsService: any = injector.resolve(CommandsService); + + await commandsService.tryExecuteCommandAction("command", []); + + assert.strictEqual(validatedWith.commandLineGroups[0], group); }); it("tolerates unknown options for a command that forwards them", async () => { diff --git a/test/define-command.ts b/test/define-command.ts index 96557600e0..d6a1ae6c70 100644 --- a/test/define-command.ts +++ b/test/define-command.ts @@ -698,6 +698,7 @@ describe("defineCommand", () => { testInjector.register("optionsTracker", {}); testInjector.register("options", { validateOptions: (): void => undefined, + recordCommandLine: (): void => undefined, }); testInjector.register("commandsService", CommandsService); const keyShortcutService = keyShortcutServiceStub(); @@ -1352,6 +1353,7 @@ describe("defineCommand", () => { validateOptions: (dashedOptions: any) => { validatedOptions = dashedOptions; }, + recordCommandLine: (): void => undefined, }); testInjector.register("commandsService", CommandsService); return testInjector; @@ -1514,6 +1516,7 @@ describe("defineCommand", () => { testInjector.register("optionsTracker", {}); testInjector.register("options", { validateOptions: (): void => undefined, + recordCommandLine: (): void => undefined, }); testInjector.register("commandsService", CommandsService); return testInjector; @@ -3547,7 +3550,8 @@ describe("defineCommand", () => { describe("injected values", () => { const reader = (values: any) => ({ - readGroupOption: (optionName: string): any => values[optionName], + readGroupOption: (_group: any, optionName: string): any => + values[optionName], }); it("need no registration and are shared by the whole injector tree", () => { @@ -3632,6 +3636,22 @@ describe("defineCommand", () => { }); }); + it("reports the listed groups, and not the inline or spread schemas", () => { + const Listed = runOptions(); + const Spread = defineOptions({ spread: booleanOption() }); + const command = createCommandFromDefinition( + defineCommand({ + name: "dctest-grp-listed", + options: [Listed, { ...Spread.schema, extra: booleanOption() }], + run: (): void => undefined, + }), + createTestInjector(), + ); + + assert.lengthOf(command.optionGroups, 1); + assert.strictEqual(command.optionGroups[0], Listed); + }); + it("compiles every part into dashedOptions", () => { const RunOptions = runOptions(); const command = createCommandFromDefinition( @@ -3656,9 +3676,6 @@ describe("defineCommand", () => { const Shared = defineOptions({ watch: booleanOption({ default: true }), }); - const Other = defineOptions({ - watch: booleanOption(), - }); assert.throws( () => @@ -3669,15 +3686,28 @@ describe("defineCommand", () => { }), /^Invalid command definition for 'dctest-grp-clash-inline': option '--watch' is declared by option group \(--watch\) and by the command's own options with different specs/, ); - assert.throws( - () => - defineCommand({ - name: "dctest-grp-clash-groups", - options: [Shared, Other], - run: (): void => undefined, - }), - /option '--watch' is declared by option group \(--watch\) and by option group \(--watch\) with different specs/, - ); + }); + + it("rejects two groups that share a spelling, whatever their specs", () => { + const Simulator = defineOptions({ sdk: stringOption() }); + const Target = defineOptions({ sdk: stringOption() }); + const OtherSpec = defineOptions({ sdk: stringOption({ alias: "S" }) }); + const listing = (options: any) => () => + defineCommand({ + name: "dctest-grp-two", + options, + run: (): void => undefined, + }); + const inline = { sdk: stringOption() }; + const message = + /option '--sdk' is declared by two option groups, option group \(--sdk\) and option group \(--sdk\)/; + + assert.throws(listing([Simulator, Target]), message); + assert.throws(listing([Simulator, OtherSpec]), message); + assert.throws(listing([Simulator, inline, Target]), message); + assert.throws(listing([inline, Simulator, Target]), message); + assert.doesNotThrow(listing([Simulator, Simulator])); + assert.doesNotThrow(listing([Simulator, inline])); }); it("treats a different alias, default or sensitivity as a different spec", () => { diff --git a/test/options.ts b/test/options.ts index b12aa4c88f..28522e630d 100644 --- a/test/options.ts +++ b/test/options.ts @@ -99,11 +99,9 @@ describe("options", () => { () => injected.release, /The option 'release' was read before the command line was parsed/, ); - options.validateOptions( - { device: { type: OptionType.String } }, - false, - true, - ); + options.validateOptions({ device: { type: OptionType.String } }, false, [ + Group, + ]); assert.isTrue(injected.release); assert.strictEqual(injected.device, "any"); }); @@ -113,7 +111,7 @@ describe("options", () => { options.validateOptions( { device: { type: OptionType.String, default: "typed" } }, false, - true, + [Group], ); options.validateOptions({ device: { type: OptionType.String, default: "nested" }, @@ -125,11 +123,9 @@ describe("options", () => { it("do not see later writes to the options service", () => { const { injected, options } = setup([], true); - options.validateOptions( - { device: { type: OptionType.String } }, - false, - true, - ); + options.validateOptions({ device: { type: OptionType.String } }, false, [ + Group, + ]); options.device = "written"; assert.strictEqual(injected.device, "any"); @@ -148,17 +144,41 @@ describe("options", () => { options.validateOptions( { device: { type: OptionType.String, default: "typed" } }, false, - true, + [Group], ); assert.strictEqual(injected.device, "typed"); }); - it("read the live values in a process without a command line", () => { - const { injected, options } = setup(["--release"], false); + it("read as defaults when the typed command does not list them", () => { + const Other = defineOptions({ + device: stringOption({ default: "other" }), + }); + const OtherType = defineOptions({ + release: stringOption({ default: "text" }), + }); + const { injected, options } = setup(["--device", "a", "--release"], true); + const sameSchema = testInjector.get(defineOptions(Group.schema)); + const other = testInjector.get(Other); + const otherType = testInjector.get(OtherType); + options.validateOptions({ device: { type: OptionType.String } }, false, [ + Group, + ]); + + assert.strictEqual(injected.device, "a"); + assert.strictEqual(other.device, "other"); + assert.strictEqual(sameSchema.device, "any"); + assert.strictEqual(otherType.release, "text"); + }); + + it("read as defaults in a process without a command line", () => { + const { injected, options } = setup( + ["--release", "--device", "a"], + false, + ); + options.validateOptions({ device: { type: OptionType.String } }); - assert.isTrue(injected.release); - options.release = false; - assert.isFalse(injected.release); + assert.isUndefined(injected.release); + assert.strictEqual(injected.device, "any"); }); it("make CliOptions readable from startup", () => { diff --git a/test/services/commands-service-dispatch.ts b/test/services/commands-service-dispatch.ts index 001472edca..9c33e77313 100644 --- a/test/services/commands-service-dispatch.ts +++ b/test/services/commands-service-dispatch.ts @@ -6,7 +6,12 @@ import { inject, runInInjectionContext } from "../../lib/common/di"; import { COMMAND_OWNER } from "../../lib/common/contracts/command-registry"; import { CommandsService } from "../../lib/common/services/commands-service"; import { HooksService } from "../../lib/common/services/hooks-service"; -import { defineCommand, stringOption } from "../../lib/common/define-command"; +import { + defineCommand, + defineOptions, + stringOption, +} from "../../lib/common/define-command"; +import { COMMAND_LINE_EXPECTED } from "../../lib/common/contracts/command-line-expected"; import { registerCommand } from "../../lib/common/services/command-definition-adapter"; import { Options } from "../../lib/options"; import { LoggerStub } from "../stubs"; @@ -24,7 +29,11 @@ interface IDispatchHarness { } const createHarness = ( - opts: { disableCommandHooks?: boolean; realOptions?: boolean } = {}, + opts: { + disableCommandHooks?: boolean; + realOptions?: boolean; + commandLine?: boolean; + } = {}, ): IDispatchHarness => { const testInjector = new Yok(); const harness = ({ @@ -73,6 +82,10 @@ const createHarness = ( trackOptions: async (): Promise => undefined, }); if (opts.realOptions) { + testInjector.register({ + provide: COMMAND_LINE_EXPECTED, + useValue: !!opts.commandLine, + }); testInjector.register("hostInfo", {}); testInjector.register("settingsService", { setSettings: (): any => undefined, @@ -82,6 +95,7 @@ const createHarness = ( } else { testInjector.register("options", { validateOptions: (): void => undefined, + recordCommandLine: (): void => undefined, }); } testInjector.register("commandsService", CommandsService); @@ -272,6 +286,55 @@ describe("CommandsService in-process dispatch", () => { assert.deepEqual(inProcess.hooks, commandLine.hooks); }); + it("gives option groups the subcommand's values before the parent's hooks", async () => { + const argv = process.argv; + process.argv = [ + "node", + "ns", + "dctest-groups", + "child", + "--level", + "typed", + ]; + try { + const harness = createHarness({ + realOptions: true, + commandLine: true, + }); + const Level = defineOptions({ + level: stringOption({ default: "group" }), + }); + const Unlisted = defineOptions({ + level: stringOption({ default: "unlisted" }), + }); + const level = harness.injector.get(Level); + const unlisted = harness.injector.get(Unlisted); + const seen: string[] = []; + harness.injector.resolve("hooksService").executeBeforeHooks = async ( + name: string, + ): Promise => { + seen.push(`${name}: ${level.level} ${unlisted.level}`); + return []; + }; + register(harness.injector, { + name: "dctest-groups|child", + options: [Level], + run: (): void => undefined, + }); + + await harness.commandsService.tryExecuteCommand("dctest-groups", [ + "child", + ]); + + assert.deepEqual(seen, [ + "dctest-groups-child: typed unlisted", + "dctest-groups|child: typed unlisted", + ]); + } finally { + process.argv = argv; + } + }); + it("rejects with the subcommand's failure instead of exiting", async () => { const harness = createHarness(); register(harness.injector, {