Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
2f77997
Test: an environment file may list no name under PLEXUS_
davidjalbers Dec 6, 2026
ec56c95
An environment file may list no name under PLEXUS_, under env or secrets
davidjalbers Dec 6, 2026
965673d
Test: the declaration of environments in the root marker, its validat…
davidjalbers Dec 6, 2026
1cbdd86
One function reads the declared environments and says each one's branch
davidjalbers Dec 6, 2026
3ace953
Test: the environment of a branch follows the declaration, and a repo…
davidjalbers Dec 6, 2026
adc0190
Test: a refusal names the declared branches and what is wrong with th…
davidjalbers Dec 6, 2026
76123d6
The branch that deploys is read from the declaration; ENVIRONMENT_BRA…
davidjalbers Dec 6, 2026
c37cc0d
Test: both repo templates ask for the environments and are born on main
davidjalbers Dec 6, 2026
a0713eb
Test: a new repo of repo-turbo is born on main
davidjalbers Dec 6, 2026
f535363
The repo templates ask for the environments, and a new repo is born o…
davidjalbers Dec 6, 2026
0d51deb
Test: doctor fails an invalid declaration, an undeclared environment …
davidjalbers Dec 6, 2026
2d94e4c
plx doctor checks the declaration of the environments against the env…
davidjalbers Dec 6, 2026
cb77a40
Test: plx new, plx apply and plx update carry the declaration of the …
davidjalbers Dec 6, 2026
0112899
Headers: the marker's answers may be structured, and what doctor chec…
davidjalbers Dec 6, 2026
312027b
Test: a repo-operations that gains updates is spliced the empty decla…
davidjalbers Dec 6, 2026
37d6fd6
Test: a refusal with an invalid declaration names its problems and no…
davidjalbers Dec 6, 2026
4e6bcaa
A refusal names the declaration's problems, or where to declare an en…
davidjalbers Dec 6, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions newborns/update-released.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,38 @@ for (const kind of ['app', 'operations'] as const) {
});
}

/** A declaration of environments as a person writes it into a marker: a comment, a block, a value nested two deep. */
const DECLARATION = `# What deploys, and from where.
environments:
staging:
promotes_from: main
auto_promote: true
production:
promotes_from: staging
`;

for (const kind of ['app', 'operations'] as const)
test(`${kind}: a declaration of environments in the marker of a repo of ${RELEASED} stands as written when ${FIRST} is taken`, async () => {
const repo = await repoAt(RELEASED, kind);
const marker = join(repo, 'PLEXUS.md');
const text = readFileSync(marker, 'utf8');
const close = text.indexOf('\n---\n', 4);
writeFileSync(marker, `${text.slice(0, close + 1)}${DECLARATION}${text.slice(close + 1)}`);
await git(repo, 'commit', '-q', '-am', 'declare the environments');
const branch = execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: repo, encoding: 'utf8' }).trim();
await sh('git', ['push', '-q', 'origin', branch], repo, env);
const taken = await take(FIRST, repo, FIRST);
assert.ok(taken.ok, taken.output);
const after = taken.read('PLEXUS.md');
assert.ok(after.includes(DECLARATION), after);
assert.equal(after.match(/^environments:/gm)?.length, 1, 'no default is added beside the answer');
assert.match(after, new RegExp(`^version: ${FIRST.replaceAll('.', '\\.')}$`, 'm'));
assert.deepEqual(parse(after.split('\n---\n')[0]?.slice(4) ?? '').environments, {
staging: { promotes_from: 'main', auto_promote: true },
production: { promotes_from: 'staging' },
});
});

/** The repo's group `ci`, as 0.134.1 renders it empty; with `host` listed in it, the tenant's own edit, committed and pushed. */
async function listHost(repo: string, host: string): Promise<void> {
const hosts = join(repo, 'inventory', 'hosts.yml');
Expand Down
84 changes: 75 additions & 9 deletions packages/cli-ci/src/commands/setup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -530,29 +530,49 @@ const RUN = (workflow: string, ref: string, event = 'workflow_dispatch', type =
GITHUB_REF_TYPE: type,
});

/** The root marker of a repo that declares two environments, so that the branches env/staging and env/production deploy. */
const DECLARES = `---
environments:
staging:
promotes_from: main
auto_promote: true
production:
promotes_from: staging
---
`;

