Repository navigation
Expand file tree
/
Copy pathswitch.ts
More file actions
116 lines (104 loc) · 5.27 KB
/
Copy pathswitch.ts
File metadata and controls
116 lines (104 loc) · 5.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { Args, Command, Flags } from '@oclif/core';
import { printError } from '../../utils/format.js';
import { createControlPlaneApiClient, requireControlPlaneAuth } from '../../utils/api-client.js';
import { readAuthConfig, writeAuthConfig } from '../../utils/auth-config.js';
import { recordCloudActiveEnvironmentId } from '../../utils/active-environment.js';
import { activateCloudDeployTarget } from '../../utils/runtime-target.js';
/**
* `os environments switch <id>` — set the active environment for this CLI session.
*
* Authenticates through `createControlPlaneApiClient` — `credentials.json`'s
* session where it targets the server, else `cloud.json`'s (the order is
* written once, there). Calls `POST /api/v1/cloud/environments/:id/activate`
* to update the server-side session, then persists `activeEnvironmentId` into
* `~/.objectstack/credentials.json` so subsequent CLI commands (and any
* client they create via `createApiClient`) automatically target this
* environment — unless the switch ran on `cloud.json`'s session, whose server
* is not the one `credentials.json` names.
*
* When the control plane it just talked to IS the one `~/.objectstack/cloud.json`
* records, the same id is written there as well, so `os package publish --install`
* can install into the environment you just switched to without repeating the
* uuid. Two files, two servers, an active environment for each — the id is
* never carried across, because it would not resolve on the other side. The
* gate lives in `utils/active-environment.ts`.
*
* Recorded there, it also makes ObjectOS Cloud the deploy target again when
* `os environments use-runtime` had made a self-hosted runtime the target: the
* two commands are the two ways to pick where `os deploy` goes, and the one
* that ran last wins. The runtime stays remembered.
*/
export default class EnvironmentsSwitch extends Command {
static override description = 'Activate an environment for subsequent CLI calls';
static override examples = [
'$ os environments switch 00000000-0000-0000-0000-000000000001',
'$ os environments switch proj-123 --no-remote',
];
static override args = {
id: Args.string({ description: 'Environment id to activate', required: true }),
};
static override flags = {
url: Flags.string({ char: 'u', description: 'Server URL', env: 'OS_CLOUD_URL' }),
token: Flags.string({ char: 't', description: 'Authentication token', env: 'OS_TOKEN' }),
remote: Flags.boolean({
description: 'Also call /activate on the server (updates the session row)',
default: true,
allowNo: true,
}),
};
async run(): Promise<void> {
const { args, flags } = await this.parse(EnvironmentsSwitch);
try {
const { client, token, baseUrl, session } = await createControlPlaneApiClient({ url: flags.url, token: flags.token });
requireControlPlaneAuth(token);
// Sanity-check the id resolves — fail fast before writing the cred file
const lookup = await client.environments.get(args.id);
const environment = lookup?.environment;
if (!environment?.id) {
throw new Error(`Environment ${args.id} not found`);
}
if (flags.remote) {
await client.environments.activate(environment.id);
}
// Cloud store first: the server session is already switched at this
// point, so the publish-side record must not be lost to a failure in the
// runtime store below (a user who only ran `os cloud login` has no
// `credentials.json` at all).
const recordedForCloud = await recordCloudActiveEnvironmentId(environment.id, baseUrl);
const leftRuntime = recordedForCloud ? await activateCloudDeployTarget() : undefined;
// Runtime store: the copy `createApiClient` reads, so the `data` / `meta`
// families keep targeting the environment you just switched to. Skipped
// when this switch ran on `cloud.json`'s session: the server it talked to
// is cloud.json's, and the environment would not resolve on the server
// `credentials.json` names.
const cfg = session === 'cloud' ? null : await readAuthConfig().catch(() => null);
if (cfg) {
cfg.activeEnvironmentId = environment.id;
cfg.lastUsedAt = new Date().toISOString();
await writeAuthConfig(cfg);
}
console.log(`\n✓ Active environment: ${environment.display_name ?? environment.id}`);
console.log(` id: ${environment.id}`);
if (recordedForCloud) {
console.log(' (also recorded in cloud.json — `os package publish --install` will use it)');
}
if (leftRuntime !== undefined) {
console.log(
` Deploy target: this environment again, not the self-hosted runtime${leftRuntime ? ` ${leftRuntime}` : ''} `
+ '(still remembered; `os environments use-runtime <url>` to go back)',
);
}
if (!recordedForCloud && !cfg) {
console.log(' ⚠ no local credential store to record it in — run `os login` or `os cloud login`');
}
if (!flags.remote) {
console.log(' (local only — server session unchanged)');
}
console.log('');
} catch (error: any) {
printError(error.message || String(error));
this.exit(1);
}
}
}