@narumitw/pi-starship 0.49.3 → 0.50.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.
Files changed (100) hide show
  1. package/NOTICES.md +4 -2
  2. package/README.md +62 -16
  3. package/package.json +10 -11
  4. package/src/command-contract.ts +13 -0
  5. package/src/command-inspector.ts +198 -0
  6. package/src/command-preset-picker.ts +203 -0
  7. package/src/command-preview.ts +206 -0
  8. package/src/commands.ts +784 -0
  9. package/src/config.ts +794 -0
  10. package/src/format/formatter.ts +275 -0
  11. package/src/format/style.ts +278 -0
  12. package/src/index.ts +1 -1
  13. package/src/modules/activity.ts +38 -0
  14. package/src/modules/brand.ts +13 -0
  15. package/src/modules/cache.ts +23 -0
  16. package/src/modules/catalog.ts +124 -0
  17. package/src/modules/cloud.ts +74 -0
  18. package/src/modules/context.ts +33 -0
  19. package/src/modules/cost.ts +31 -0
  20. package/src/modules/deployment.ts +61 -0
  21. package/src/modules/development.ts +112 -0
  22. package/src/modules/directory.ts +151 -0
  23. package/src/modules/display.ts +14 -0
  24. package/src/modules/execution.ts +84 -0
  25. package/src/modules/extension-status.ts +93 -0
  26. package/src/modules/fill.ts +14 -0
  27. package/src/modules/git/branch.ts +31 -0
  28. package/src/modules/git/commit.ts +29 -0
  29. package/src/modules/git/metrics.ts +26 -0
  30. package/src/modules/git/runtime.ts +415 -0
  31. package/src/modules/git/state.ts +21 -0
  32. package/src/modules/git/status.ts +87 -0
  33. package/src/modules/git/worktree.ts +16 -0
  34. package/src/modules/github-pr.ts +24 -0
  35. package/src/modules/helpers.ts +5 -0
  36. package/src/modules/index.ts +31 -0
  37. package/src/modules/inspection.ts +138 -0
  38. package/src/modules/languages.ts +87 -0
  39. package/src/modules/model.ts +85 -0
  40. package/src/modules/package.ts +17 -0
  41. package/src/modules/provider.ts +13 -0
  42. package/src/modules/render.ts +166 -0
  43. package/src/modules/terminal.ts +60 -0
  44. package/src/modules/thinking.ts +13 -0
  45. package/src/modules/time.ts +20 -0
  46. package/src/modules/tokens.ts +18 -0
  47. package/src/modules/truncation.ts +37 -0
  48. package/src/modules/turn.ts +13 -0
  49. package/src/modules/types.ts +189 -0
  50. package/src/modules/workspace-helpers.ts +10 -0
  51. package/src/pi-starship.ts +619 -0
  52. package/src/presets/bracketed-segments.ts +45 -0
  53. package/src/presets/catalog.ts +138 -0
  54. package/src/presets/catppuccin-powerline.ts +90 -0
  55. package/src/presets/gruvbox-rainbow.ts +66 -0
  56. package/src/presets/jetpack.ts +51 -0
  57. package/src/presets/minimal.ts +23 -0
  58. package/src/presets/nerd-font-symbols.ts +27 -0
  59. package/src/presets/no-empty-icons.ts +47 -0
  60. package/src/presets/no-nerd-font.ts +51 -0
  61. package/src/presets/no-runtime-versions.ts +52 -0
  62. package/src/presets/pastel-powerline.ts +53 -0
  63. package/src/presets/plain-text-symbols.ts +52 -0
  64. package/src/presets/pure-preset.ts +55 -0
  65. package/src/presets/tokyo-night.ts +53 -0
  66. package/src/runtime/cloud.ts +166 -0
  67. package/src/runtime/command.ts +123 -0
  68. package/src/runtime/deployment.ts +201 -0
  69. package/src/runtime/development.ts +153 -0
  70. package/src/runtime/execution.ts +151 -0
  71. package/src/runtime/github-pr.ts +332 -0
  72. package/src/runtime/helpers.ts +274 -0
  73. package/src/runtime/languages.ts +205 -0
  74. package/src/runtime/package.ts +112 -0
  75. package/src/runtime/refresh-controller.ts +107 -0
  76. package/src/runtime/types.ts +63 -0
  77. package/src/runtime/workspace.ts +147 -0
  78. package/src/usage.ts +53 -0
  79. package/dist/chunks/chunk-CKNSOLSW.ts +0 -10
  80. package/dist/chunks/chunk-CKNSOLSW.ts.map +0 -7
  81. package/dist/chunks/chunk-G2GG2V6Q.ts +0 -218
  82. package/dist/chunks/chunk-G2GG2V6Q.ts.map +0 -7
  83. package/dist/chunks/chunk-Q6DLIM7H.ts +0 -2492
  84. package/dist/chunks/chunk-Q6DLIM7H.ts.map +0 -7
  85. package/dist/chunks/cloud-JBSZWTB6.ts +0 -142
  86. package/dist/chunks/cloud-JBSZWTB6.ts.map +0 -7
  87. package/dist/chunks/commands-BSQZ2R4M.ts +0 -757
  88. package/dist/chunks/commands-BSQZ2R4M.ts.map +0 -7
  89. package/dist/chunks/deployment-ZNYM4B6W.ts +0 -172
  90. package/dist/chunks/deployment-ZNYM4B6W.ts.map +0 -7
  91. package/dist/chunks/development-TNWZ5SRC.ts +0 -132
  92. package/dist/chunks/development-TNWZ5SRC.ts.map +0 -7
  93. package/dist/chunks/execution-QHAP4U33.ts +0 -132
  94. package/dist/chunks/execution-QHAP4U33.ts.map +0 -7
  95. package/dist/chunks/languages-DPWDCH6Q.ts +0 -184
  96. package/dist/chunks/languages-DPWDCH6Q.ts.map +0 -7
  97. package/dist/chunks/package-MXN2YFLX.ts +0 -104
  98. package/dist/chunks/package-MXN2YFLX.ts.map +0 -7
  99. package/dist/pi-starship.ts +0 -1350
  100. package/dist/pi-starship.ts.map +0 -7
