Skip to content

Commit 66356fb

Browse files
authored
Merge pull request #25 from rhyek/chore/service-env-optional-services
Give a service its own env, and make services optional
2 parents 7c16e28 + a9e48de commit 66356fb

20 files changed

Lines changed: 1255 additions & 133 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,15 @@
11
# Changelog
22

3+
## 0.10.0
4+
5+
### Features
6+
7+
- **A service takes an `env` of its own**: `vars`, `override` and `additionalFiles` for it
8+
alone, on top of the config's unless `inherits: false`. See
9+
[docs/config/services.md](docs/config/services.md#env).
10+
- **`services` is optional in `stackctl.config.ts`**, for a config that only sets the
11+
environment of `exec` and `run`.
12+
313
## 0.9.0
414

515
### Features

‎docs/config/config-file.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ repo.
2727

2828
| Option | What it is |
2929
| ---------------- | -------------------------------------------------------------------------------------------------- |
30-
| `services` | Your application services, keyed by name. **Required.** See [Services](./services.md). |
30+
| `services` | Your application services, keyed by name. See [Services](./services.md). Without it, the config sets the environment of `exec` and `run` alone. |
3131
| `serviceRootDir` | The directory services live under, e.g. `'apps'`: each service is at `<serviceRootDir>/<name>`. **Recommended.** Without it, every service sets `targetDir`. |
3232
| `env` | Variables of the config's own, and how `.env` files load. See [Environment](./env.md). |
3333
| `logs` | On-screen timestamps. See [Logs](./logs.md). |

‎docs/config/env.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ description: The env option of stackctl.config.ts - env.vars for variables set i
66

77
The `env` option adjusts how stackctl builds each process's environment.
88
[Environment and profiles](../guide/env.md) explains what loads by default; this page is the
9-
option reference.
9+
option reference. A service can add `vars`, `override` and `additionalFiles` of its own on top:
10+
see [a service's `env`](./services.md#env).
1011

1112
```ts
1213
export default defineConfig({
@@ -36,7 +37,8 @@ export default defineConfig({
3637
- **Type:** `Record<string, string | undefined> | (ctx) => Record<…>`
3738

3839
Variables for everything stackctl starts: every service, `stackctl exec` and `run`, and
39-
[infra](./infra.md) (Compose and its callbacks).
40+
[infra](./infra.md) (Compose and its callbacks). A service's own
41+
[`env.vars`](./services.md#env) merge over them.
4042

4143
```ts
4244
env: {

‎docs/config/services.md‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
description: Every option of a service in stackctl.config.ts - port, healthcheck and readiness, deps, command, urls, autostart, tokens, logs, color and directory.
2+
description: Every option of a service in stackctl.config.ts - port, healthcheck and readiness, deps, command, urls, autostart, its own env files and variables, tokens, logs, color and directory.
33
---
44

55
# Services
@@ -41,6 +41,7 @@ Every option is optional. `{}` is a valid service: it runs the `dev` script in
4141
| [`autostart`](#autostart) | `true` | Whether it starts with the session. |
4242
| [`selectable`](#selectable) | `true` | Whether the picker lists it. |
4343
| [`targetDir`](#targetdir) | `<serviceRootDir>/<name>` | The service's directory. |
44+
| [`env`](#env) | the config's | `.env` files, variables and overrides of its own. |
4445
| [`tokens`](#tokens) | none | Values for this service's callbacks. |
4546
| [`logs`](#logs) | inherits | Timestamps and log formatting for this service. |
4647
| [`color`](#color) | assigned | The color of its log label. |
@@ -175,6 +176,42 @@ lives somewhere else. It is required when the config has no `serviceRootDir`.
175176
- **It decides which `.env` files load**: those of every directory from the root down to it.
176177
See [Which files load](../guide/env.md#which-files-load).
177178

179+
## `env`
180+
181+
- **Type:** `{ inherits?, vars?, override?, additionalFiles? } | (ctx) => vars`
182+
183+
`.env` files, variables and overrides for this service alone, on top of the config's
184+
[`env`](./env.md):
185+
186+
```ts
187+
api: {
188+
env: {
189+
vars: { LOG_LEVEL: 'debug' },
190+
override: ['NODE_OPTIONS'],
191+
additionalFiles: [{ file: '.env.api', after: '.env' }],
192+
},
193+
},
194+
```
195+
196+
Each option works as its namesake in the config's [`env`](./env.md), for this service only.
197+
`inherits` decides what happens to the config's:
198+
199+
| Option | `inherits: true` (default) | `inherits: false` |
200+
| ----------------- | --------------------------------------- | ----------------- |
201+
| `vars` | Merged over the config's, its own win. | Its own only. |
202+
| `override` | Added to the config's. | Its own only. |
203+
| `additionalFiles` | Loaded after the config's. | Its own only. |
204+
205+
- **A callback stands for `vars`**: `env: ({ envs }) => ({ … })`. Its `envs` holds the service's
206+
`.env` files and the config's `vars` when it inherits, and its `tokens` are the service's.
207+
- **It reaches the service everywhere**: its process, its callbacks (`port`, `urls`, …), and
208+
[`stackctl exec` and `run`](../guide/commands.md#targets) with it as the target. A directory
209+
that is no service gets the config's `env` alone.
210+
- **`decrypt` is the config's**, and applies to every service either way.
211+
- **A file the config's `additionalFiles` lists** is an error here, unless `inherits: false`.
212+
- **It shows in the resolved config**: `stackctl show-config` prints each service's result as
213+
`envFiles`, `envOverride` and `envVars`, so don't compose a secret in `vars`.
214+
178215
## `tokens`
179216

180217
- **Type:** `Record<string, string>`

‎docs/guide/commands.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ sctl exec libs/db -- node src/migrate.ts # a directory that isn't a service
3232
```
3333

3434
- **A path anywhere inside a service is that service**, and the command runs in the service's
35-
own directory.
35+
own directory, with the service's own [`env`](../config/services.md#env).
3636
- **`./api` is always the directory.** A bare `api` is the service.
3737
- **A directory outside every service** gets the `.env` files of every directory from the root
3838
down to it, and no `PORT`.

‎docs/guide/env.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,8 @@ To commit secrets too, encrypt them with dotenvx and turn on
5757

5858
From lowest to highest:
5959

60-
1. [`env.vars`](../config/env.md#envvars), variables set in the config.
60+
1. [`env.vars`](../config/env.md#envvars), variables set in the config, with a service's own
61+
[`env.vars`](../config/services.md#env) over them.
6162
2. The `.env` files, in the order [above](#which-files-load).
6263
3. **The environment stackctl was started with.** `LOG_LEVEL=debug sctl` overrides every
6364
file for one run, as in Vite, Next.js and `node --env-file`.
@@ -120,7 +121,9 @@ When a file's content changes, the services that read it restart:
120121
| a folder such as `apps/` | every running service below it |
121122
| a service's own folder | that service |
122123

123-
Symlinked files are followed. A write
124+
A file only one service looks for, through its own
125+
[`env.additionalFiles`](../config/services.md#env), restarts only that service. Symlinked files
126+
are followed. A write
124127
that changes nothing (a `touch`) restarts nothing.
125128

126129
Values the config computed are the exception: `env.vars` and callbacks such as `port` run once,

‎docs/reference/cli.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@ session's, else the latest one's. It never asks the session anything.
261261
stackctl show-config
262262
stackctl show-config --profile test
263263
stackctl show-config | jq '.services | map_values({ port, publicOrigin })'
264-
stackctl show-config | jq '.envFiles.workspace'
264+
stackctl show-config | jq '.services.api.envFiles'
265265
```
266266

267267
Prints the fully resolved config as JSON, with no session: callbacks have run and defaults
@@ -270,10 +270,10 @@ are applied. It is the same object a session reports as `config` on
270270

271271
| Field | What it holds |
272272
| --------------- | -------------------------------------------------------------------------------------- |
273-
| `services` | Each service's `port`, `publicOrigin`, `urls`, `healthcheck`, `deps`, `command`, `targetDir` (as written) and `resolvedTargetDir` (absolute). |
273+
| `services` | Each service's `port`, `publicOrigin`, `urls`, `healthcheck`, `deps`, `command`, `targetDir` (as written), `resolvedTargetDir` (absolute), and its [`env`](../config/services.md#env) combined with the config's: `envFiles`, `envOverride` and `envVars`. |
274274
| `infra` | Per provider: the compose `file`, the profile's `projectName`, and each service's `enabled`, `port`, `urls` and `publicOrigin`. |
275275
| `reverseProxy` | Its `port`, `tls`, `publicAddress` and `routes`. |
276-
| `envFiles` | The `.env` filenames the profile looks for in each directory, in load order. |
276+
| `envFiles` | The `.env` filenames the profile looks for in each directory, in load order. A service's own are on the service. |
277277

278278
Functions (`logs.formatter`, infra callbacks) have no JSON form and are left out.
279279

‎packages/stackctl/src/cli-spec/commands.spec.ts‎

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,137 @@ describe('exec and run take a target', () => {
424424
});
425425
});
426426

427+
describe("a service's own env", () => {
428+
let dir: string;
429+
beforeAll(() => {
430+
dir = path.join(ws, 'svc-env');
431+
for (const name of ['api', 'solo', 'web']) {
432+
fs.mkdirSync(path.join(dir, 'packages', name), { recursive: true });
433+
fs.writeFileSync(
434+
path.join(dir, 'packages', name, 'package.json'),
435+
JSON.stringify({ name, scripts: { dev: 'true' } }),
436+
);
437+
}
438+
fs.mkdirSync(path.join(dir, 'scripts'));
439+
fs.writeFileSync(
440+
path.join(dir, 'stackctl.config.ts'),
441+
[
442+
"import { defineConfig } from 'stackctl';",
443+
'export default defineConfig({',
444+
" serviceRootDir: 'packages',",
445+
" env: { vars: { TOP: 'top', SHARED: 'top' }, additionalFiles: [{ file: '.env.shared', after: '.env' }] },", // oxfmt-ignore
446+
' services: {',
447+
" api: { env: { vars: { SHARED: 'api' }, override: ['SHELL_SET'], additionalFiles: [{ file: '.env.api', after: '.env' }] } },", // oxfmt-ignore
448+
" solo: { env: { inherits: false, vars: { MINE: 'solo' } } },",
449+
' web: {},',
450+
' },',
451+
'});',
452+
'',
453+
].join('\n'),
454+
);
455+
fs.writeFileSync(path.join(dir, '.env'), 'SHELL_SET=file\n');
456+
fs.writeFileSync(path.join(dir, '.env.shared'), 'SHARED_FILE=1\n');
457+
fs.writeFileSync(path.join(dir, '.env.api'), 'API_FILE=1\n');
458+
});
459+
afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
460+
461+
const names = ['TOP', 'SHARED', 'API_FILE', 'SHARED_FILE', 'SHELL_SET', 'MINE'];
462+
const print = ['sh', '-c', `echo "${names.map((name) => `$${name}`).join('|')}"`];
463+
const execIn = (target: string) =>
464+
stackctl(['--workspace-dir', dir, 'exec', target, '--', ...print], {
465+
env: { SHELL_SET: 'shell' },
466+
});
467+
468+
test("exec gives a service its own vars, files and override over the config's", async () => {
469+
expect((await execIn('api')).stdout).toBe('top|api|1|1|file|');
470+
});
471+
472+
test("exec gives another service the config's alone", async () => {
473+
expect((await execIn('web')).stdout).toBe('top|top||1|shell|');
474+
});
475+
476+
test("exec gives a service that doesn't inherit its own alone", async () => {
477+
expect((await execIn('solo')).stdout).toBe('||||shell|solo');
478+
});
479+
480+
test("exec gives a directory that is no service the config's alone", async () => {
481+
expect((await execIn('./scripts')).stdout).toBe('top|top||1|shell|');
482+
});
483+
484+
test("resolveEnv() lists the service's own files", async () => {
485+
const { resolveEnv } = (await import(
486+
pathToFileURL(path.join(buildDir, 'index.js')).href
487+
)) as typeof import('../index');
488+
const api = resolveEnv({ workspaceDir: dir, target: 'api' });
489+
const web = resolveEnv({ workspaceDir: dir, target: 'web' });
490+
expect(api.files).toContain(path.join(dir, '.env.api'));
491+
expect(api.env).toMatchObject({ SHARED: 'api', API_FILE: '1' });
492+
expect(web.files).not.toContain(path.join(dir, '.env.api'));
493+
expect(web.env.SHARED).toBe('top');
494+
});
495+
496+
test('show-config prints each service its combined env', async () => {
497+
const result = await stackctl(['--workspace-dir', dir, 'show-config']);
498+
const { services } = JSON.parse(result.stdout) as {
499+
services: Record<string, { envFiles: string[]; envOverride?: unknown; envVars?: unknown }>;
500+
};
501+
expect(services.api).toMatchObject({
502+
envOverride: ['SHELL_SET'],
503+
envVars: { TOP: 'top', SHARED: 'api' },
504+
});
505+
expect(services.api!.envFiles).toEqual([
506+
'.env',
507+
'.env.shared',
508+
'.env.api',
509+
'.env.local',
510+
'.env.development',
511+
'.env.development.local',
512+
]);
513+
expect(services.solo).toMatchObject({ envVars: { MINE: 'solo' } });
514+
expect(services.solo!.envFiles).not.toContain('.env.shared');
515+
expect(services.web!.envFiles).not.toContain('.env.api');
516+
});
517+
});
518+
519+
describe('a config with no services', () => {
520+
let dir: string;
521+
beforeAll(() => {
522+
dir = path.join(ws, 'no-services');
523+
fs.mkdirSync(path.join(dir, 'scripts', 'tool'), { recursive: true });
524+
fs.writeFileSync(
525+
path.join(dir, 'stackctl.config.ts'),
526+
"import { defineConfig } from 'stackctl';\nexport default defineConfig({ env: { vars: { FROM_CONFIG: 'yes' } } });\n", // oxfmt-ignore
527+
);
528+
fs.writeFileSync(path.join(dir, 'scripts', 'tool', '.env.local'), 'TOOL_VAR=tool\n');
529+
});
530+
afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
531+
532+
test('start says there is nothing to start, and fails', async () => {
533+
const result = await stackctl(['--workspace-dir', dir, '--headless']);
534+
expect(result.exitCode).toBe(1);
535+
expect(result.stderr).toContain('stackctl.config.ts declares no services');
536+
});
537+
538+
test('exec runs a command in a directory with the config and its .env files', async () => {
539+
const result = await stackctl([
540+
'--workspace-dir',
541+
dir,
542+
'exec',
543+
'./scripts/tool',
544+
'--',
545+
'sh',
546+
'-c',
547+
'echo "$FROM_CONFIG|$TOOL_VAR|$PWD"',
548+
]);
549+
expect(result.stdout).toBe(`yes|tool|${path.join(dir, 'scripts', 'tool')}`);
550+
});
551+
552+
test('show-config prints no services', async () => {
553+
const result = await stackctl(['--workspace-dir', dir, 'show-config']);
554+
expect((JSON.parse(result.stdout) as { services: unknown }).services).toEqual({});
555+
});
556+
});
557+
427558
describe("a config whose workspaceDir isn't its own folder", () => {
428559
// outer/config/stackctl.config.ts sets `workspaceDir: '..'`: the workspace is outer/, where the
429560
// services and the walked-up .env files are, and config/'s own .env file is no workspace's.

‎packages/stackctl/src/commands/default.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { startedByAgent } from '../agent-detection';
22
import { guidanceAtStart } from '../agent-guidance';
3+
import { getRegisteredPackages } from '../config';
34
import { isCI } from '../env-base';
45
import { resolveSelectedNames } from '../saved-selection';
56
import { readOwnVersion } from '../skill';
@@ -42,6 +43,14 @@ export function resolveSelectedNamesOrExit(
4243
/** Starts the session the options ask for; a session ends by exiting the process. */
4344
export async function runDefaultAction(opts: StartOptions): Promise<void> {
4445
await loadConfigOrExit();
46+
// A config may declare none, to set the environment of `exec` and `run` alone.
47+
if (getRegisteredPackages().length === 0) {
48+
console.error(
49+
'stackctl.config.ts declares no services, so there is nothing to start. ' +
50+
'Run a command with `stackctl exec` or `stackctl run`.',
51+
);
52+
process.exit(1);
53+
}
4554

4655
// Best-effort: the agent guidance should never block a run. What is installed is kept
4756
// current; what is missing is offered once, and only to a person about to see the terminal UI.

‎packages/stackctl/src/commands/workspace.ts‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
getRegisteredPackages,
66
getWorkspaceDir,
77
} from '../config';
8-
import { envFileNames, workspaceEnvLayer } from '../env';
8+
import { envFileNames, recordWorkspaceEnv, workspaceEnvLayer } from '../env';
99
import {
1010
NoProjectConfigError,
1111
findConfigPath,
@@ -40,17 +40,17 @@ export function applyWorkspaceEnv(config: Config<string> | null): void {
4040
return;
4141
}
4242
workspaceEnvApplied = true;
43-
Object.assign(
44-
process.env,
45-
workspaceEnvLayer({
46-
// The config's own root, which may not be the folder holding it (where the CLI anchored).
47-
resolvedWorkspaceDir: config ? getWorkspaceDir() : process.cwd(),
48-
files: config?.envFiles ?? envFileNames(),
49-
override: config?.envOverride,
50-
decrypt: config?.envDecrypt,
51-
vars: config?.envVars,
52-
}),
53-
);
43+
const layer = workspaceEnvLayer({
44+
// The config's own root, which may not be the folder holding it (where the CLI anchored).
45+
resolvedWorkspaceDir: config ? getWorkspaceDir() : process.cwd(),
46+
files: config?.envFiles ?? envFileNames(),
47+
override: config?.envOverride,
48+
decrypt: config?.envDecrypt,
49+
vars: config?.envVars,
50+
});
51+
// So what a target is started with can leave it out: see `withoutWorkspaceEnv`.
52+
recordWorkspaceEnv(Object.keys(layer));
53+
Object.assign(process.env, layer);
5454
}
5555

5656
/**

0 commit comments

Comments
 (0)