@narumitw/pi-starship 0.28.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,4 @@
1
+ import { homedir, hostname, userInfo } from "node:os";
1
2
  import {
2
3
  type ExtensionAPI,
3
4
  type ExtensionContext,
@@ -10,20 +11,29 @@ import {
10
11
  type LoadedStarshipConfig,
11
12
  loadOrCreateStarshipConfig,
12
13
  loadStarshipConfig,
14
+ type StarshipConfig,
13
15
  settingsFilePath,
14
16
  } from "./config.js";
15
17
  import { readInstalledPackageInfo } from "./installed-packages.js";
16
- import { gitStatusEqual, readGitStatus, readGitWorktree } from "./modules/git/runtime.js";
18
+ import { gitSnapshotEqual, readGitSnapshot } from "./modules/git/runtime.js";
17
19
  import {
18
20
  type ExtensionStatusIconAliasMap,
19
- type GitStatusSnapshot,
20
- type GitWorktreeSnapshot,
21
+ type GitSnapshot,
22
+ reachableModuleRequirements,
21
23
  renderStatusline,
22
24
  type StarshipRuntimeSnapshot,
25
+ type WorkspaceSnapshot,
23
26
  } from "./modules/index.js";
27
+ import { execWorkspaceCommand } from "./runtime/command.js";
28
+ import { AsyncRefreshController } from "./runtime/refresh-controller.js";
29
+ import {
30
+ collectWorkspaceSnapshot,
31
+ type WorkspaceRefreshInput,
32
+ workspaceSnapshotEqual,
33
+ } from "./runtime/workspace.js";
24
34
 
25
- const GIT_REFRESH_INTERVAL_MS = 30_000;
26
- const GIT_EVENT_DEBOUNCE_MS = 250;
35
+ const REFRESH_INTERVAL_MS = 30_000;
36
+ const EVENT_DEBOUNCE_MS = 250;
27
37
  const EMPTY_ALIASES: ExtensionStatusIconAliasMap = new Map();
28
38
 
29
39
  interface RuntimeState {
@@ -31,10 +41,21 @@ interface RuntimeState {
31
41
  isStreaming: boolean;
32
42
  thinkingLevel: string;
33
43
  lastCompletedTool?: string;
34
- gitStatus?: GitStatusSnapshot;
35
- gitWorktree?: GitWorktreeSnapshot;
44
+ git?: GitSnapshot;
45
+ workspace?: WorkspaceSnapshot;
36
46
  extensionStatusIconAliases: ExtensionStatusIconAliasMap;
37
47
  requestRender?: () => void;
48
+ renderPreview?: (loaded: LoadedStarshipConfig, width: number) => string[];
49
+ }
50
+
51
+ interface RefreshTarget {
52
+ cwd: string;
53
+ generation: number;
54
+ }
55
+
56
+ interface GitRefreshInput {
57
+ cwd: string;
58
+ config: StarshipConfig;
38
59
  }
39
60
 
40
61
  export default function piStarship(pi: ExtensionAPI) {
@@ -47,101 +68,92 @@ export default function piStarship(pi: ExtensionAPI) {
47
68
  };
48
69
  let conflictWarningShown = false;
49
70
  let sessionGeneration = 0;
50
- let gitRequestId = 0;
51
- let activeGitTarget: { cwd: string; generation: number } | undefined;
52
- let gitRefreshInFlight = false;
53
- let gitDebounceTimer: ReturnType<typeof setTimeout> | undefined;
54
- let pendingGitRefresh: { cwd: string; generation: number; requestId: number } | undefined;
71
+ let activeTarget: RefreshTarget | undefined;
72
+ let eventDebounceTimer: ReturnType<typeof setTimeout> | undefined;
55
73
 
56
74
  const refresh = () => runtime.requestRender?.();
57
- const clearDebounce = () => {
58
- if (!gitDebounceTimer) return;
59
- clearTimeout(gitDebounceTimer);
60
- gitDebounceTimer = undefined;
61
- };
62
- const isActiveTarget = (cwd: string, generation: number) =>
63
- activeGitTarget?.cwd === cwd &&
64
- activeGitTarget.generation === generation &&
65
- generation === sessionGeneration;
66
- const isCurrentRequest = (cwd: string, generation: number, requestId: number) =>
67
- isActiveTarget(cwd, generation) && requestId === gitRequestId;
68
-
69
- const setGitStatus = (status: GitStatusSnapshot | undefined) => {
70
- if (gitStatusEqual(runtime.gitStatus, status)) return;
71
- runtime.gitStatus = status;
72
- refresh();
73
- };
74
-
75
- const refreshGitWorktree = (cwd: string, generation: number) => {
76
- void (async () => {
77
- let worktree: GitWorktreeSnapshot | undefined;
75
+ const gitController = new AsyncRefreshController<GitRefreshInput, GitSnapshot | undefined>({
76
+ async read(input) {
77
+ const requirements = reachableModuleRequirements(input.config);
78
+ const gitReachable = [...requirements.keys()].some((name) => name.startsWith("git_"));
79
+ if (!gitReachable) return undefined;
78
80
  try {
79
- worktree = await readGitWorktree(pi, cwd);
81
+ return await readGitSnapshot(pi, input.cwd, {
82
+ includeMetrics: requirements.has("git_metrics"),
83
+ includeTag: requirements.get("git_commit")?.has("tag") ?? false,
84
+ });
80
85
  } catch {
81
- worktree = undefined;
82
- }
83
- if (!isActiveTarget(cwd, generation)) return;
84
- if (
85
- runtime.gitWorktree?.name === worktree?.name &&
86
- runtime.gitWorktree?.path === worktree?.path
87
- ) {
88
- return;
86
+ return undefined;
89
87
  }
90
- runtime.gitWorktree = worktree;
88
+ },
89
+ equal: gitSnapshotEqual,
90
+ publish(snapshot) {
91
+ runtime.git = snapshot;
91
92
  refresh();
92
- })();
93
- };
94
-
95
- const runGitRefresh = (cwd: string, generation: number, requestId: number) => {
96
- if (!isCurrentRequest(cwd, generation, requestId)) return;
97
- if (gitRefreshInFlight) {
98
- pendingGitRefresh = { cwd, generation, requestId };
99
- return;
100
- }
101
- gitRefreshInFlight = true;
102
- void (async () => {
93
+ },
94
+ });
95
+ const workspaceController = new AsyncRefreshController<WorkspaceRefreshInput, WorkspaceSnapshot>({
96
+ async read(input) {
103
97
  try {
104
- const status = await readGitStatus(pi, cwd);
105
- if (isCurrentRequest(cwd, generation, requestId)) setGitStatus(status);
98
+ return await collectWorkspaceSnapshot(input);
106
99
  } catch {
107
- if (isCurrentRequest(cwd, generation, requestId)) setGitStatus(undefined);
108
- } finally {
109
- gitRefreshInFlight = false;
110
- const pending = pendingGitRefresh;
111
- pendingGitRefresh = undefined;
112
- if (pending) runGitRefresh(pending.cwd, pending.generation, pending.requestId);
100
+ return { modules: {} };
113
101
  }
114
- })();
102
+ },
103
+ equal: workspaceSnapshotEqual,
104
+ publish(snapshot) {
105
+ runtime.workspace = snapshot;
106
+ refresh();
107
+ },
108
+ });
109
+
110
+ const clearDebounce = () => {
111
+ if (!eventDebounceTimer) return;
112
+ clearTimeout(eventDebounceTimer);
113
+ eventDebounceTimer = undefined;
115
114
  };
115
+ const isActiveTarget = (target: RefreshTarget) =>
116
+ activeTarget?.cwd === target.cwd &&
117
+ activeTarget.generation === target.generation &&
118
+ target.generation === sessionGeneration;
116
119
 
117
- const refreshGit = (cwd: string, generation = sessionGeneration) => {
118
- if (!isActiveTarget(cwd, generation)) return;
119
- runGitRefresh(cwd, generation, ++gitRequestId);
120
+ const requestRefresh = (
121
+ target: RefreshTarget,
122
+ reason: WorkspaceRefreshInput["reason"] = "event",
123
+ ) => {
124
+ if (!loaded || !isActiveTarget(target)) return;
125
+ gitController.request({ cwd: target.cwd, config: loaded.config });
126
+ workspaceController.request(
127
+ workspaceInput(target.cwd, loaded.config, reason, runtime.workspace),
128
+ );
120
129
  };
121
- const scheduleGit = (ctx: ExtensionContext) => {
122
- if (!activeGitTarget || activeGitTarget.cwd !== ctx.cwd) return;
123
- const { cwd, generation } = activeGitTarget;
124
- const requestId = ++gitRequestId;
130
+ const scheduleRefresh = (ctx: ExtensionContext) => {
131
+ const target = activeTarget;
132
+ if (!target || target.cwd !== ctx.cwd) return;
125
133
  clearDebounce();
126
- gitDebounceTimer = setTimeout(() => {
127
- gitDebounceTimer = undefined;
128
- runGitRefresh(cwd, generation, requestId);
129
- }, GIT_EVENT_DEBOUNCE_MS);
134
+ eventDebounceTimer = setTimeout(() => {
135
+ eventDebounceTimer = undefined;
136
+ requestRefresh(target);
137
+ }, EVENT_DEBOUNCE_MS);
130
138
  };
131
139
 
132
140
  const installFooter = (ctx: ExtensionContext) => {
133
141
  const generation = ++sessionGeneration;
134
- const cwd = ctx.cwd;
142
+ const target = { cwd: ctx.cwd, generation };
135
143
  clearDebounce();
136
- pendingGitRefresh = undefined;
137
- runtime.gitStatus = undefined;
138
- runtime.gitWorktree = undefined;
144
+ gitController.stop();
145
+ workspaceController.stop();
146
+ runtime.git = undefined;
147
+ runtime.workspace = undefined;
139
148
  runtime.requestRender = undefined;
140
- activeGitTarget = ctx.mode === "tui" ? { cwd, generation } : undefined;
149
+ runtime.renderPreview = undefined;
150
+ activeTarget = ctx.mode === "tui" ? target : undefined;
141
151
  ctx.ui.setStatus("starship", undefined);
142
- if (!activeGitTarget || !loaded) return;
152
+ if (!activeTarget || !loaded) return;
153
+ gitController.start(generation);
154
+ workspaceController.start(generation);
143
155
 
144
- const installed = readInstalledPackageInfo(getAgentDir(), cwd, ctx.isProjectTrusted());
156
+ const installed = readInstalledPackageInfo(getAgentDir(), target.cwd, ctx.isProjectTrusted());
145
157
  runtime.extensionStatusIconAliases = installed.aliases;
146
158
  if (installed.hasStatuslineConflict && !conflictWarningShown) {
147
159
  conflictWarningShown = true;
@@ -153,17 +165,25 @@ export default function piStarship(pi: ExtensionAPI) {
153
165
 
154
166
  ctx.ui.setFooter((tui, _theme, footerData) => {
155
167
  runtime.requestRender = () => tui.requestRender();
168
+ runtime.renderPreview = (preview, width) => {
169
+ const snapshot = runtimeSnapshot(ctx, footerData, runtime);
170
+ return wrapFormattedStatusline(
171
+ renderStatusline(preview.config, snapshot, width).ansi,
172
+ width,
173
+ );
174
+ };
156
175
  const unsubscribe = footerData.onBranchChange(() => {
157
- runtime.gitStatus = undefined;
176
+ runtime.git = undefined;
177
+ gitController.clear();
158
178
  clearDebounce();
159
- refreshGit(cwd, generation);
179
+ requestRefresh(target);
160
180
  tui.requestRender();
161
181
  });
162
182
  const timer = setInterval(() => {
163
183
  clearDebounce();
164
- refreshGit(cwd, generation);
184
+ requestRefresh(target, "periodic");
165
185
  tui.requestRender();
166
- }, GIT_REFRESH_INTERVAL_MS);
186
+ }, REFRESH_INTERVAL_MS);
167
187
  let disposed = false;
168
188
 
169
189
  return {
@@ -172,25 +192,29 @@ export default function piStarship(pi: ExtensionAPI) {
172
192
  disposed = true;
173
193
  unsubscribe();
174
194
  clearInterval(timer);
175
- if (isActiveTarget(cwd, generation)) {
176
- activeGitTarget = undefined;
195
+ if (isActiveTarget(target)) {
196
+ activeTarget = undefined;
177
197
  clearDebounce();
178
- pendingGitRefresh = undefined;
179
- runtime.gitStatus = undefined;
180
- runtime.gitWorktree = undefined;
198
+ gitController.stop();
199
+ workspaceController.stop();
200
+ runtime.git = undefined;
201
+ runtime.workspace = undefined;
181
202
  runtime.requestRender = undefined;
203
+ runtime.renderPreview = undefined;
182
204
  }
183
205
  },
184
206
  invalidate() {},
185
207
  render(width: number): string[] {
186
208
  if (!loaded) return [];
187
209
  const snapshot = runtimeSnapshot(ctx, footerData, runtime);
188
- return wrapFormattedStatusline(renderStatusline(loaded.config, snapshot).ansi, width);
210
+ return wrapFormattedStatusline(
211
+ renderStatusline(loaded.config, snapshot, width).ansi,
212
+ width,
213
+ );
189
214
  },
190
215
  };
191
216
  });
192
- refreshGit(cwd, generation);
193
- refreshGitWorktree(cwd, generation);
217
+ requestRefresh(target, "initial");
194
218
  };
195
219
 
196
220
  const configPath = settingsFilePath(getAgentDir());
@@ -199,8 +223,17 @@ export default function piStarship(pi: ExtensionAPI) {
199
223
  getLoaded: () => loaded ?? loadStarshipConfig(configPath),
200
224
  apply(next) {
201
225
  loaded = next;
226
+ const target = activeTarget;
227
+ if (target) requestRefresh(target);
202
228
  refresh();
203
229
  },
230
+ renderPreview(preview, width) {
231
+ return (
232
+ runtime.renderPreview?.(preview, width) ?? [
233
+ "Live preview is unavailable until the footer is ready.",
234
+ ]
235
+ );
236
+ },
204
237
  });
205
238
 
206
239
  pi.on("session_start", (_event, ctx) => {
@@ -219,13 +252,15 @@ export default function piStarship(pi: ExtensionAPI) {
219
252
 
220
253
  pi.on("session_shutdown", (_event, ctx) => {
221
254
  sessionGeneration += 1;
222
- activeGitTarget = undefined;
255
+ activeTarget = undefined;
223
256
  clearDebounce();
224
- pendingGitRefresh = undefined;
225
- runtime.gitStatus = undefined;
226
- runtime.gitWorktree = undefined;
257
+ gitController.stop();
258
+ workspaceController.stop();
259
+ runtime.git = undefined;
260
+ runtime.workspace = undefined;
227
261
  runtime.extensionStatusIconAliases = EMPTY_ALIASES;
228
262
  runtime.requestRender = undefined;
263
+ runtime.renderPreview = undefined;
229
264
  ctx.ui.setFooter(undefined);
230
265
  ctx.ui.setStatus("starship", undefined);
231
266
  });
@@ -241,7 +276,7 @@ export default function piStarship(pi: ExtensionAPI) {
241
276
  });
242
277
  pi.on("agent_end", (_event, ctx) => {
243
278
  runtime.isStreaming = false;
244
- scheduleGit(ctx);
279
+ scheduleRefresh(ctx);
245
280
  refresh();
246
281
  });
247
282
  pi.on("turn_start", () => {
@@ -249,7 +284,7 @@ export default function piStarship(pi: ExtensionAPI) {
249
284
  refresh();
250
285
  });
251
286
  pi.on("turn_end", (_event, ctx) => {
252
- scheduleGit(ctx);
287
+ scheduleRefresh(ctx);
253
288
  refresh();
254
289
  });
255
290
  pi.on("tool_execution_start", (event) => {
@@ -261,11 +296,91 @@ export default function piStarship(pi: ExtensionAPI) {
261
296
  if (count <= 1) runtime.activeTools.delete(event.toolName);
262
297
  else runtime.activeTools.set(event.toolName, count - 1);
263
298
  runtime.lastCompletedTool = event.toolName;
264
- scheduleGit(ctx);
299
+ scheduleRefresh(ctx);
265
300
  refresh();
266
301
  });
267
302
  }
268
303
 
304
+ function workspaceInput(
305
+ cwd: string,
306
+ config: StarshipConfig,
307
+ reason: WorkspaceRefreshInput["reason"],
308
+ previous: WorkspaceSnapshot | undefined,
309
+ ): WorkspaceRefreshInput {
310
+ return {
311
+ cwd,
312
+ config,
313
+ environment: allowlistedEnvironment(config),
314
+ homeDir: homedir(),
315
+ platform: process.platform,
316
+ hostname: hostname(),
317
+ username: safeUsername(),
318
+ exec: execWorkspaceCommand,
319
+ reason,
320
+ previous,
321
+ };
322
+ }
323
+
324
+ const ENVIRONMENT_ALLOWLIST = [
325
+ "AWS_CONFIG_FILE",
326
+ "AWS_DEFAULT_PROFILE",
327
+ "AWS_DEFAULT_REGION",
328
+ "AWS_PROFILE",
329
+ "AWS_REGION",
330
+ "AZURE_CONFIG_DIR",
331
+ "CLOUDSDK_ACTIVE_CONFIG_NAME",
332
+ "CLOUDSDK_CONFIG",
333
+ "CODESPACES",
334
+ "CONDA_DEFAULT_ENV",
335
+ "DOCKER_CONFIG",
336
+ "DOCKER_CONTEXT",
337
+ "GUIX_ENVIRONMENT",
338
+ "IN_NIX_SHELL",
339
+ "KUBECONFIG",
340
+ "LOGNAME",
341
+ "NIX_SHELL_LEVEL",
342
+ "NIX_SHELL_NAME",
343
+ "OS_CLIENT_CONFIG_FILE",
344
+ "OS_CLOUD",
345
+ "OS_PROJECT_NAME",
346
+ "PATH",
347
+ "PIXI_ENVIRONMENT_NAME",
348
+ "PIXI_PROJECT_NAME",
349
+ "PYENV_VERSION",
350
+ "REMOTE_CONTAINERS",
351
+ "RUSTC",
352
+ "RUSTUP_TOOLCHAIN",
353
+ "SSH_CONNECTION",
354
+ "SSH_TTY",
355
+ "TF_DATA_DIR",
356
+ "TF_WORKSPACE",
357
+ "USER",
358
+ "USERNAME",
359
+ "VIRTUAL_ENV",
360
+ "WSL_DISTRO_NAME",
361
+ ] as const;
362
+
363
+ function allowlistedEnvironment(config: StarshipConfig): Record<string, string | undefined> {
364
+ const result: Record<string, string | undefined> = {};
365
+ const configured = config.modules.username.options.detect_env_vars;
366
+ const names = new Set([
367
+ ...ENVIRONMENT_ALLOWLIST,
368
+ ...(Array.isArray(configured)
369
+ ? configured.filter((name): name is string => typeof name === "string")
370
+ : []),
371
+ ]);
372
+ for (const name of names) result[name] = process.env[name];
373
+ return result;
374
+ }
375
+
376
+ function safeUsername(): string {
377
+ try {
378
+ return userInfo().username;
379
+ } catch {
380
+ return process.env.USER ?? process.env.USERNAME ?? "";
381
+ }
382
+ }
383
+
269
384
  function runtimeSnapshot(
270
385
  ctx: ExtensionContext,
271
386
  footerData: ReadonlyFooterDataProvider,
@@ -281,9 +396,14 @@ function runtimeSnapshot(
281
396
  lastCompletedTool: runtime.lastCompletedTool,
282
397
  contextUsage: ctx.getContextUsage() ?? undefined,
283
398
  tokenTotals: tokenTotals(ctx),
284
- gitBranch: footerData.getGitBranch(),
285
- gitStatus: runtime.gitStatus,
286
- gitWorktree: runtime.gitWorktree,
399
+ gitBranch: runtime.git?.branch?.name ?? footerData.getGitBranch(),
400
+ gitBranchDetails: runtime.git?.branch,
401
+ gitCommit: runtime.git?.commit,
402
+ gitState: runtime.git?.state,
403
+ gitMetrics: runtime.git?.metrics,
404
+ gitStatus: runtime.git?.status,
405
+ gitWorktree: runtime.git?.worktree,
406
+ workspace: runtime.workspace,
287
407
  extensionStatuses: footerData.getExtensionStatuses(),
288
408
  extensionStatusIconAliases: runtime.extensionStatusIconAliases,
289
409
  now: new Date(),
@@ -322,4 +442,10 @@ export function wrapFormattedStatusline(format: string, width: number): string[]
322
442
  return wrapTextWithAnsi(format, width);
323
443
  }
324
444
 
325
- export { parseGitStatusPorcelain, parseGitWorktree } from "./modules/git/runtime.js";
445
+ export {
446
+ parseGitDiffShortstat,
447
+ parseGitState,
448
+ parseGitStatusPorcelain,
449
+ parseGitStatusPorcelainV2,
450
+ parseGitWorktree,
451
+ } from "./modules/git/runtime.js";
@@ -0,0 +1,166 @@
1
+ import { join } from "node:path";
2
+ import { parse as parseYaml } from "yaml";
3
+ import {
4
+ exactAlias,
5
+ isRecord,
6
+ joinHome,
7
+ MAX_METADATA_FILE_BYTES,
8
+ optionBoolean,
9
+ optionMap,
10
+ parseIni,
11
+ safeMetadata,
12
+ } from "./helpers.js";
13
+ import type { CollectorContext, MutableModuleSnapshot } from "./types.js";
14
+
15
+ export async function collectCloud(context: CollectorContext): Promise<MutableModuleSnapshot> {
16
+ const result: MutableModuleSnapshot = {};
17
+ if (context.needs("aws")) {
18
+ const values = await collectAws(context);
19
+ if (values) result.aws = values;
20
+ }
21
+ if (context.needs("gcloud")) {
22
+ const values = await collectGcloud(context);
23
+ if (values) result.gcloud = values;
24
+ }
25
+ if (context.needs("azure")) {
26
+ const values = await collectAzure(context);
27
+ if (values) result.azure = values;
28
+ }
29
+ if (context.needs("openstack")) {
30
+ const values = await collectOpenstack(context);
31
+ if (values) result.openstack = values;
32
+ }
33
+ return result;
34
+ }
35
+
36
+ async function collectAws(context: CollectorContext): Promise<Record<string, string> | undefined> {
37
+ const env = context.input.environment;
38
+ const profile = safeMetadata(env.AWS_PROFILE ?? env.AWS_DEFAULT_PROFILE) ?? "default";
39
+ let region = safeMetadata(env.AWS_REGION ?? env.AWS_DEFAULT_REGION);
40
+ if (!region) {
41
+ const configPath =
42
+ safeMetadata(env.AWS_CONFIG_FILE, 1_024) ?? joinHome(context.input, ".aws", "config");
43
+ const source = await context.fs.readFile(configPath, MAX_METADATA_FILE_BYTES);
44
+ if (source) {
45
+ const section = profile === "default" ? "default" : `profile ${profile}`;
46
+ region = safeMetadata(parseIni(source)[section]?.region);
47
+ }
48
+ }
49
+ if (profile === "default" && !region && !env.AWS_PROFILE && !env.AWS_DEFAULT_PROFILE)
50
+ return undefined;
51
+ const values: Record<string, string> = {
52
+ profile: exactAlias(profile, optionMap(context, "aws", "profile_aliases")) ?? profile,
53
+ };
54
+ if (region)
55
+ values.region = exactAlias(region, optionMap(context, "aws", "region_aliases")) ?? region;
56
+ return values;
57
+ }
58
+
59
+ async function collectGcloud(
60
+ context: CollectorContext,
61
+ ): Promise<Record<string, string> | undefined> {
62
+ const env = context.input.environment;
63
+ const directory =
64
+ safeMetadata(env.CLOUDSDK_CONFIG, 1_024) ?? joinHome(context.input, ".config", "gcloud");
65
+ const active =
66
+ safeMetadata(env.CLOUDSDK_ACTIVE_CONFIG_NAME) ??
67
+ safeMetadata(await context.fs.readFile(join(directory, "active_config"), 256));
68
+ if (!active || !/^[A-Za-z0-9_-]+$/u.test(active)) return undefined;
69
+ const source = await context.fs.readFile(
70
+ join(directory, "configurations", `config_${active}`),
71
+ MAX_METADATA_FILE_BYTES,
72
+ );
73
+ if (!source) return { active };
74
+ const document = parseIni(source);
75
+ const account = safeMetadata(document.core?.account);
76
+ const project = safeMetadata(document.core?.project);
77
+ const region = safeMetadata(document.compute?.region);
78
+ const values: Record<string, string> = { active };
79
+ if (account) {
80
+ values.account = account;
81
+ const separator = account.lastIndexOf("@");
82
+ if (separator >= 0 && separator < account.length - 1)
83
+ values.domain = account.slice(separator + 1);
84
+ }
85
+ if (project) {
86
+ values.project =
87
+ exactAlias(project, optionMap(context, "gcloud", "project_aliases")) ?? project;
88
+ }
89
+ if (region)
90
+ values.region = exactAlias(region, optionMap(context, "gcloud", "region_aliases")) ?? region;
91
+ return values;
92
+ }
93
+
94
+ async function collectAzure(
95
+ context: CollectorContext,
96
+ ): Promise<Record<string, string> | undefined> {
97
+ const directory =
98
+ safeMetadata(context.input.environment.AZURE_CONFIG_DIR, 1_024) ??
99
+ joinHome(context.input, ".azure");
100
+ const source = await context.fs.readFile(
101
+ join(directory, "azureProfile.json"),
102
+ MAX_METADATA_FILE_BYTES,
103
+ );
104
+ if (!source) return undefined;
105
+ try {
106
+ const document = JSON.parse(source.replace(/^\uFEFF/u, "")) as unknown;
107
+ const subscriptions =
108
+ isRecord(document) && Array.isArray(document.subscriptions)
109
+ ? document.subscriptions.filter(isRecord)
110
+ : [];
111
+ const selected = subscriptions.find((item) => item.isDefault === true) ?? subscriptions[0];
112
+ const subscription = safeMetadata(selected?.name);
113
+ if (!subscription) return undefined;
114
+ const values: Record<string, string> = {
115
+ subscription:
116
+ exactAlias(subscription, optionMap(context, "azure", "subscription_aliases")) ??
117
+ subscription,
118
+ };
119
+ if (optionBoolean(context, "azure", "show_username")) {
120
+ const user = isRecord(selected?.user) ? selected.user : undefined;
121
+ const username = safeMetadata(user?.name);
122
+ if (username) values.username = username;
123
+ }
124
+ return values;
125
+ } catch {
126
+ return undefined;
127
+ }
128
+ }
129
+
130
+ async function collectOpenstack(
131
+ context: CollectorContext,
132
+ ): Promise<Record<string, string> | undefined> {
133
+ const env = context.input.environment;
134
+ const cloud = safeMetadata(env.OS_CLOUD);
135
+ let project = safeMetadata(env.OS_PROJECT_NAME);
136
+ if (!cloud) return undefined;
137
+ if (!project) {
138
+ const path =
139
+ safeMetadata(env.OS_CLIENT_CONFIG_FILE, 1_024) ??
140
+ joinHome(context.input, ".config", "openstack", "clouds.yaml");
141
+ const source = await context.fs.readFile(path, MAX_METADATA_FILE_BYTES);
142
+ if (source) {
143
+ try {
144
+ const document = parseYaml(source) as unknown;
145
+ const clouds =
146
+ isRecord(document) && isRecord(document.clouds) ? document.clouds : undefined;
147
+ const selected =
148
+ clouds && Object.hasOwn(clouds, cloud) && isRecord(clouds[cloud])
149
+ ? clouds[cloud]
150
+ : undefined;
151
+ const auth = isRecord(selected?.auth) ? selected.auth : undefined;
152
+ project = safeMetadata(auth?.project_name);
153
+ } catch {
154
+ // Malformed YAML is ignored.
155
+ }
156
+ }
157
+ }
158
+ const values: Record<string, string> = {
159
+ cloud: exactAlias(cloud, optionMap(context, "openstack", "cloud_aliases")) ?? cloud,
160
+ };
161
+ if (project) {
162
+ values.project =
163
+ exactAlias(project, optionMap(context, "openstack", "project_aliases")) ?? project;
164
+ }
165
+ return values;
166
+ }