@@ -0,0 +1,93 @@
1
+ import { defineModule } from "./types.js";
2
+
3
+ export const extensionStatusModule = defineModule({
4
+ name: "extension_status",
5
+ variables: ["symbol", "statuses", "count"],
6
+ defaults: {
7
+ format: "[$statuses]($style)",
8
+ symbol: "",
9
+ style: "dimmed white",
10
+ disabled: false,
11
+ },
12
+ values: ({ runtime, extensionStatus }) => {
13
+ const statuses = [...runtime.extensionStatuses.entries()]
14
+ .filter(([key, value]) => key !== "starship" && value.trim())
15
+ .map(([key, value]) => formatExtensionStatus(key, value, extensionStatus.icons))
16
+ .slice(0, extensionStatus.maxStatuses);
17
+ if (statuses.length === 0) return undefined;
18
+ return {
19
+ statuses: statuses.join(extensionStatus.separator),
20
+ count: `${statuses.length}`,
21
+ };
22
+ },
23
+ });
24
+
25
+ export function formatExtensionStatus(
26
+ key: string,
27
+ value: string,
28
+ configuredIcons: Readonly<Record<string, string>>,
29
+ ): string {
30
+ const status = splitExtensionStatusIcon(stripExtensionStatusPrefix(key, value));
31
+ const icon = extensionStatusIcon(key, status.icon, configuredIcons);
32
+ const text = simplifyExtensionStatusText(status.text);
33
+ return icon ? `${icon} ${text}` : text;
34
+ }
35
+
36
+ function extensionStatusIcon(
37
+ key: string,
38
+ leadingIcon: string | undefined,
39
+ configuredIcons: Readonly<Record<string, string>>,
40
+ ): string {
41
+ if (Object.hasOwn(configuredIcons, key)) return configuredIcons[key] ?? "";
42
+ const namespaceIcon = configuredNamespaceIcon(key, configuredIcons);
43
+ if (namespaceIcon !== undefined) return namespaceIcon;
44
+ const fallbackIcon = Object.hasOwn(configuredIcons, "fallback")
45
+ ? configuredIcons.fallback
46
+ : undefined;
47
+ return leadingIcon ?? fallbackIcon ?? "🔌";
48
+ }
49
+
50
+ function configuredNamespaceIcon(
51
+ key: string,
52
+ configuredIcons: Readonly<Record<string, string>>,
53
+ ): string | undefined {
54
+ let match: { baseLength: number; icon: string } | undefined;
55
+ for (const [selector, icon] of Object.entries(configuredIcons)) {
56
+ if (!selector.endsWith(":*")) continue;
57
+ const base = selector.slice(0, -2);
58
+ if (!base || !key.startsWith(`${base}:`)) continue;
59
+ if (!match || base.length > match.baseLength) match = { baseLength: base.length, icon };
60
+ }
61
+ return match?.icon;
62
+ }
63
+
64
+ function splitExtensionStatusIcon(value: string): { icon?: string; text: string } {
65
+ const trimmed = value.trim();
66
+ const [first, ...rest] = trimmed.split(/\s+/u);
67
+ if (first && isEmojiOnlyToken(first)) return { icon: first, text: rest.join(" ") };
68
+ return { text: trimmed };
69
+ }
70
+
71
+ function isEmojiOnlyToken(value: string): boolean {
72
+ return /^(?=.*(?:\p{Extended_Pictographic}|\p{Regional_Indicator}|[0-9#*]\ufe0f?\u20e3))(?:\p{Extended_Pictographic}|\p{Emoji_Modifier}|\p{Regional_Indicator}|\u200d|\ufe0f|[0-9#*]\ufe0f?\u20e3)+$/u.test(
73
+ value,
74
+ );
75
+ }
76
+
77
+ function stripExtensionStatusPrefix(key: string, value: string): string {
78
+ return value.trim().replace(new RegExp(`^${escapeRegExp(key)}\\s*:\\s*`, "iu"), "");
79
+ }
80
+
81
+ function simplifyExtensionStatusText(value: string): string {
82
+ return value
83
+ .trim()
84
+ .replace(/\bready\b/giu, "✓")
85
+ .replace(/\bmissing\b/giu, "✗")
86
+ .replace(/,\s*/g, " ")
87
+ .replace(/\s+\([^)]*\)\s*$/u, "")
88
+ .replace(/\s+/gu, " ");
89
+ }
90
+
91
+ function escapeRegExp(value: string): string {
92
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
93
+ }
@@ -0,0 +1,14 @@
1
+ import { defineModule } from "./types.js";
2
+
3
+ export const fillModule = defineModule({
4
+ name: "fill",
5
+ variables: ["symbol"],
6
+ defaults: {
7
+ format: "[$symbol]($style)",
8
+ symbol: " ",
9
+ style: "bold black",
10
+ disabled: false,
11
+ },
12
+ layout: "fill",
13
+ values: () => ({}),
14
+ });
@@ -0,0 +1,31 @@
1
+ import { truncateLeadingGraphemes } from "../truncation.js";
2
+ import { defineModule } from "../types.js";
3
+
4
+ export const gitBranchModule = defineModule({
5
+ name: "git_branch",
6
+ variables: ["symbol", "branch", "remote_name", "remote_branch"],
7
+ defaults: {
8
+ format: "[ $symbol $branch ]($style)",
9
+ symbol: "🌿",
10
+ style: "bold purple",
11
+ disabled: false,
12
+ },
13
+ options: {
14
+ // Starship uses i64::MAX as its effective no-truncation default. Zero is the
15
+ // equivalent stable TOML representation in pi-starship's bounded integer schema.
16
+ truncation_length: { kind: "integer", default: 0, minimum: 0, maximum: 1_000_000 },
17
+ truncation_symbol: { kind: "string", default: "…" },
18
+ },
19
+ values: ({ runtime, options }) => {
20
+ const branch = runtime.gitBranchDetails;
21
+ const name = branch?.name ?? runtime.gitBranch;
22
+ if (!name) return undefined;
23
+ const length = typeof options.truncation_length === "number" ? options.truncation_length : 0;
24
+ const symbol = typeof options.truncation_symbol === "string" ? options.truncation_symbol : "…";
25
+ return {
26
+ branch: truncateLeadingGraphemes(name, length, symbol),
27
+ remote_name: truncateLeadingGraphemes(branch?.remoteName ?? "", length, symbol),
28
+ remote_branch: truncateLeadingGraphemes(branch?.remoteBranch ?? "", length, symbol),
29
+ };
30
+ },
31
+ });
@@ -0,0 +1,29 @@
1
+ import { defineModule } from "../types.js";
2
+
3
+ const DEFAULT_HASH_LENGTH = 7;
4
+
5
+ export const gitCommitModule = defineModule({
6
+ name: "git_commit",
7
+ variables: ["symbol", "hash", "tag"],
8
+ defaults: {
9
+ format: "[ ($hash) ]($style)",
10
+ symbol: "",
11
+ style: "green bold",
12
+ disabled: false,
13
+ },
14
+ options: {
15
+ commit_hash_length: { kind: "integer", default: DEFAULT_HASH_LENGTH, minimum: 0, maximum: 64 },
16
+ },
17
+ values: ({ runtime, options }) => {
18
+ const commit = runtime.gitCommit;
19
+ if (!commit) return undefined;
20
+ const hashLength =
21
+ typeof options.commit_hash_length === "number"
22
+ ? options.commit_hash_length
23
+ : DEFAULT_HASH_LENGTH;
24
+ return {
25
+ hash: commit.hash.slice(0, hashLength),
26
+ tag: commit.tag ? ` 🏷 ${commit.tag}` : "",
27
+ };
28
+ },
29
+ });
@@ -0,0 +1,26 @@
1
+ import { defineModule } from "../types.js";
2
+
3
+ export const gitMetricsModule = defineModule({
4
+ name: "git_metrics",
5
+ variables: ["symbol", "added", "deleted"],
6
+ defaults: {
7
+ format: "([+$added]($added_style) )([-$deleted]($deleted_style) )",
8
+ symbol: "",
9
+ style: "none",
10
+ disabled: true,
11
+ },
12
+ styleDefaults: {
13
+ added_style: "bold green",
14
+ deleted_style: "bold red",
15
+ },
16
+ styleVariables: ["added_style", "deleted_style"],
17
+ resolveStyleVariables: ({ styles }) => styles,
18
+ values: ({ runtime }) => {
19
+ const metrics = runtime.gitMetrics;
20
+ if (!metrics || (metrics.added === 0 && metrics.deleted === 0)) return undefined;
21
+ return {
22
+ added: metrics.added > 0 ? metrics.added.toString() : "",
23
+ deleted: metrics.deleted > 0 ? metrics.deleted.toString() : "",
24
+ };
25
+ },
26
+ });
@@ -0,0 +1,415 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { basename, isAbsolute, join, resolve } from "node:path";
3
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
+ import type {
5
+ GitBranchSnapshot,
6
+ GitCommitSnapshot,
7
+ GitMetricsSnapshot,
8
+ GitSnapshot,
9
+ GitStateSnapshot,
10
+ GitStatusSnapshot,
11
+ GitWorktreeSnapshot,
12
+ } from "../types.js";
13
+
14
+ const GIT_TIMEOUT_MS = 3_000;
15
+
16
+ export interface ReadGitSnapshotOptions {
17
+ includeMetrics: boolean;
18
+ includeTag: boolean;
19
+ signal?: AbortSignal;
20
+ }
21
+
22
+ export async function readGitSnapshot(
23
+ pi: ExtensionAPI,
24
+ cwd: string,
25
+ options: ReadGitSnapshotOptions,
26
+ ): Promise<GitSnapshot | undefined> {
27
+ const statusPromise = pi.exec(
28
+ "git",
29
+ [
30
+ "--no-optional-locks",
31
+ "status",
32
+ "--porcelain=v2",
33
+ "--branch",
34
+ "--show-stash",
35
+ "--untracked-files=normal",
36
+ ],
37
+ { cwd, signal: options.signal, timeout: GIT_TIMEOUT_MS },
38
+ );
39
+ const metadataPromise = pi.exec(
40
+ "git",
41
+ ["rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir", "--git-dir"],
42
+ { cwd, signal: options.signal, timeout: GIT_TIMEOUT_MS },
43
+ );
44
+ const metricsPromise = options.includeMetrics
45
+ ? pi.exec("git", ["--no-optional-locks", "diff", "--shortstat", "HEAD", "--"], {
46
+ cwd,
47
+ signal: options.signal,
48
+ timeout: GIT_TIMEOUT_MS,
49
+ })
50
+ : Promise.resolve(undefined);
51
+ const tagPromise = options.includeTag
52
+ ? pi.exec("git", ["describe", "--tags", "--exact-match", "HEAD"], {
53
+ cwd,
54
+ signal: options.signal,
55
+ timeout: GIT_TIMEOUT_MS,
56
+ })
57
+ : Promise.resolve(undefined);
58
+
59
+ const [statusResult, metadataResult, metricsResult, tagResult] = await Promise.all([
60
+ statusPromise,
61
+ metadataPromise,
62
+ metricsPromise,
63
+ tagPromise,
64
+ ]);
65
+ if (statusResult.code !== 0 || statusResult.killed) return undefined;
66
+
67
+ const parsed = parseGitStatusPorcelainV2(statusResult.stdout);
68
+ const metadata =
69
+ metadataResult.code === 0 && !metadataResult.killed
70
+ ? parseGitRepositoryMetadata(metadataResult.stdout)
71
+ : undefined;
72
+ const commit = withTag(parsed.commit, tagResult);
73
+ const metrics =
74
+ metricsResult && metricsResult.code === 0 && !metricsResult.killed
75
+ ? parseGitDiffShortstat(metricsResult.stdout)
76
+ : undefined;
77
+
78
+ return {
79
+ ...parsed,
80
+ root: metadata?.root,
81
+ commit,
82
+ state: metadata ? parseGitState(metadata.gitDirectory) : undefined,
83
+ metrics,
84
+ worktree: metadata?.worktree,
85
+ };
86
+ }
87
+
88
+ export async function readGitStatus(
89
+ pi: ExtensionAPI,
90
+ cwd: string,
91
+ ): Promise<GitStatusSnapshot | undefined> {
92
+ const result = await pi.exec(
93
+ "git",
94
+ [
95
+ "--no-optional-locks",
96
+ "status",
97
+ "--porcelain=v2",
98
+ "--branch",
99
+ "--show-stash",
100
+ "--untracked-files=normal",
101
+ ],
102
+ { cwd, timeout: GIT_TIMEOUT_MS },
103
+ );
104
+ if (result.code !== 0 || result.killed) return undefined;
105
+ return parseGitStatusPorcelainV2(result.stdout).status;
106
+ }
107
+
108
+ export async function readGitWorktree(
109
+ pi: ExtensionAPI,
110
+ cwd: string,
111
+ ): Promise<GitWorktreeSnapshot | undefined> {
112
+ const result = await pi.exec(
113
+ "git",
114
+ ["rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir", "--git-dir"],
115
+ { cwd, timeout: GIT_TIMEOUT_MS },
116
+ );
117
+ if (result.code !== 0 || result.killed) return undefined;
118
+ return parseGitRepositoryMetadata(result.stdout)?.worktree;
119
+ }
120
+
121
+ interface ParsedGitStatus {
122
+ branch?: GitBranchSnapshot;
123
+ commit?: GitCommitSnapshot;
124
+ status: GitStatusSnapshot;
125
+ }
126
+
127
+ export function parseGitStatusPorcelainV2(output: string): ParsedGitStatus {
128
+ const status = emptyGitStatus();
129
+ let branchName: string | undefined;
130
+ let commitHash: string | undefined;
131
+ let upstream: string | undefined;
132
+
133
+ for (const line of output.split(/\r?\n/u)) {
134
+ if (!line) continue;
135
+ if (line.startsWith("# branch.oid ")) {
136
+ const value = line.slice("# branch.oid ".length).trim();
137
+ if (value && value !== "(initial)") commitHash = value;
138
+ continue;
139
+ }
140
+ if (line.startsWith("# branch.head ")) {
141
+ branchName = line.slice("# branch.head ".length).trim();
142
+ continue;
143
+ }
144
+ if (line.startsWith("# branch.upstream ")) {
145
+ upstream = line.slice("# branch.upstream ".length).trim();
146
+ continue;
147
+ }
148
+ if (line.startsWith("# branch.ab ")) {
149
+ const match = /^# branch\.ab \+(\d+) -(\d+)$/u.exec(line);
150
+ status.ahead = match?.[1] ? Number(match[1]) : 0;
151
+ status.behind = match?.[2] ? Number(match[2]) : 0;
152
+ continue;
153
+ }
154
+ if (line.startsWith("# stash ")) {
155
+ const count = Number(line.slice("# stash ".length));
156
+ status.stashed = Number.isSafeInteger(count) && count > 0 ? count : 0;
157
+ continue;
158
+ }
159
+ addPorcelainV2Status(status, line);
160
+ }
161
+ finalizeStatus(status);
162
+
163
+ const detached = branchName === "(detached)";
164
+ const remote = splitUpstream(upstream);
165
+ const branch = branchName
166
+ ? {
167
+ name: detached ? "HEAD" : branchName,
168
+ ...remote,
169
+ detached,
170
+ }
171
+ : undefined;
172
+ const commit = commitHash ? { hash: commitHash, detached } : undefined;
173
+ return { branch, commit, status };
174
+ }
175
+
176
+ export function parseGitStatusPorcelain(output: string): GitStatusSnapshot {
177
+ const status = emptyGitStatus();
178
+ for (const line of output.split(/\r?\n/u)) {
179
+ if (!line) continue;
180
+ if (line.startsWith("## ")) {
181
+ const ahead = /\bahead (\d+)/u.exec(line);
182
+ const behind = /\bbehind (\d+)/u.exec(line);
183
+ status.ahead = ahead?.[1] ? Number(ahead[1]) : 0;
184
+ status.behind = behind?.[1] ? Number(behind[1]) : 0;
185
+ continue;
186
+ }
187
+ const indexStatus = line[0] ?? " ";
188
+ const worktreeStatus = line[1] ?? " ";
189
+ if (indexStatus === "?" && worktreeStatus === "?") {
190
+ status.untracked += 1;
191
+ continue;
192
+ }
193
+ if (isConflict(indexStatus, worktreeStatus)) {
194
+ status.conflicted += 1;
195
+ continue;
196
+ }
197
+ addNormalStatus(status, indexStatus, worktreeStatus);
198
+ if (indexStatus === "R" || indexStatus === "C") status.renamed += 1;
199
+ }
200
+ finalizeStatus(status);
201
+ return status;
202
+ }
203
+
204
+ export function parseGitDiffShortstat(output: string): GitMetricsSnapshot {
205
+ return {
206
+ added: parseShortstatMetric(output, "insertion(+)", "insertions(+)") ?? 0,
207
+ deleted: parseShortstatMetric(output, "deletion(-)", "deletions(-)") ?? 0,
208
+ };
209
+ }
210
+
211
+ function parseShortstatMetric(
212
+ output: string,
213
+ singularLabel: string,
214
+ pluralLabel: string,
215
+ ): number | undefined {
216
+ for (const field of output.split(",")) {
217
+ const trimmed = field.trim();
218
+ const separator = trimmed.indexOf(" ");
219
+ if (separator <= 0) continue;
220
+ const label = trimmed.slice(separator + 1).trimStart();
221
+ if (label !== singularLabel && label !== pluralLabel) continue;
222
+ const countText = trimmed.slice(0, separator);
223
+ for (const character of countText) {
224
+ if (character < "0" || character > "9") return undefined;
225
+ }
226
+ const count = Number(countText);
227
+ return Number.isSafeInteger(count) ? count : undefined;
228
+ }
229
+ return undefined;
230
+ }
231
+
232
+ export function parseGitState(gitDirectory: string): GitStateSnapshot | undefined {
233
+ const rebaseMerge = join(gitDirectory, "rebase-merge");
234
+ if (existsSync(rebaseMerge))
235
+ return operationWithProgress("REBASING", rebaseMerge, "msgnum", "end");
236
+
237
+ const rebaseApply = join(gitDirectory, "rebase-apply");
238
+ if (existsSync(rebaseApply)) {
239
+ const state = existsSync(join(rebaseApply, "applying"))
240
+ ? "AM"
241
+ : existsSync(join(rebaseApply, "rebasing"))
242
+ ? "REBASING"
243
+ : "AM/REBASE";
244
+ return operationWithProgress(state, rebaseApply, "next", "last");
245
+ }
246
+ if (existsSync(join(gitDirectory, "MERGE_HEAD"))) return { state: "MERGING" };
247
+ if (existsSync(join(gitDirectory, "REVERT_HEAD"))) return { state: "REVERTING" };
248
+ if (existsSync(join(gitDirectory, "CHERRY_PICK_HEAD"))) return { state: "CHERRY-PICKING" };
249
+ if (existsSync(join(gitDirectory, "BISECT_LOG"))) return { state: "BISECTING" };
250
+ return undefined;
251
+ }
252
+
253
+ interface GitRepositoryMetadata {
254
+ root: string;
255
+ gitDirectory: string;
256
+ worktree?: GitWorktreeSnapshot;
257
+ }
258
+
259
+ function parseGitRepositoryMetadata(output: string): GitRepositoryMetadata | undefined {
260
+ const lines = output.trimEnd().split(/\r?\n/u);
261
+ if (lines.length !== 3) return undefined;
262
+ const [path, commonDir, gitDirectory] = lines;
263
+ if (!path || !commonDir || !gitDirectory) return undefined;
264
+ if (![path, commonDir, gitDirectory].every(isAbsolute)) return undefined;
265
+ return {
266
+ root: path,
267
+ gitDirectory,
268
+ worktree: samePath(commonDir, gitDirectory)
269
+ ? undefined
270
+ : { name: basename(path) || path, path },
271
+ };
272
+ }
273
+
274
+ export function parseGitWorktree(output: string): GitWorktreeSnapshot | undefined {
275
+ return parseGitRepositoryMetadata(output)?.worktree;
276
+ }
277
+
278
+ function addPorcelainV2Status(status: GitStatusSnapshot, line: string) {
279
+ const kind = line[0];
280
+ if (kind === "?") {
281
+ status.untracked += 1;
282
+ return;
283
+ }
284
+ if (kind === "u") {
285
+ status.conflicted += 1;
286
+ return;
287
+ }
288
+ if (kind !== "1" && kind !== "2") return;
289
+ const indexStatus = line[2] ?? ".";
290
+ const worktreeStatus = line[3] ?? ".";
291
+ addNormalStatus(status, indexStatus, worktreeStatus);
292
+ if (kind === "2") status.renamed += 1;
293
+ }
294
+
295
+ function addNormalStatus(status: GitStatusSnapshot, indexStatus: string, worktreeStatus: string) {
296
+ if (indexStatus === "A") status.indexAdded += 1;
297
+ if (indexStatus === "D") status.indexDeleted += 1;
298
+ if (indexStatus === "M") status.indexModified += 1;
299
+ if (indexStatus === "T") status.indexTypechanged += 1;
300
+ if (worktreeStatus === "A") status.worktreeAdded += 1;
301
+ if (worktreeStatus === "D") status.worktreeDeleted += 1;
302
+ if (worktreeStatus === "M") status.worktreeModified += 1;
303
+ if (worktreeStatus === "T") status.worktreeTypechanged += 1;
304
+ }
305
+
306
+ function finalizeStatus(status: GitStatusSnapshot) {
307
+ status.deleted = status.worktreeDeleted + status.indexDeleted;
308
+ status.modified = status.worktreeModified + status.worktreeAdded;
309
+ status.staged = status.indexModified + status.indexAdded + status.indexTypechanged;
310
+ status.typechanged = status.worktreeTypechanged;
311
+ }
312
+
313
+ function emptyGitStatus(): GitStatusSnapshot {
314
+ return {
315
+ ahead: 0,
316
+ behind: 0,
317
+ stashed: 0,
318
+ conflicted: 0,
319
+ deleted: 0,
320
+ renamed: 0,
321
+ modified: 0,
322
+ staged: 0,
323
+ typechanged: 0,
324
+ untracked: 0,
325
+ worktreeAdded: 0,
326
+ worktreeDeleted: 0,
327
+ worktreeModified: 0,
328
+ worktreeTypechanged: 0,
329
+ indexAdded: 0,
330
+ indexDeleted: 0,
331
+ indexModified: 0,
332
+ indexTypechanged: 0,
333
+ };
334
+ }
335
+
336
+ function splitUpstream(upstream: string | undefined): {
337
+ remoteName?: string;
338
+ remoteBranch?: string;
339
+ } {
340
+ if (!upstream) return {};
341
+ const separator = upstream.indexOf("/");
342
+ if (separator <= 0 || separator === upstream.length - 1) return { remoteBranch: upstream };
343
+ return {
344
+ remoteName: upstream.slice(0, separator),
345
+ remoteBranch: upstream.slice(separator + 1),
346
+ };
347
+ }
348
+
349
+ function withTag(
350
+ commit: GitCommitSnapshot | undefined,
351
+ result:
352
+ | {
353
+ stdout: string;
354
+ code: number;
355
+ killed: boolean;
356
+ }
357
+ | undefined,
358
+ ): GitCommitSnapshot | undefined {
359
+ if (!commit || !result || result.code !== 0 || result.killed) return commit;
360
+ const tag = result.stdout.trim();
361
+ return tag ? { ...commit, tag: tag.split(/\r?\n/u)[0] } : commit;
362
+ }
363
+
364
+ function operationWithProgress(
365
+ state: string,
366
+ directory: string,
367
+ currentName: string,
368
+ totalName: string,
369
+ ): GitStateSnapshot {
370
+ const progressCurrent = readPositiveInteger(join(directory, currentName));
371
+ const progressTotal = readPositiveInteger(join(directory, totalName));
372
+ return progressCurrent !== undefined && progressTotal !== undefined
373
+ ? { state, progressCurrent, progressTotal }
374
+ : { state };
375
+ }
376
+
377
+ function readPositiveInteger(path: string): number | undefined {
378
+ try {
379
+ const value = Number(readFileSync(path, "utf8").trim());
380
+ return Number.isSafeInteger(value) && value > 0 ? value : undefined;
381
+ } catch {
382
+ return undefined;
383
+ }
384
+ }
385
+
386
+ function samePath(left: string, right: string): boolean {
387
+ const normalizedLeft = resolve(left);
388
+ const normalizedRight = resolve(right);
389
+ return process.platform === "win32"
390
+ ? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
391
+ : normalizedLeft === normalizedRight;
392
+ }
393
+
394
+ function isConflict(indexStatus: string, worktreeStatus: string): boolean {
395
+ return (
396
+ (indexStatus === "D" && worktreeStatus === "D") ||
397
+ (indexStatus === "A" && worktreeStatus === "A") ||
398
+ indexStatus === "U" ||
399
+ worktreeStatus === "U"
400
+ );
401
+ }
402
+
403
+ export function gitStatusEqual(
404
+ left: GitStatusSnapshot | undefined,
405
+ right: GitStatusSnapshot | undefined,
406
+ ): boolean {
407
+ return JSON.stringify(left) === JSON.stringify(right);
408
+ }
409
+
410
+ export function gitSnapshotEqual(
411
+ left: GitSnapshot | undefined,
412
+ right: GitSnapshot | undefined,
413
+ ): boolean {
414
+ return JSON.stringify(left) === JSON.stringify(right);
415
+ }
@@ -0,0 +1,21 @@
1
+ import { defineModule } from "../types.js";
2
+
3
+ export const gitStateModule = defineModule({
4
+ name: "git_state",
5
+ variables: ["symbol", "state", "progress_current", "progress_total"],
6
+ defaults: {
7
+ format: "[ ($state( $progress_current/$progress_total)) ]($style)",
8
+ symbol: "",
9
+ style: "bold yellow",
10
+ disabled: false,
11
+ },
12
+ values: ({ runtime }) => {
13
+ const state = runtime.gitState;
14
+ if (!state) return undefined;
15
+ return {
16
+ state: state.state,
17
+ progress_current: state.progressCurrent?.toString() ?? "",
18
+ progress_total: state.progressTotal?.toString() ?? "",
19
+ };
20
+ },
21
+ });