for (const job of ['repo', 'deploy'] as const) {
test(`${job}: a run of on_push on a branch that deploys nowhere fails in one line naming the branch and the branches that deploy, before anything is read`, () => {
const run = runJob([job], { env: { ...CONNECT, ...RUN('on_push', 'feature-x') }, vault: VAULT });
const run = runJob([job], {
env: { ...CONNECT, ...RUN('on_push', 'feature-x') },
vault: VAULT,
marker: DECLARES,
});
assert.equal(run.status, 1, run.log);
assert.deepEqual(run.calls, []);
assert.match(run.log, /on_push.*feature-x.*main.*develop/);
assert.match(run.log, /on_push.*feature-x.*env\/staging and env\/production/);
assert.equal(run.log.trim().split('\n').length, 1, run.log);
assert.deepEqual([run.output, run.env], [{}, {}]);
});
}

test('a branch named like a property of every object deploys nowhere either', () => {
const run = runJob(['repo'], { env: { ...CONNECT, ...RUN('on_push', 'constructor') }, vault: VAULT });
const run = runJob(['repo'], {
env: { ...CONNECT, ...RUN('on_push', 'constructor') },
vault: VAULT,
marker: DECLARES,
});
assert.equal(run.status, 1, run.log);
assert.deepEqual(run.calls, []);
assert.match(run.log, /on_push on constructor deploys nowhere/);
});

for (const tag of ['v1', 'main']) {
for (const tag of ['v1', 'env/staging']) {
test(`a run of on_push on the tag ${tag} is refused, and the message says tag`, () => {
const run = runJob(['repo'], {
env: { ...CONNECT, ...RUN('on_push', tag, 'workflow_dispatch', 'tag') },
vault: VAULT,
marker: DECLARES,
});
assert.equal(run.status, 1, run.log);
assert.deepEqual(run.calls, []);
Expand All @@ -562,17 +582,63 @@ for (const tag of ['v1', 'main']) {
}

for (const [branch, event] of [
['main', 'push'],
['develop', 'push'],
['main', 'workflow_dispatch'],
['develop', 'workflow_dispatch'],
['env/staging', 'push'],
['env/production', 'push'],
['env/staging', 'workflow_dispatch'],
['env/production', 'workflow_dispatch'],
]) {
test(`a run of on_push on ${branch} by ${event} is not refused`, () => {
const run = runJob(['repo'], { env: { ...CONNECT, ...RUN('on_push', branch, event) }, vault: VAULT });
const run = runJob(['repo'], {
env: { ...CONNECT, ...RUN('on_push', branch, event) },
vault: VAULT,
marker: DECLARES,
});
assert.equal(run.status, 0, run.log);
});
}

test('a run of on_push on main, or on an env/ branch the repo does not declare, is refused, and the line lists the branches that deploy', () => {
for (const branch of ['main', 'develop', 'env/preview']) {
const run = runJob(['repo'], {
env: { ...CONNECT, ...RUN('on_push', branch, 'push') },
vault: VAULT,
marker: DECLARES,
});
assert.equal(run.status, 1, `${branch}: ${run.log}`);
assert.match(
run.log,
new RegExp(
`on_push on ${branch.replace('/', '\\/')} deploys nowhere: this repo deploys from env/staging and env/production; run on_push there`,
),
);
}
});

test('a run of on_push in a repo that declares no environment is refused, and the line says so', () => {
for (const marker of [undefined, '---\nrepo: shop\n---\n']) {
const run = runJob(['repo'], { env: { ...CONNECT, ...RUN('on_push', 'main', 'push') }, vault: VAULT, marker });
assert.equal(run.status, 1, run.log);
assert.match(
run.log,
/on_push on main deploys nowhere: the repo declares no environment; declare one under `environments` in the root marker/,
);
}
});

test('a run of on_push in a repo whose declaration is invalid is refused with the reason', () => {
const run = runJob(['repo'], {
env: { ...CONNECT, ...RUN('on_push', 'env/staging', 'push') },
vault: VAULT,
marker: '---\nenvironments:\n staging:\n promotes_from: develop\n---\n',
});
assert.equal(run.status, 1, run.log);
assert.match(
run.log,
/on_push on env\/staging deploys nowhere: the `environments` of the root marker are invalid: `staging`: `promotes_from` names `develop`/,
);
assert.doesNotMatch(run.log, /deploys from/);
});

for (const [workflow, event] of [
['on_commit', 'push'],
['on_pr', 'pull_request'],
Expand Down
8 changes: 5 additions & 3 deletions packages/cli-ci/src/commands/setupWithoutToken.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ const FORGE_RUNNER = { RUNNER_ENVIRONMENT: 'github-hosted' };
const CACHE_HOST = { PLX_TURBO_CACHE_HOST: 'cache.acme.internal' };
const VAULT = { 'op://acme-ci/repo_web/server-actions-key': 'a-key' };
/** A pull request from a fork: a forge runner, the repo's cache host, the overlay, and no secret. */
const ON_PUSH = { GITHUB_WORKFLOW: 'on_push', GITHUB_REF_NAME: 'main', GITHUB_EVENT_NAME: 'push' };
const ON_PUSH = { GITHUB_WORKFLOW: 'on_push', GITHUB_REF_NAME: 'env/staging', GITHUB_EVENT_NAME: 'push' };
/** The root marker of a repo whose branch env/staging deploys. */
const MARKER = '---\nenvironments:\n staging:\n promotes_from: main\n---\n';
const FORK = { ...FORGE_RUNNER, ...CACHE_HOST, GITHUB_WORKFLOW: 'on_pr', GITHUB_EVENT_NAME: 'pull_request' };

/** The one line the step says about it. */
Expand Down Expand Up @@ -49,15 +51,15 @@ test('a repo job of the workflow on_commit or on_pr reads nothing where it has n
const job = runJob(['repo'], { env: { GITHUB_WORKFLOW }, vault: VAULT });
assert.equal(job.status, 0, `${GITHUB_WORKFLOW}\n${job.log}`);
}
const job = runJob(['repo'], { env: ON_PUSH, vault: VAULT });
const job = runJob(['repo'], { env: ON_PUSH, vault: VAULT, marker: MARKER });
assert.equal(job.status, 1, job.log);
assert.match(job.log, /on_push .*vault/);
assert.match(job.log, /OP_SERVICE_ACCOUNT_TOKEN/);
assert.deepEqual(job.output, {});
});

test('a deploy job with no token fails, since it cannot deploy', () => {
const job = runJob(['deploy'], { env: { ...FORGE_RUNNER, ...ON_PUSH }, vault: VAULT });
const job = runJob(['deploy'], { env: { ...FORGE_RUNNER, ...ON_PUSH }, vault: VAULT, marker: MARKER });
assert.equal(job.status, 1, job.log);
assert.match(job.log, /OP_CONNECT_HOST and OP_CONNECT_TOKEN/);
assert.match(job.log, /OP_SERVICE_ACCOUNT_TOKEN/);
Expand Down
13 changes: 8 additions & 5 deletions packages/cli-ci/src/core/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@ import { appendFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import {
type Context,
declarationRefusal,
describeBranches,
detailOf,
ENVIRONMENT_BRANCHES,
environmentOf,
isOperationsRepo,
orAbsent,
type Plan,
readDeclaredEnvironments,
run,
write,
} from '@plexus-ms/lib';
Expand Down Expand Up @@ -78,13 +80,14 @@ const cacheHostOf = (env: NodeJS.ProcessEnv): string | undefined => env.PLX_TURB
* in the deploy: it fails here, before anything is read, built or pushed. The
* workflow is told by its name, which the forge hands every step.
*/
function refuseOnPushWithoutEnvironment(env: NodeJS.ProcessEnv): void {
async function refuseOnPushWithoutEnvironment(ctx: Context, env: NodeJS.ProcessEnv): Promise<void> {
if (env.GITHUB_WORKFLOW !== 'on_push') return;
const ref = env.GITHUB_REF_NAME ?? '';
const tag = env.GITHUB_REF_TYPE === 'tag';
if (!tag && environmentOf(env.GITHUB_EVENT_NAME ?? '', ref)) return;
const declared = await readDeclaredEnvironments(ctx, '.');
if (!tag && environmentOf(declared, env.GITHUB_EVENT_NAME ?? '', ref)) return;
throw new Error(
`on_push on ${tag ? 'tag ' : ''}${ref} deploys nowhere: only the branches ${Object.keys(ENVIRONMENT_BRANCHES).join(' and ')} deploy; run on_push there`,
`on_push on ${tag ? 'tag ' : ''}${ref} deploys nowhere: ${declarationRefusal(declared) ?? `this repo deploys from ${describeBranches(declared, 'and')}; run on_push there`}`,
);
}

Expand Down Expand Up @@ -145,7 +148,7 @@ async function vaultFor(
export async function setup(ctx: Context, options: SetupOptions, env: NodeJS.ProcessEnv = process.env): Promise<void> {
// The job repo of an app repo, whose publish pushes the apps' images.
const images = options.job === 'repo' && (options.publishes ?? 'images') === 'images';
if (images || options.job === 'deploy') refuseOnPushWithoutEnvironment(env);
if (images || options.job === 'deploy') await refuseOnPushWithoutEnvironment(ctx, env);
const repository = need('GITHUB_REPOSITORY', env);
const owner = ownerOf(repository);
const repo = repository.split('/')[1] ?? repository;
Expand Down
29 changes: 29 additions & 0 deletions packages/cli/src/commands/apply.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,3 +193,32 @@ test('apply takes a repo given relatively as the repo it is, not as a directory
process.chdir(cwd);
}
});

test('apply brings the files in line with a hand-edited declaration of environments and leaves the marker as written', async () => {
const templates = join(dir, 'fleet-templates');
put(join(templates, 'fleet'), {
'template.yml': 'name: fleet\nquestions:\n environments:\n type: yaml\n default: {}\n',
'files/branches.txt.jinja':
'{% for name, e in environments.items() %}env/{{ name }} from {{ e.promotes_from }}{% if e.auto_promote is defined and e.auto_promote %} (auto){% endif %}\n{% endfor %}',
});
const marker = (environments: string) =>
`---\nversion: ${version}\ntemplates: [fleet]\nenvironments:\n${environments}---\n\nThe prose.\n`;
const staging = ' staging:\n promotes_from: main\n';
const repo = join(dir, 'fleet-repo');
mkdirSync(repo);
git(repo, 'init', '-q', '-b', 'main');
put(repo, { 'PLEXUS.md': marker(staging), 'branches.txt': 'env/staging from main\n' });
git(repo, 'add', '-A');
git(repo, 'commit', '-q', '-m', 'init');
const edited = marker(
`${staging} auto_promote: true # promotes itself\n production:\n promotes_from: staging\n`,
);
put(repo, { 'PLEXUS.md': edited });
const { code } = await plx('-y', 'apply', '--templates', templates, repo);
assert.equal(code, 0);
assert.equal(
readFileSync(join(repo, 'branches.txt'), 'utf8'),
'env/staging from main (auto)\nenv/production from staging\n',
);
assert.equal(readFileSync(join(repo, 'PLEXUS.md'), 'utf8'), edited);
});
33 changes: 30 additions & 3 deletions packages/cli/src/commands/deploy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ function fixture(): Fixture {
const root = mkdtempSync(join(scratch, 'case-'));
const repo = join(root, 'repo');
put(repo, {
'PLEXUS.md': '---\nrepo: shop\n---\n',
'PLEXUS.md': '---\nrepo: shop\nenvironments:\n staging:\n promotes_from: main\n---\n',
'apps/shop/Dockerfile': 'FROM scratch\n',
'apps/admin/Dockerfile': 'FROM scratch\n',
...stack('shop', SHOP_COMPOSE),
Expand Down Expand Up @@ -365,19 +365,46 @@ test('a repo whose stacks have zero apps deploys the same way: no image is resol
assert.equal(existsSync(join(f.fake, 'docker.log')), false);
});

test('without --environment the environment follows the branch; where it follows none, the verb says so', async () => {
test('without --environment the environment follows the declared branch; where it follows none, the verb says so and names the branches', async () => {
const f = fixture();
const args = ['deploy', '--inventory', f.inv, '--commit', SHA, '-C', f.repo];
await assert.rejects(
plx(args, f.fake, { GITHUB_EVENT_NAME: 'pull_request', GITHUB_REF_NAME: '3/merge' }),
UsageError,
);
for (const ref of ['main', 'develop', 'env/preview'])
await assert.rejects(
plx(args, f.fake, { GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: ref }),
(e: unknown) => e instanceof UsageError && e.message.includes('run on a push to env/staging'),
ref,
);
assert.deepEqual(runs(f.fake), []);
const err = await plx(args, f.fake, { GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: 'develop' });
const err = await plx(args, f.fake, { GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: 'env/staging' });
assert.equal(runs(f.fake).length, 3);
assert.equal(summary(err).length, 3);
});

test('a repo that declares no environment deploys from no branch, and a declaration that is invalid is refused with its reason', async () => {
const f = fixture();
const args = ['deploy', '--inventory', f.inv, '--commit', SHA, '-C', f.repo];
put(f.repo, { 'PLEXUS.md': '---\nrepo: shop\n---\n' });
await assert.rejects(
plx(args, f.fake, { GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: 'env/staging' }),
(e: unknown) =>
e instanceof UsageError &&
e.message.includes('the repo declares no environment; declare one under `environments` in the root marker'),
);
put(f.repo, { 'PLEXUS.md': '---\nrepo: shop\nenvironments:\n staging:\n promotes_from: develop\n---\n' });
await assert.rejects(
plx(args, f.fake, { GITHUB_EVENT_NAME: 'push', GITHUB_REF_NAME: 'env/staging' }),
(e: unknown) =>
e instanceof UsageError &&
e.message.includes('are invalid: `staging`: `promotes_from` names `develop`') &&
!e.message.includes('run on a push'),
);
assert.deepEqual(runs(f.fake), []);
});

test('plx deploy needs the inventory the records are read from, and says what to pass in the same words in every repo', async () => {
const f = fixture();
const refusal = (e: unknown) =>
Expand Down
21 changes: 17 additions & 4 deletions packages/cli/src/commands/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,17 @@
// absent one, so a mount can always pass the flag.
//
// plx deploy --environment staging --inventory ../operations/inventory
// plx deploy --inventory operations/inventory # in a job, on a push to main or develop
// plx deploy --inventory operations/inventory # in a job, on a push to a declared env/<name> branch
// plx deploy -e production --inventory inventory -- -e stack_wait_timeout=180
import { resolve } from 'node:path';
import { deploy, ENVIRONMENT_BRANCHES, environmentOf, UsageError } from '@plexus-ms/lib';
import {
declarationRefusal,
deploy,
describeBranches,
environmentOf,
readDeclaredEnvironments,
UsageError,
} from '@plexus-ms/lib';
import type { Command } from 'commander';
import { contextOf, version } from '../program.ts';

Expand Down Expand Up @@ -52,10 +59,16 @@ export function register(program: Command): void {
if (opts.commit && !/^([0-9a-f]{40}|[0-9a-f]{64})$/.test(opts.commit))
throw new UsageError(`--commit ${opts.commit}: a full commit hash, 40 or 64 hex digits in lower case`);
const env = process.env;
const environment = environmentOf(env.GITHUB_EVENT_NAME ?? '', env.GITHUB_REF_NAME ?? '', opts.environment);
const declared = await readDeclaredEnvironments(ctx, resolve(opts.dir));
const environment = environmentOf(
declared,
env.GITHUB_EVENT_NAME ?? '',
env.GITHUB_REF_NAME ?? '',
opts.environment,
);
if (!environment)
throw new UsageError(
`no environment: pass --environment, or run on a push to ${Object.keys(ENVIRONMENT_BRANCHES).join(' or ')}`,
`no environment: pass --environment; ${declarationRefusal(declared) ?? `or run on a push to ${describeBranches(declared, 'or')}`}`,
);
const result = await deploy(ctx, {
environment,
Expand Down
4 changes: 2 additions & 2 deletions packages/dev/src/ship.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2288,15 +2288,15 @@ for (const [template, answers, edits] of [
const end = snapshot(human);
const expected = { ...start };
expected['PLEXUS.md'] = {
// The questions the templates have gained since the move are spliced into the marker, as their defaults, and the
// The questions the templates have gained since the move are spliced into the marker, as their defaults (an empty declaration of environments among them), and the
// answer to ci_registry, which the version no longer asks, leaves it (the package repo was never asked it).
text: removeMarkerKeys(
setMarkerKeys(start['PLEXUS.md']?.text ?? '', {
version: CURRENT,
templates: [template, 'updates'],
...(template === 'repo-turbo'
? { postgres: '', repo: '', turbo_cache_host: '' }
: { housekeeping: false, repo: '' }),
: { environments: {}, housekeeping: false, repo: '' }),
}),
template === 'repo-operations' ? ['ci_registry'] : [],
),
Expand Down
Loading