claudeup 4.19.0 → 4.22.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.
- package/bin/claudeup.js +43 -19
- package/package.json +14 -19
- package/scripts/build-binaries.ts +77 -0
- package/scripts/check-optional-deps.ts +49 -0
- package/scripts/test-isolated.ts +43 -0
- package/src/__tests__/cli-router.test.ts +65 -0
- package/src/__tests__/conventions-integration.test.ts +745 -0
- package/src/__tests__/conventions-manager.test.ts +1172 -0
- package/src/__tests__/doctor-bins.test.ts +35 -0
- package/src/__tests__/doctor.test.ts +450 -0
- package/src/__tests__/dual-write-prevention.test.ts +14 -4
- package/src/__tests__/file-locking.test.ts +208 -0
- package/src/__tests__/gitignore-prerun.test.ts +1 -0
- package/src/__tests__/install-command.test.ts +81 -0
- package/src/__tests__/install-plan.test.ts +98 -0
- package/src/__tests__/manifest.test.ts +136 -0
- package/src/__tests__/marketplace-refresh.test.ts +267 -0
- package/src/__tests__/plugin-requires.test.ts +133 -0
- package/src/__tests__/plugin-setup.test.ts +7 -0
- package/src/__tests__/profile-command.test.ts +116 -0
- package/src/__tests__/profile-materializer.test.ts +82 -0
- package/src/__tests__/profile-sync.test.ts +136 -0
- package/src/__tests__/registry-version-resolution.test.ts +74 -0
- package/src/__tests__/resolve-executable.test.ts +42 -0
- package/src/__tests__/resolver.test.ts +218 -0
- package/src/__tests__/symlink-manager.test.ts +99 -0
- package/src/__tests__/toolchain.test.ts +56 -0
- package/src/cli/claude.ts +21 -0
- package/src/cli/doctor.ts +132 -0
- package/src/cli/install.ts +360 -0
- package/src/cli/profile.ts +166 -0
- package/src/cli/router.ts +107 -0
- package/src/cli/update.ts +85 -0
- package/src/data/cli-tools.ts +7 -7
- package/src/data/gitignore-defaults.ts +4 -0
- package/src/data/marketplaces.ts +12 -0
- package/src/data/predefined-profiles.ts +3 -4
- package/src/main.tsx +11 -154
- package/src/prerunner/index.ts +62 -27
- package/src/services/claude-cli.ts +19 -22
- package/src/services/claude-settings.ts +99 -26
- package/src/services/conventions-manager.ts +865 -0
- package/src/services/doctor-bins.ts +49 -0
- package/src/services/doctor.ts +509 -0
- package/src/services/install-plan.ts +107 -0
- package/src/services/manifest.ts +166 -0
- package/src/services/marketplace-refresh.ts +173 -0
- package/src/services/plugin-manager.ts +7 -1
- package/src/services/plugin-requires.ts +215 -0
- package/src/services/plugin-version-check.ts +9 -4
- package/src/services/profile-materializer.ts +61 -0
- package/src/services/profile-sync.ts +150 -0
- package/src/services/resolver.ts +293 -0
- package/src/services/symlink-manager.ts +146 -0
- package/src/services/toolchain.ts +97 -0
- package/src/services/version-check.ts +10 -11
- package/src/types/index.ts +138 -31
- package/src/ui/App.tsx +0 -4
- package/src/ui/screens/CliToolsScreen.tsx +11 -3
- package/src/ui/screens/index.ts +0 -1
- package/src/ui/state/reducer.ts +0 -101
- package/src/ui/state/types.ts +0 -35
- package/src/utils/command-utils.ts +23 -0
- package/src/utils/file-locking.ts +144 -0
- package/src/data/alias-flags.js +0 -205
- package/src/data/cli-tools.js +0 -123
- package/src/data/gitignore-defaults.js +0 -24
- package/src/data/gitignore-reasons.js +0 -97
- package/src/data/gitignore-templates.js +0 -21
- package/src/data/marketplaces.js +0 -138
- package/src/data/mcp-servers.js +0 -509
- package/src/data/predefined-profiles.js +0 -248
- package/src/data/settings-catalog.js +0 -625
- package/src/data/skill-repos.js +0 -160
- package/src/data/statuslines.js +0 -159
- package/src/data/statuslines.ts +0 -188
- package/src/index.js +0 -4
- package/src/index.ts +0 -5
- package/src/main.js +0 -170
- package/src/prerunner/index.js +0 -252
- package/src/services/alias-settings.js +0 -51
- package/src/services/alias-shell-writer.js +0 -1018
- package/src/services/alias-store.js +0 -129
- package/src/services/claude-cli.js +0 -189
- package/src/services/claude-runner.js +0 -28
- package/src/services/claude-settings.js +0 -1223
- package/src/services/gitignore-detector.js +0 -155
- package/src/services/gitignore-fixer.js +0 -231
- package/src/services/gitignore-prerun.js +0 -46
- package/src/services/gitignore-resolver.js +0 -143
- package/src/services/gitignore-service.js +0 -117
- package/src/services/local-marketplace.js +0 -339
- package/src/services/marketplace-fetcher.js +0 -96
- package/src/services/marketplace-sync.js +0 -94
- package/src/services/mcp-registry.js +0 -87
- package/src/services/plugin-manager.js +0 -473
- package/src/services/plugin-mcp-config.js +0 -177
- package/src/services/plugin-setup.js +0 -499
- package/src/services/plugin-version-check.js +0 -262
- package/src/services/profiles.js +0 -161
- package/src/services/settings-manager.js +0 -243
- package/src/services/skills-manager.js +0 -393
- package/src/services/skillsmp-client.js +0 -87
- package/src/services/update-cache.js +0 -52
- package/src/services/version-check.js +0 -99
- package/src/types/gitignore.js +0 -6
- package/src/types/index.js +0 -1
- package/src/ui/App.js +0 -355
- package/src/ui/adapters/pluginsAdapter.js +0 -139
- package/src/ui/adapters/settingsAdapter.js +0 -111
- package/src/ui/adapters/skillsAdapter.js +0 -154
- package/src/ui/components/CategoryHeader.js +0 -9
- package/src/ui/components/EmptyFilterState.js +0 -4
- package/src/ui/components/FlagDetailEditor.js +0 -0
- package/src/ui/components/ScopeIndicator.js +0 -30
- package/src/ui/components/ScrollableList.js +0 -36
- package/src/ui/components/SearchInput.js +0 -19
- package/src/ui/components/StyledText.js +0 -39
- package/src/ui/components/TabBar.js +0 -19
- package/src/ui/components/layout/FooterHints.js +0 -29
- package/src/ui/components/layout/Panel.js +0 -6
- package/src/ui/components/layout/ProgressBar.js +0 -14
- package/src/ui/components/layout/ScopeTabs.js +0 -6
- package/src/ui/components/layout/ScreenLayout.js +0 -16
- package/src/ui/components/layout/index.js +0 -5
- package/src/ui/components/modals/ConfirmModal.js +0 -14
- package/src/ui/components/modals/InputModal.js +0 -5
- package/src/ui/components/modals/LoadingModal.js +0 -17
- package/src/ui/components/modals/MessageModal.js +0 -16
- package/src/ui/components/modals/ModalContainer.js +0 -137
- package/src/ui/components/modals/SelectModal.js +0 -18
- package/src/ui/components/modals/VersionMismatchModal.js +0 -36
- package/src/ui/components/modals/index.js +0 -6
- package/src/ui/components/primitives/ActionHints.js +0 -13
- package/src/ui/components/primitives/DetailSection.js +0 -7
- package/src/ui/components/primitives/KeyValueLine.js +0 -8
- package/src/ui/components/primitives/ListCategoryRow.js +0 -8
- package/src/ui/components/primitives/MetaText.js +0 -8
- package/src/ui/components/primitives/ScopeDetail.js +0 -32
- package/src/ui/components/primitives/ScopeSquares.js +0 -11
- package/src/ui/components/primitives/SelectableRow.js +0 -5
- package/src/ui/components/primitives/index.js +0 -8
- package/src/ui/hooks/index.js +0 -4
- package/src/ui/hooks/useAsyncData.js +0 -77
- package/src/ui/hooks/useGitignoreModal.js +0 -74
- package/src/ui/hooks/useKeyboard.js +0 -13
- package/src/ui/hooks/useKeyboardHandler.js +0 -39
- package/src/ui/hooks/useMismatchModal.js +0 -77
- package/src/ui/registry.js +0 -1
- package/src/ui/renderers/cliToolRenderers.js +0 -54
- package/src/ui/renderers/gitignoreRenderers.js +0 -46
- package/src/ui/renderers/mcpRenderers.js +0 -26
- package/src/ui/renderers/pluginRenderers.js +0 -124
- package/src/ui/renderers/profileRenderers.js +0 -177
- package/src/ui/renderers/settingsRenderers.js +0 -73
- package/src/ui/renderers/skillRenderers.js +0 -138
- package/src/ui/screens/AliasScreen.js +0 -1111
- package/src/ui/screens/CliToolsScreen.js +0 -338
- package/src/ui/screens/EnvVarsScreen.js +0 -152
- package/src/ui/screens/GitignoreScreen.js +0 -328
- package/src/ui/screens/McpRegistryScreen.js +0 -238
- package/src/ui/screens/McpScreen.js +0 -176
- package/src/ui/screens/ModelSelectorScreen.js +0 -296
- package/src/ui/screens/ModelSelectorScreen.tsx +0 -444
- package/src/ui/screens/PluginsScreen.js +0 -769
- package/src/ui/screens/ProfilesScreen.js +0 -298
- package/src/ui/screens/SkillsScreen.js +0 -549
- package/src/ui/screens/StatusLineScreen.js +0 -206
- package/src/ui/screens/StatusLineScreen.tsx +0 -416
- package/src/ui/screens/index.js +0 -10
- package/src/ui/state/AnimationContext.js +0 -34
- package/src/ui/state/AppContext.js +0 -162
- package/src/ui/state/DimensionsContext.js +0 -71
- package/src/ui/state/reducer.js +0 -547
- package/src/ui/state/types.js +0 -1
- package/src/ui/theme.js +0 -47
- package/src/utils/clipboard.js +0 -56
- package/src/utils/command-utils.js +0 -19
- package/src/utils/fuzzy-search.js +0 -101
- package/src/utils/string-utils.js +0 -62
|
@@ -1,1018 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Render the managed `claude` alias and splice it into shell rc files.
|
|
3
|
-
*
|
|
4
|
-
* Two layers:
|
|
5
|
-
* - Pure render functions (POSIX vs fish) that take a config and emit text.
|
|
6
|
-
* - I/O helpers that detect installed shells and replace the managed block
|
|
7
|
-
* idempotently using sentinel comment markers.
|
|
8
|
-
*/
|
|
9
|
-
import { readFile, writeFile, stat } from "node:fs/promises";
|
|
10
|
-
import { existsSync } from "node:fs";
|
|
11
|
-
import { join } from "node:path";
|
|
12
|
-
import { homedir } from "node:os";
|
|
13
|
-
import { ALIAS_FLAGS, getFlagById, } from "../data/alias-flags.js";
|
|
14
|
-
import { CHANNELS_FLAG_ID, defaultValueFor, derivedChannelValues, listValues, } from "./alias-store.js";
|
|
15
|
-
const BLOCK_BEGIN = "# >>> claudeup managed alias >>>";
|
|
16
|
-
const BLOCK_END = "# <<< claudeup managed alias <<<";
|
|
17
|
-
/**
|
|
18
|
-
* Probe the user's home dir for the three supported shell rc files.
|
|
19
|
-
*
|
|
20
|
-
* Path discovery is intentionally simple: we don't follow `$ZDOTDIR` or
|
|
21
|
-
* fish's `$XDG_CONFIG_HOME` overrides yet. If users hit those, we expose
|
|
22
|
-
* a path override later — for now the conventional locations cover the
|
|
23
|
-
* default install on macOS / Linux.
|
|
24
|
-
*/
|
|
25
|
-
export async function detectShells(home = homedir(), shellEnv = process.env.SHELL ?? "") {
|
|
26
|
-
const candidates = [
|
|
27
|
-
{ kind: "zsh", path: join(home, ".zshrc") },
|
|
28
|
-
{ kind: "bash", path: join(home, ".bashrc") },
|
|
29
|
-
{ kind: "fish", path: join(home, ".config", "fish", "config.fish") },
|
|
30
|
-
];
|
|
31
|
-
const defaultKind = inferDefaultShell(shellEnv);
|
|
32
|
-
const results = [];
|
|
33
|
-
for (const c of candidates) {
|
|
34
|
-
let exists = existsSync(c.path);
|
|
35
|
-
if (exists) {
|
|
36
|
-
// existsSync can lie on broken symlinks — check stat too
|
|
37
|
-
try {
|
|
38
|
-
await stat(c.path);
|
|
39
|
-
}
|
|
40
|
-
catch {
|
|
41
|
-
exists = false;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
results.push({
|
|
45
|
-
kind: c.kind,
|
|
46
|
-
path: c.path,
|
|
47
|
-
exists,
|
|
48
|
-
isDefault: c.kind === defaultKind,
|
|
49
|
-
});
|
|
50
|
-
}
|
|
51
|
-
return results;
|
|
52
|
-
}
|
|
53
|
-
function inferDefaultShell(shellEnv) {
|
|
54
|
-
if (shellEnv.endsWith("/zsh"))
|
|
55
|
-
return "zsh";
|
|
56
|
-
if (shellEnv.endsWith("/bash"))
|
|
57
|
-
return "bash";
|
|
58
|
-
if (shellEnv.endsWith("/fish"))
|
|
59
|
-
return "fish";
|
|
60
|
-
return null;
|
|
61
|
-
}
|
|
62
|
-
/**
|
|
63
|
-
* Build the alias body as a list of segments. Pure function.
|
|
64
|
-
*
|
|
65
|
-
* Validation:
|
|
66
|
-
* - `xorGroup` collisions are resolved by emitting only the first enabled
|
|
67
|
-
* flag in the group. The UI is responsible for warning the user; the
|
|
68
|
-
* renderer never silently keeps both.
|
|
69
|
-
* - `requires` is enforced: a flag whose dependency is disabled is dropped.
|
|
70
|
-
*/
|
|
71
|
-
export function renderArgs(config) {
|
|
72
|
-
const out = [];
|
|
73
|
-
const seenXor = new Set();
|
|
74
|
-
for (const flag of ALIAS_FLAGS) {
|
|
75
|
-
if (flag.requires) {
|
|
76
|
-
const dep = config.flags[flag.requires];
|
|
77
|
-
if (!isFlagEnabled(dep))
|
|
78
|
-
continue;
|
|
79
|
-
}
|
|
80
|
-
if (flag.xorGroup) {
|
|
81
|
-
if (seenXor.has(flag.xorGroup))
|
|
82
|
-
continue;
|
|
83
|
-
}
|
|
84
|
-
const value = config.flags[flag.id];
|
|
85
|
-
if (!value)
|
|
86
|
-
continue;
|
|
87
|
-
// `--channels` is the union (own ∪ dev-load-if-enabled), computed here at
|
|
88
|
-
// render time — the union is NOT stored, so own/derived stay distinct in
|
|
89
|
-
// the UI. A dev-loaded channel must run, so derived values force `--channels`
|
|
90
|
-
// to emit even when the user's own channels list is disabled/empty.
|
|
91
|
-
const renderValue = flag.id === CHANNELS_FLAG_ID
|
|
92
|
-
? channelsUnionValue(config.flags, value)
|
|
93
|
-
: value;
|
|
94
|
-
const rendered = renderFlag(flag, renderValue);
|
|
95
|
-
if (rendered.length === 0)
|
|
96
|
-
continue;
|
|
97
|
-
out.push(...rendered);
|
|
98
|
-
if (flag.xorGroup)
|
|
99
|
-
seenXor.add(flag.xorGroup);
|
|
100
|
-
}
|
|
101
|
-
return out;
|
|
102
|
-
}
|
|
103
|
-
/**
|
|
104
|
-
* Convenience: render each segment to its literal-token approximation.
|
|
105
|
-
* Composite segments are stringified by joining their literal parts with
|
|
106
|
-
* `<sub>` placeholders for raw parts. Used by tests and validation summaries
|
|
107
|
-
* where the actual shell substitution doesn't matter.
|
|
108
|
-
*/
|
|
109
|
-
export function renderArgsAsTokens(config) {
|
|
110
|
-
return renderArgs(config).map((seg) => {
|
|
111
|
-
if (seg.kind === "literal")
|
|
112
|
-
return seg.text;
|
|
113
|
-
return seg.parts
|
|
114
|
-
.map((p) => (p.kind === "literal" ? p.text : `<${p.posix}>`))
|
|
115
|
-
.join("");
|
|
116
|
-
});
|
|
117
|
-
}
|
|
118
|
-
function isFlagEnabled(value) {
|
|
119
|
-
if (!value)
|
|
120
|
-
return false;
|
|
121
|
-
switch (value.kind) {
|
|
122
|
-
case "boolean":
|
|
123
|
-
return value.enabled;
|
|
124
|
-
case "tri-state":
|
|
125
|
-
return value.state !== "unset";
|
|
126
|
-
case "select":
|
|
127
|
-
case "text":
|
|
128
|
-
case "optional-text":
|
|
129
|
-
case "text-list":
|
|
130
|
-
case "multi-with-custom":
|
|
131
|
-
return value.enabled;
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
function lit(text) {
|
|
135
|
-
return { kind: "literal", text };
|
|
136
|
-
}
|
|
137
|
-
/**
|
|
138
|
-
* Wrap a templated value as a composite segment if it contains any tokens,
|
|
139
|
-
* otherwise return it as a plain literal.
|
|
140
|
-
*/
|
|
141
|
-
function templatedSegment(value) {
|
|
142
|
-
const parts = expandTemplateValue(value);
|
|
143
|
-
if (parts.length === 1 && parts[0].kind === "literal") {
|
|
144
|
-
return { kind: "literal", text: parts[0].text };
|
|
145
|
-
}
|
|
146
|
-
return { kind: "composite", parts };
|
|
147
|
-
}
|
|
148
|
-
/**
|
|
149
|
-
* Build the effective `--channels` value for rendering: the user's own
|
|
150
|
-
* channels unioned with the dev-load flag's values (when dev-load is enabled),
|
|
151
|
-
* deduped, own-first. Enabled when EITHER source contributes a value, so a
|
|
152
|
-
* dev-loaded channel still forces `--channels` to emit even if the user never
|
|
153
|
-
* enabled their own channels list. The union lives here, at render time — it
|
|
154
|
-
* is never written back to `channels.values`, so provenance is preserved.
|
|
155
|
-
*/
|
|
156
|
-
function channelsUnionValue(flags, own) {
|
|
157
|
-
const ownValues = own.kind === "text-list" && own.enabled
|
|
158
|
-
? listValues(own)
|
|
159
|
-
: [];
|
|
160
|
-
const derived = derivedChannelValues(flags);
|
|
161
|
-
const merged = dedupe([...ownValues, ...derived]).filter((v) => v.length > 0);
|
|
162
|
-
return { kind: "text-list", enabled: merged.length > 0, values: merged };
|
|
163
|
-
}
|
|
164
|
-
function renderFlag(flag, value) {
|
|
165
|
-
switch (value.kind) {
|
|
166
|
-
case "boolean":
|
|
167
|
-
return value.enabled ? [lit(flag.flag)] : [];
|
|
168
|
-
case "tri-state":
|
|
169
|
-
if (value.state === "on")
|
|
170
|
-
return [lit(flag.flag)];
|
|
171
|
-
if (value.state === "off" && flag.triStateOff)
|
|
172
|
-
return [lit(flag.triStateOff)];
|
|
173
|
-
return [];
|
|
174
|
-
case "select":
|
|
175
|
-
if (!value.enabled)
|
|
176
|
-
return [];
|
|
177
|
-
// Empty value means "bare flag, default variant" (e.g. `--tmux` alone).
|
|
178
|
-
return value.value === ""
|
|
179
|
-
? [lit(flag.flag)]
|
|
180
|
-
: [lit(flag.flag), lit(value.value)];
|
|
181
|
-
case "text":
|
|
182
|
-
if (!value.enabled || !value.value)
|
|
183
|
-
return [];
|
|
184
|
-
return [
|
|
185
|
-
lit(flag.flag),
|
|
186
|
-
flag.templated ? templatedSegment(value.value) : lit(value.value),
|
|
187
|
-
];
|
|
188
|
-
case "optional-text":
|
|
189
|
-
if (!value.enabled)
|
|
190
|
-
return [];
|
|
191
|
-
if (!value.value)
|
|
192
|
-
return [lit(flag.flag)];
|
|
193
|
-
return [
|
|
194
|
-
lit(flag.flag),
|
|
195
|
-
flag.templated ? templatedSegment(value.value) : lit(value.value),
|
|
196
|
-
];
|
|
197
|
-
case "text-list": {
|
|
198
|
-
if (!value.enabled || value.values.length === 0)
|
|
199
|
-
return [];
|
|
200
|
-
const out = [];
|
|
201
|
-
for (const v of value.values) {
|
|
202
|
-
if (!v)
|
|
203
|
-
continue;
|
|
204
|
-
out.push(lit(flag.flag), flag.templated ? templatedSegment(v) : lit(v));
|
|
205
|
-
}
|
|
206
|
-
return out;
|
|
207
|
-
}
|
|
208
|
-
case "multi-with-custom": {
|
|
209
|
-
if (!value.enabled)
|
|
210
|
-
return [];
|
|
211
|
-
const tokens = dedupe([...value.picked, ...value.custom]).filter((t) => t.length > 0);
|
|
212
|
-
if (tokens.length === 0)
|
|
213
|
-
return [lit(flag.flag)];
|
|
214
|
-
return [lit(flag.flag), lit(tokens.join(","))];
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
/**
|
|
219
|
-
* Per-token shell-substitution code. POSIX and fish forms diverge slightly:
|
|
220
|
-
*
|
|
221
|
-
* - POSIX: classic `$(cmd)` with double quotes around `$PWD` so paths with
|
|
222
|
-
* spaces survive word-splitting in `basename`. The double quotes are
|
|
223
|
-
* tolerable inside the outer-double-quoted segment because we're already
|
|
224
|
-
* committed to a "embedded substitution" layer.
|
|
225
|
-
* - fish: `(cmd)` and fish handles variable expansion without the
|
|
226
|
-
* word-splitting concern, so `$PWD` doesn't need inner quoting.
|
|
227
|
-
*
|
|
228
|
-
* Note for POSIX: when this segment is emitted as `'"$(basename "$PWD")"'`,
|
|
229
|
-
* the shell sees `"$(basename "$PWD")"` — outer `"…"` enclosing an inner
|
|
230
|
-
* `"$PWD"`. POSIX (and bash/zsh) handle nested double quotes inside command
|
|
231
|
-
* substitution correctly: the inner `"$PWD"` is parsed within the `$(...)`
|
|
232
|
-
* subshell scope, not the outer shell's scope.
|
|
233
|
-
*/
|
|
234
|
-
const TOKEN_TO_SUB = {
|
|
235
|
-
"{folder}": {
|
|
236
|
-
posix: '$(basename "$PWD")',
|
|
237
|
-
fish: "(basename $PWD)",
|
|
238
|
-
},
|
|
239
|
-
"{day}": { posix: "$(date +%d)", fish: "(date +%d)" },
|
|
240
|
-
"{month}": { posix: "$(date +%m)", fish: "(date +%m)" },
|
|
241
|
-
"{year}": { posix: "$(date +%Y)", fish: "(date +%Y)" },
|
|
242
|
-
};
|
|
243
|
-
const TEMPLATE_RE = /\{(folder|day|month|year)\}/g;
|
|
244
|
-
/**
|
|
245
|
-
* Split a templated value into alternating literal and raw parts.
|
|
246
|
-
* Empty literal pieces are dropped. If the value contains no tokens, returns
|
|
247
|
-
* a single literal part covering the full string.
|
|
248
|
-
*/
|
|
249
|
-
export function expandTemplateValue(value) {
|
|
250
|
-
const out = [];
|
|
251
|
-
let last = 0;
|
|
252
|
-
for (const match of value.matchAll(TEMPLATE_RE)) {
|
|
253
|
-
const start = match.index;
|
|
254
|
-
if (start > last) {
|
|
255
|
-
out.push({ kind: "literal", text: value.slice(last, start) });
|
|
256
|
-
}
|
|
257
|
-
const sub = TOKEN_TO_SUB[match[0]];
|
|
258
|
-
if (sub) {
|
|
259
|
-
out.push({ kind: "raw", posix: sub.posix, fish: sub.fish });
|
|
260
|
-
}
|
|
261
|
-
last = start + match[0].length;
|
|
262
|
-
}
|
|
263
|
-
if (last < value.length) {
|
|
264
|
-
out.push({ kind: "literal", text: value.slice(last) });
|
|
265
|
-
}
|
|
266
|
-
if (out.length === 0) {
|
|
267
|
-
out.push({ kind: "literal", text: value });
|
|
268
|
-
}
|
|
269
|
-
return out;
|
|
270
|
-
}
|
|
271
|
-
function dedupe(arr) {
|
|
272
|
-
return Array.from(new Set(arr));
|
|
273
|
-
}
|
|
274
|
-
/**
|
|
275
|
-
* Fish quoting. Fish single quotes are simpler — only `\` and `'` need escapes.
|
|
276
|
-
*/
|
|
277
|
-
function quoteFish(s) {
|
|
278
|
-
return `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
|
|
279
|
-
}
|
|
280
|
-
export function renderAlias(config, shell) {
|
|
281
|
-
const args = renderArgs(config);
|
|
282
|
-
const name = config.aliasName;
|
|
283
|
-
if (shell === "fish") {
|
|
284
|
-
return { shell, block: renderFishBlock(name, args) };
|
|
285
|
-
}
|
|
286
|
-
return { shell, block: renderPosixBlock(name, args) };
|
|
287
|
-
}
|
|
288
|
-
function renderPosixBlock(name, segments) {
|
|
289
|
-
// The alias body lives inside outer single quotes:
|
|
290
|
-
// alias <name>='claude … '
|
|
291
|
-
// Each segment becomes one shell-arg inside that body. Composite segments
|
|
292
|
-
// (templated values) interleave literal text with double-quoted shell
|
|
293
|
-
// substitutions via close-outer + double-quote + reopen-outer.
|
|
294
|
-
const body = segments.length === 0
|
|
295
|
-
? ""
|
|
296
|
-
: " " + segments.map(renderPosixSegment).join(" ");
|
|
297
|
-
const line = `alias ${name}='claude${body}'`;
|
|
298
|
-
return `${BLOCK_BEGIN}\n${line}\n${BLOCK_END}\n`;
|
|
299
|
-
}
|
|
300
|
-
function renderPosixSegment(seg) {
|
|
301
|
-
if (seg.kind === "literal")
|
|
302
|
-
return quoteInsidePosixAlias(seg.text);
|
|
303
|
-
return seg.parts
|
|
304
|
-
.map((p) => p.kind === "literal"
|
|
305
|
-
? quoteInsidePosixAlias(p.text)
|
|
306
|
-
: embedPosixSubstitution(p.posix))
|
|
307
|
-
.join("");
|
|
308
|
-
}
|
|
309
|
-
/**
|
|
310
|
-
* Embed shell substitution code inside the outer single-quoted alias body
|
|
311
|
-
* so it fires when the alias is expanded, not when the alias is defined.
|
|
312
|
-
*
|
|
313
|
-
* The outer alias body is `'…'`. To inject `$(cmd)` and have it evaluate at
|
|
314
|
-
* expansion time, we close the outer `'`, switch to double quotes (which
|
|
315
|
-
* interpolate), emit the substitution, close the double quotes, reopen the
|
|
316
|
-
* outer `'`. Net source text: `'"$(cmd)"'`.
|
|
317
|
-
*
|
|
318
|
-
* Any inner double quotes in the substitution code (e.g. `"$PWD"` for
|
|
319
|
-
* spaces-in-paths protection) survive because POSIX command substitution
|
|
320
|
-
* has its own quoting context inside `$(...)`.
|
|
321
|
-
*/
|
|
322
|
-
function embedPosixSubstitution(posixCode) {
|
|
323
|
-
return `'"${posixCode}"'`;
|
|
324
|
-
}
|
|
325
|
-
const POSIX_BARE = /^[A-Za-z0-9_\-=,:.\/!@%+]+$/;
|
|
326
|
-
function quoteInsidePosixAlias(token) {
|
|
327
|
-
if (POSIX_BARE.test(token))
|
|
328
|
-
return token;
|
|
329
|
-
// No internal single quotes guaranteed by upstream validation.
|
|
330
|
-
return `'\\''${token}'\\''`;
|
|
331
|
-
}
|
|
332
|
-
/**
|
|
333
|
-
* Tokens with embedded single quotes can't be cleanly nested inside an outer
|
|
334
|
-
* single-quoted alias body without compounding escape layers that make the
|
|
335
|
-
* file unreadable. The UI surfaces this as an error before write.
|
|
336
|
-
*
|
|
337
|
-
* Composite segments are not checked here — their literal parts are checked
|
|
338
|
-
* via the same recursion. A `'` in a templated value's literal portion would
|
|
339
|
-
* still be unrenderable, so we walk the parts.
|
|
340
|
-
*/
|
|
341
|
-
export function findUnquotableTokens(segments) {
|
|
342
|
-
const out = [];
|
|
343
|
-
for (const seg of segments) {
|
|
344
|
-
if (seg.kind === "literal") {
|
|
345
|
-
if (seg.text.includes("'"))
|
|
346
|
-
out.push(seg.text);
|
|
347
|
-
continue;
|
|
348
|
-
}
|
|
349
|
-
for (const p of seg.parts) {
|
|
350
|
-
if (p.kind === "literal" && p.text.includes("'"))
|
|
351
|
-
out.push(p.text);
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
return out;
|
|
355
|
-
}
|
|
356
|
-
function renderFishBlock(name, segments) {
|
|
357
|
-
// Fish: `alias <name> 'claude --foo bar'` — outer single quotes, no `=`.
|
|
358
|
-
const body = segments.length === 0
|
|
359
|
-
? ""
|
|
360
|
-
: " " + segments.map(renderFishSegment).join(" ");
|
|
361
|
-
const line = `alias ${name} 'claude${body}'`;
|
|
362
|
-
return `${BLOCK_BEGIN}\n${line}\n${BLOCK_END}\n`;
|
|
363
|
-
}
|
|
364
|
-
function renderFishSegment(seg) {
|
|
365
|
-
if (seg.kind === "literal")
|
|
366
|
-
return quoteFish(seg.text);
|
|
367
|
-
return seg.parts
|
|
368
|
-
.map((p) => p.kind === "literal"
|
|
369
|
-
? quoteFish(p.text)
|
|
370
|
-
: embedFishSubstitution(p.fish))
|
|
371
|
-
.join("");
|
|
372
|
-
}
|
|
373
|
-
/**
|
|
374
|
-
* Fish substitution embedding mirrors POSIX. Outer `'…'` is fish's literal
|
|
375
|
-
* single-quote (no interpolation), so close-and-double-quote-reopen is the
|
|
376
|
-
* same dance: `'"(cmd)"'` becomes literal-' + `(cmd)` evaluated at expansion
|
|
377
|
-
* time + literal-'.
|
|
378
|
-
*/
|
|
379
|
-
function embedFishSubstitution(fishCode) {
|
|
380
|
-
return `'"${fishCode}"'`;
|
|
381
|
-
}
|
|
382
|
-
// ─── Splicing ─────────────────────────────────────────────────────────────
|
|
383
|
-
/**
|
|
384
|
-
* Replace the existing managed block in `existing` with `block`, or append
|
|
385
|
-
* `block` to the end if no block is present. Pure function — no I/O.
|
|
386
|
-
*/
|
|
387
|
-
export function spliceManagedBlock(existing, block) {
|
|
388
|
-
const beginIdx = existing.indexOf(BLOCK_BEGIN);
|
|
389
|
-
if (beginIdx === -1) {
|
|
390
|
-
if (existing.length === 0)
|
|
391
|
-
return block;
|
|
392
|
-
const sep = existing.endsWith("\n") ? "" : "\n";
|
|
393
|
-
return existing + sep + "\n" + block;
|
|
394
|
-
}
|
|
395
|
-
const endIdx = existing.indexOf(BLOCK_END, beginIdx);
|
|
396
|
-
if (endIdx === -1) {
|
|
397
|
-
// Malformed block — replace from BEGIN to EOF to be safe.
|
|
398
|
-
return existing.slice(0, beginIdx) + block;
|
|
399
|
-
}
|
|
400
|
-
// Consume the trailing newline of the END marker if present.
|
|
401
|
-
let cutEnd = endIdx + BLOCK_END.length;
|
|
402
|
-
if (existing[cutEnd] === "\n")
|
|
403
|
-
cutEnd += 1;
|
|
404
|
-
return existing.slice(0, beginIdx) + block + existing.slice(cutEnd);
|
|
405
|
-
}
|
|
406
|
-
export async function writeAliasToShell(config, target, options = {}) {
|
|
407
|
-
const args = renderArgs(config);
|
|
408
|
-
const unquotable = findUnquotableTokens(args);
|
|
409
|
-
if (unquotable.length > 0) {
|
|
410
|
-
throw new Error(`Cannot render alias: ${unquotable.length} value${unquotable.length === 1 ? "" : "s"} contain a single quote, which can't be embedded in a shell alias. Edit the offending value(s) and try again: ${unquotable
|
|
411
|
-
.map((t) => JSON.stringify(t))
|
|
412
|
-
.join(", ")}`);
|
|
413
|
-
}
|
|
414
|
-
const rendered = renderAlias(config, target.kind);
|
|
415
|
-
const existing = target.exists ? await readFile(target.path, "utf8") : "";
|
|
416
|
-
// Adoption: when a line range was supplied AND the file has no managed block
|
|
417
|
-
// yet, replace the adopted alias line in place — the managed block takes its
|
|
418
|
-
// slot, so the original can't survive as a duplicate. Once a managed block
|
|
419
|
-
// exists, marker-based splicing is position-independent and takes over.
|
|
420
|
-
const hasBlock = existing.includes(BLOCK_BEGIN);
|
|
421
|
-
const next = options.adoptLineRange && !hasBlock
|
|
422
|
-
? spliceManagedBlockAtRange(existing, rendered.block, options.adoptLineRange)
|
|
423
|
-
: spliceManagedBlock(existing, rendered.block);
|
|
424
|
-
await writeFile(target.path, next, "utf8");
|
|
425
|
-
return {
|
|
426
|
-
shell: target.kind,
|
|
427
|
-
path: target.path,
|
|
428
|
-
action: target.exists ? "updated" : "created",
|
|
429
|
-
};
|
|
430
|
-
}
|
|
431
|
-
/**
|
|
432
|
-
* Summarize which flags are in conflict given the current config.
|
|
433
|
-
* The UI uses this to grey out / annotate rows. The renderer enforces the
|
|
434
|
-
* same rules independently — this helper is purely for display.
|
|
435
|
-
*/
|
|
436
|
-
export function validateConfig(config) {
|
|
437
|
-
const issues = [];
|
|
438
|
-
// xor groups
|
|
439
|
-
const groups = new Map();
|
|
440
|
-
for (const flag of ALIAS_FLAGS) {
|
|
441
|
-
if (!flag.xorGroup)
|
|
442
|
-
continue;
|
|
443
|
-
if (!isFlagEnabled(config.flags[flag.id]))
|
|
444
|
-
continue;
|
|
445
|
-
const list = groups.get(flag.xorGroup) ?? [];
|
|
446
|
-
list.push(flag.id);
|
|
447
|
-
groups.set(flag.xorGroup, list);
|
|
448
|
-
}
|
|
449
|
-
for (const [group, ids] of groups) {
|
|
450
|
-
if (ids.length > 1) {
|
|
451
|
-
const winner = ids[0];
|
|
452
|
-
const losers = ids.slice(1);
|
|
453
|
-
for (const loser of losers) {
|
|
454
|
-
issues.push({
|
|
455
|
-
flagId: loser,
|
|
456
|
-
reason: `Mutually exclusive with --${winner}; will be dropped on write.`,
|
|
457
|
-
});
|
|
458
|
-
}
|
|
459
|
-
}
|
|
460
|
-
}
|
|
461
|
-
// requires
|
|
462
|
-
for (const flag of ALIAS_FLAGS) {
|
|
463
|
-
if (!flag.requires)
|
|
464
|
-
continue;
|
|
465
|
-
if (!isFlagEnabled(config.flags[flag.id]))
|
|
466
|
-
continue;
|
|
467
|
-
if (!isFlagEnabled(config.flags[flag.requires])) {
|
|
468
|
-
const dep = getFlagById(flag.requires);
|
|
469
|
-
issues.push({
|
|
470
|
-
flagId: flag.id,
|
|
471
|
-
reason: `Requires ${dep.flag}; will be dropped on write.`,
|
|
472
|
-
});
|
|
473
|
-
}
|
|
474
|
-
}
|
|
475
|
-
return issues;
|
|
476
|
-
}
|
|
477
|
-
/**
|
|
478
|
-
* Find the managed block in shell rc text, parse the alias line, and return
|
|
479
|
-
* the alias name plus the argv tokens after `claude`.
|
|
480
|
-
*
|
|
481
|
-
* Returns `null` when no managed block exists, the block is malformed, or
|
|
482
|
-
* the alias line can't be parsed. Callers treat null as "no managed alias
|
|
483
|
-
* on disk — start from defaults".
|
|
484
|
-
*/
|
|
485
|
-
export function parseManagedBlock(rcText) {
|
|
486
|
-
const beginIdx = rcText.indexOf(BLOCK_BEGIN);
|
|
487
|
-
if (beginIdx === -1)
|
|
488
|
-
return null;
|
|
489
|
-
const endIdx = rcText.indexOf(BLOCK_END, beginIdx);
|
|
490
|
-
if (endIdx === -1)
|
|
491
|
-
return null;
|
|
492
|
-
// Lines inside the block, sans markers.
|
|
493
|
-
const inner = rcText.slice(beginIdx + BLOCK_BEGIN.length, endIdx);
|
|
494
|
-
// Find the `alias <name>=...` line (skip blank lines, comments, the markers).
|
|
495
|
-
const aliasLine = inner
|
|
496
|
-
.split("\n")
|
|
497
|
-
.map((l) => l.trim())
|
|
498
|
-
.find((l) => /^alias\s+[A-Za-z_][A-Za-z0-9_-]*\s*=/.test(l));
|
|
499
|
-
if (!aliasLine)
|
|
500
|
-
return null;
|
|
501
|
-
return parseAliasLine(aliasLine);
|
|
502
|
-
}
|
|
503
|
-
const ALIAS_LINE_RE = /^alias\s+([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*'(.*)'\s*$/;
|
|
504
|
-
/**
|
|
505
|
-
* Parse a single `alias <name>='<body>'` line. Body is the raw text inside
|
|
506
|
-
* the outer single quotes; the tokenizer below undoes the writer's escape
|
|
507
|
-
* scheme.
|
|
508
|
-
*/
|
|
509
|
-
export function parseAliasLine(line) {
|
|
510
|
-
const match = ALIAS_LINE_RE.exec(line);
|
|
511
|
-
if (!match)
|
|
512
|
-
return null;
|
|
513
|
-
const [, aliasName, body] = match;
|
|
514
|
-
// First token is the command itself (claude). Drop it; we only want argv.
|
|
515
|
-
const tokens = tokenizePosixAliasBody(body);
|
|
516
|
-
if (tokens.length === 0 || tokens[0] !== "claude")
|
|
517
|
-
return null;
|
|
518
|
-
return { aliasName, args: tokens.slice(1) };
|
|
519
|
-
}
|
|
520
|
-
/**
|
|
521
|
-
* Tokenize the body of a POSIX alias inside the outer single quotes.
|
|
522
|
-
*
|
|
523
|
-
* Our writer emits three shapes inside the outer `'…'`:
|
|
524
|
-
* 1. Bare tokens (matching POSIX_BARE) — emitted as-is.
|
|
525
|
-
* 2. Quoted literals: `'\''text without single quotes'\''` — these survive
|
|
526
|
-
* the outer single quotes by closing them, emitting a literal `'`,
|
|
527
|
-
* single-quoting the inner content, then a literal `'`, and reopening.
|
|
528
|
-
* 3. Substitution embeds: `'"$(cmd)"'` — close outer ', open ", embed,
|
|
529
|
-
* close ", reopen outer '. Result is one shell arg with the
|
|
530
|
-
* substitution that fires on alias expansion.
|
|
531
|
-
*
|
|
532
|
-
* Reading the body left-to-right, we expect to see:
|
|
533
|
-
* - bare chars (collect into the current token's value)
|
|
534
|
-
* - whitespace (delimits tokens)
|
|
535
|
-
* - `'\''<text>'\''` (collect inner text verbatim into the current token)
|
|
536
|
-
* - `'"<sub>"'` (record as a raw substitution and unparse it back into
|
|
537
|
-
* the closest matching template token via `unparseSubstitution`)
|
|
538
|
-
*
|
|
539
|
-
* Tokens emitted as `composite` segments (template values) re-tokenize into
|
|
540
|
-
* a single shell arg whose pieces are interleaved literal+raw. We rebuild
|
|
541
|
-
* those as `{token}` strings to match what the UI stores.
|
|
542
|
-
*/
|
|
543
|
-
export function tokenizePosixAliasBody(body) {
|
|
544
|
-
const tokens = [];
|
|
545
|
-
let current = "";
|
|
546
|
-
let inToken = false;
|
|
547
|
-
let i = 0;
|
|
548
|
-
const len = body.length;
|
|
549
|
-
const flush = () => {
|
|
550
|
-
if (inToken) {
|
|
551
|
-
tokens.push(current);
|
|
552
|
-
current = "";
|
|
553
|
-
inToken = false;
|
|
554
|
-
}
|
|
555
|
-
};
|
|
556
|
-
while (i < len) {
|
|
557
|
-
const ch = body[i];
|
|
558
|
-
if (ch === " " || ch === "\t") {
|
|
559
|
-
flush();
|
|
560
|
-
i += 1;
|
|
561
|
-
continue;
|
|
562
|
-
}
|
|
563
|
-
// Quoted literal: '\''…'\''
|
|
564
|
-
if (body.startsWith(`'\\''`, i)) {
|
|
565
|
-
// Skip the opening sequence.
|
|
566
|
-
i += 4;
|
|
567
|
-
const end = body.indexOf(`'\\''`, i);
|
|
568
|
-
if (end === -1)
|
|
569
|
-
return tokens; // malformed — bail, return what we have
|
|
570
|
-
current += body.slice(i, end);
|
|
571
|
-
inToken = true;
|
|
572
|
-
i = end + 4;
|
|
573
|
-
continue;
|
|
574
|
-
}
|
|
575
|
-
// Substitution embed: '"<sub>"'
|
|
576
|
-
if (body.startsWith(`'"`, i)) {
|
|
577
|
-
const inner = i + 2;
|
|
578
|
-
const close = body.indexOf(`"'`, inner);
|
|
579
|
-
if (close === -1)
|
|
580
|
-
return tokens;
|
|
581
|
-
const subCode = body.slice(inner, close);
|
|
582
|
-
const token = unparseSubstitution(subCode);
|
|
583
|
-
current += token;
|
|
584
|
-
inToken = true;
|
|
585
|
-
i = close + 2;
|
|
586
|
-
continue;
|
|
587
|
-
}
|
|
588
|
-
// Bare character.
|
|
589
|
-
current += ch;
|
|
590
|
-
inToken = true;
|
|
591
|
-
i += 1;
|
|
592
|
-
}
|
|
593
|
-
flush();
|
|
594
|
-
return tokens;
|
|
595
|
-
}
|
|
596
|
-
/**
|
|
597
|
-
* Map a POSIX substitution code back to its template token, if one matches.
|
|
598
|
-
* Falls through to a `$(...)` literal when no token matches — that way we
|
|
599
|
-
* preserve hand-edited substitutions as opaque values rather than dropping
|
|
600
|
-
* them.
|
|
601
|
-
*
|
|
602
|
-
* Mirror of TOKEN_TO_SUB in the writer.
|
|
603
|
-
*/
|
|
604
|
-
function unparseSubstitution(posixCode) {
|
|
605
|
-
switch (posixCode) {
|
|
606
|
-
case '$(basename "$PWD")':
|
|
607
|
-
return "{folder}";
|
|
608
|
-
case "$(date +%d)":
|
|
609
|
-
return "{day}";
|
|
610
|
-
case "$(date +%m)":
|
|
611
|
-
return "{month}";
|
|
612
|
-
case "$(date +%Y)":
|
|
613
|
-
return "{year}";
|
|
614
|
-
default:
|
|
615
|
-
// Unknown substitution: pass through the raw code so the user can see
|
|
616
|
-
// it in the UI and decide whether to keep it. The writer can't faithfully
|
|
617
|
-
// round-trip it, but at least we don't silently drop it.
|
|
618
|
-
return posixCode;
|
|
619
|
-
}
|
|
620
|
-
}
|
|
621
|
-
/**
|
|
622
|
-
* Apply parsed argv tokens to a FlagValue map. Walks the catalog in order,
|
|
623
|
-
* consuming tokens that match each flag's pattern. Tokens that don't match
|
|
624
|
-
* any flag are dropped silently (e.g. the user hand-added a flag we don't
|
|
625
|
-
* know about). Returns a fresh `Record<flagId, FlagValue>` suitable for
|
|
626
|
-
* splicing into an AliasConfig.
|
|
627
|
-
*
|
|
628
|
-
* Ordering: the writer emits flags in catalog order, so a left-to-right
|
|
629
|
-
* scan is sufficient. We pre-index by flag string for `--foo` lookups.
|
|
630
|
-
*/
|
|
631
|
-
export function argsToFlagValues(args) {
|
|
632
|
-
return argsToFlagValuesWithLeftovers(args).flags;
|
|
633
|
-
}
|
|
634
|
-
/**
|
|
635
|
-
* Like {@link argsToFlagValues}, but reports every token it couldn't map to a
|
|
636
|
-
* catalog flag. Unknown `--flag value` pairs contribute BOTH tokens to
|
|
637
|
-
* `leftovers` (the flag and its consumed value) so the adoption gate sees the
|
|
638
|
-
* full extent of what wouldn't round-trip.
|
|
639
|
-
*/
|
|
640
|
-
export function argsToFlagValuesWithLeftovers(args) {
|
|
641
|
-
// Index every flag by its primary `flag` string AND its triStateOff variant.
|
|
642
|
-
const byFlag = new Map();
|
|
643
|
-
for (const flag of ALIAS_FLAGS) {
|
|
644
|
-
byFlag.set(flag.flag, { flag, off: false });
|
|
645
|
-
if (flag.triStateOff) {
|
|
646
|
-
byFlag.set(flag.triStateOff, { flag, off: true });
|
|
647
|
-
}
|
|
648
|
-
}
|
|
649
|
-
const out = {};
|
|
650
|
-
const leftovers = [];
|
|
651
|
-
let i = 0;
|
|
652
|
-
while (i < args.length) {
|
|
653
|
-
const tok = args[i];
|
|
654
|
-
const entry = byFlag.get(tok);
|
|
655
|
-
if (!entry) {
|
|
656
|
-
// Unknown token — record it. If the next token looks like its value
|
|
657
|
-
// (doesn't start with `-`), consume and record that too so unknown
|
|
658
|
-
// flag/value pairs don't cascade-corrupt the rest of the parse, and so
|
|
659
|
-
// the adoption gate sees the full unrecognized span.
|
|
660
|
-
leftovers.push(tok);
|
|
661
|
-
i += 1;
|
|
662
|
-
if (i < args.length && !args[i].startsWith("-")) {
|
|
663
|
-
leftovers.push(args[i]);
|
|
664
|
-
i += 1;
|
|
665
|
-
}
|
|
666
|
-
continue;
|
|
667
|
-
}
|
|
668
|
-
const { flag, off } = entry;
|
|
669
|
-
const peek = () => args[i + 1];
|
|
670
|
-
const takeValue = () => {
|
|
671
|
-
const v = args[i + 1];
|
|
672
|
-
i += 2;
|
|
673
|
-
return v;
|
|
674
|
-
};
|
|
675
|
-
switch (flag.kind) {
|
|
676
|
-
case "boolean":
|
|
677
|
-
out[flag.id] = { kind: "boolean", enabled: true };
|
|
678
|
-
i += 1;
|
|
679
|
-
break;
|
|
680
|
-
case "tri-state":
|
|
681
|
-
out[flag.id] = { kind: "tri-state", state: off ? "off" : "on" };
|
|
682
|
-
i += 1;
|
|
683
|
-
break;
|
|
684
|
-
case "select": {
|
|
685
|
-
// The writer emits `--flag` alone for "bare" empty value, or
|
|
686
|
-
// `--flag <value>` for a selection. We can't tell without peeking
|
|
687
|
-
// at whether the next token is a known value.
|
|
688
|
-
const opts = flag.options ?? [];
|
|
689
|
-
const next = peek();
|
|
690
|
-
const valid = next !== undefined && opts.some((o) => o.value === next);
|
|
691
|
-
if (valid) {
|
|
692
|
-
out[flag.id] = { kind: "select", enabled: true, value: takeValue() };
|
|
693
|
-
}
|
|
694
|
-
else {
|
|
695
|
-
out[flag.id] = { kind: "select", enabled: true, value: "" };
|
|
696
|
-
i += 1;
|
|
697
|
-
}
|
|
698
|
-
break;
|
|
699
|
-
}
|
|
700
|
-
case "text":
|
|
701
|
-
// `text` always emits a value; if there's no next token we treat as
|
|
702
|
-
// disabled (defensive).
|
|
703
|
-
if (peek() !== undefined) {
|
|
704
|
-
out[flag.id] = { kind: "text", enabled: true, value: takeValue() };
|
|
705
|
-
}
|
|
706
|
-
else {
|
|
707
|
-
out[flag.id] = { kind: "text", enabled: false, value: "" };
|
|
708
|
-
i += 1;
|
|
709
|
-
}
|
|
710
|
-
break;
|
|
711
|
-
case "optional-text": {
|
|
712
|
-
// Optional-text: next token is the value if it doesn't look like a
|
|
713
|
-
// flag. We can't perfectly distinguish a deliberately-bare emission
|
|
714
|
-
// from one followed by an unrelated flag, but the writer's emission
|
|
715
|
-
// of bare is `flag.flag` alone with the next token being another
|
|
716
|
-
// catalog flag — so checking the lookup tells us.
|
|
717
|
-
const next = peek();
|
|
718
|
-
if (next === undefined || byFlag.has(next)) {
|
|
719
|
-
out[flag.id] = { kind: "optional-text", enabled: true, value: "" };
|
|
720
|
-
i += 1;
|
|
721
|
-
}
|
|
722
|
-
else {
|
|
723
|
-
out[flag.id] = {
|
|
724
|
-
kind: "optional-text",
|
|
725
|
-
enabled: true,
|
|
726
|
-
value: takeValue(),
|
|
727
|
-
};
|
|
728
|
-
}
|
|
729
|
-
break;
|
|
730
|
-
}
|
|
731
|
-
case "text-list": {
|
|
732
|
-
// Each instance of the flag emits one value. Collect repeats.
|
|
733
|
-
const values = [];
|
|
734
|
-
// Consume the first pair.
|
|
735
|
-
if (peek() !== undefined)
|
|
736
|
-
values.push(takeValue());
|
|
737
|
-
else
|
|
738
|
-
i += 1;
|
|
739
|
-
// Consume additional pairs of the same flag.
|
|
740
|
-
while (i < args.length && args[i] === flag.flag) {
|
|
741
|
-
if (i + 1 < args.length) {
|
|
742
|
-
values.push(args[i + 1]);
|
|
743
|
-
i += 2;
|
|
744
|
-
}
|
|
745
|
-
else {
|
|
746
|
-
i += 1;
|
|
747
|
-
break;
|
|
748
|
-
}
|
|
749
|
-
}
|
|
750
|
-
out[flag.id] = {
|
|
751
|
-
kind: "text-list",
|
|
752
|
-
enabled: true,
|
|
753
|
-
values,
|
|
754
|
-
};
|
|
755
|
-
break;
|
|
756
|
-
}
|
|
757
|
-
case "multi-with-custom": {
|
|
758
|
-
// Either bare `--debug` (no filter) or `--debug a,b,c`.
|
|
759
|
-
const next = peek();
|
|
760
|
-
if (next === undefined || byFlag.has(next)) {
|
|
761
|
-
out[flag.id] = {
|
|
762
|
-
kind: "multi-with-custom",
|
|
763
|
-
enabled: true,
|
|
764
|
-
picked: [],
|
|
765
|
-
custom: [],
|
|
766
|
-
};
|
|
767
|
-
i += 1;
|
|
768
|
-
}
|
|
769
|
-
else {
|
|
770
|
-
const tokens = takeValue()
|
|
771
|
-
.split(",")
|
|
772
|
-
.map((s) => s.trim())
|
|
773
|
-
.filter((s) => s.length > 0);
|
|
774
|
-
const picklist = new Set(flag.picklist ?? []);
|
|
775
|
-
const picked = [];
|
|
776
|
-
const custom = [];
|
|
777
|
-
for (const t of tokens) {
|
|
778
|
-
if (picklist.has(t))
|
|
779
|
-
picked.push(t);
|
|
780
|
-
else
|
|
781
|
-
custom.push(t);
|
|
782
|
-
}
|
|
783
|
-
out[flag.id] = {
|
|
784
|
-
kind: "multi-with-custom",
|
|
785
|
-
enabled: true,
|
|
786
|
-
picked,
|
|
787
|
-
custom,
|
|
788
|
-
};
|
|
789
|
-
}
|
|
790
|
-
break;
|
|
791
|
-
}
|
|
792
|
-
}
|
|
793
|
-
}
|
|
794
|
-
// Restore channels provenance: the writer emits `--channels` as
|
|
795
|
-
// (own ∪ dev-load), so a naive parse folds derived values back into
|
|
796
|
-
// channels.values. Subtract the dev-load values (when that flag was
|
|
797
|
-
// emitted/enabled) so channels.values holds only the user's OWN channels —
|
|
798
|
-
// the derived ones come from the dev-load flag at display/render time.
|
|
799
|
-
const channels = out[CHANNELS_FLAG_ID];
|
|
800
|
-
const derived = derivedChannelValues(out);
|
|
801
|
-
if (channels && channels.kind === "text-list" && derived.length > 0) {
|
|
802
|
-
const ownOnly = channels.values.filter((v) => !derived.includes(v));
|
|
803
|
-
out[CHANNELS_FLAG_ID] = {
|
|
804
|
-
kind: "text-list",
|
|
805
|
-
// Keep enabled only if the user has their own channels; a channels list
|
|
806
|
-
// that was purely derived shouldn't appear enabled after the subtraction.
|
|
807
|
-
enabled: ownOnly.length > 0,
|
|
808
|
-
values: ownOnly,
|
|
809
|
-
};
|
|
810
|
-
}
|
|
811
|
-
return { flags: out, leftovers };
|
|
812
|
-
}
|
|
813
|
-
/**
|
|
814
|
-
* High-level entry point: read shell rc text, parse the managed block, and
|
|
815
|
-
* return a populated flag map plus the parsed alias name. Returns null when
|
|
816
|
-
* there's no managed block to parse from.
|
|
817
|
-
*/
|
|
818
|
-
export function parseAliasFromRc(rcText) {
|
|
819
|
-
const parsed = parseManagedBlock(rcText);
|
|
820
|
-
if (!parsed || !parsed.aliasName)
|
|
821
|
-
return null;
|
|
822
|
-
return {
|
|
823
|
-
aliasName: parsed.aliasName,
|
|
824
|
-
flags: argsToFlagValues(parsed.args),
|
|
825
|
-
};
|
|
826
|
-
}
|
|
827
|
-
const ANY_ALIAS_LINE_RE = /^alias\s+([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(['"])(.*)\2\s*$/;
|
|
828
|
-
/**
|
|
829
|
-
* Tokenize a general (hand-written) POSIX alias body into argv strings.
|
|
830
|
-
*
|
|
831
|
-
* Unlike {@link tokenizePosixAliasBody} — which only undoes OUR writer's escape
|
|
832
|
-
* scheme — this handles the shapes a human would type: bare words, single-
|
|
833
|
-
* quoted runs (literal, no escapes), and double-quoted runs (we treat the
|
|
834
|
-
* content literally; we do NOT expand `$VAR` or `$(cmd)`). Adjacent quoted and
|
|
835
|
-
* bare pieces with no whitespace between them concatenate into one argv token,
|
|
836
|
-
* matching shell word-joining (`foo' bar'` → `foo bar`).
|
|
837
|
-
*
|
|
838
|
-
* Returns `null` for anything we can't cleanly tokenize: unterminated quotes,
|
|
839
|
-
* or a body containing a shell substitution (`$(`, backtick) or variable (`$`)
|
|
840
|
-
* — those can't be faithfully represented as a static flag value, so the
|
|
841
|
-
* caller treats the whole alias as not-adoptable rather than guessing.
|
|
842
|
-
*/
|
|
843
|
-
export function tokenizeGeneralAliasBody(body) {
|
|
844
|
-
const tokens = [];
|
|
845
|
-
let current = "";
|
|
846
|
-
let inToken = false;
|
|
847
|
-
let i = 0;
|
|
848
|
-
const len = body.length;
|
|
849
|
-
const flush = () => {
|
|
850
|
-
if (inToken) {
|
|
851
|
-
tokens.push(current);
|
|
852
|
-
current = "";
|
|
853
|
-
inToken = false;
|
|
854
|
-
}
|
|
855
|
-
};
|
|
856
|
-
while (i < len) {
|
|
857
|
-
const ch = body[i];
|
|
858
|
-
if (ch === " " || ch === "\t") {
|
|
859
|
-
flush();
|
|
860
|
-
i += 1;
|
|
861
|
-
continue;
|
|
862
|
-
}
|
|
863
|
-
// Bail on dynamic content — we can't round-trip a variable/substitution.
|
|
864
|
-
if (ch === "$" || ch === "`")
|
|
865
|
-
return null;
|
|
866
|
-
if (ch === "'") {
|
|
867
|
-
// Single-quoted run: literal until the next single quote.
|
|
868
|
-
const end = body.indexOf("'", i + 1);
|
|
869
|
-
if (end === -1)
|
|
870
|
-
return null; // unterminated
|
|
871
|
-
current += body.slice(i + 1, end);
|
|
872
|
-
inToken = true;
|
|
873
|
-
i = end + 1;
|
|
874
|
-
continue;
|
|
875
|
-
}
|
|
876
|
-
if (ch === '"') {
|
|
877
|
-
// Double-quoted run: literal until the next double quote. We reject any
|
|
878
|
-
// `$` or backtick inside (caught at the top of the loop on the next
|
|
879
|
-
// pass only if unquoted — so scan the run explicitly here).
|
|
880
|
-
const end = body.indexOf('"', i + 1);
|
|
881
|
-
if (end === -1)
|
|
882
|
-
return null; // unterminated
|
|
883
|
-
const inner = body.slice(i + 1, end);
|
|
884
|
-
if (inner.includes("$") || inner.includes("`"))
|
|
885
|
-
return null;
|
|
886
|
-
current += inner;
|
|
887
|
-
inToken = true;
|
|
888
|
-
i = end + 1;
|
|
889
|
-
continue;
|
|
890
|
-
}
|
|
891
|
-
// Bare character.
|
|
892
|
-
current += ch;
|
|
893
|
-
inToken = true;
|
|
894
|
-
i += 1;
|
|
895
|
-
}
|
|
896
|
-
flush();
|
|
897
|
-
return tokens;
|
|
898
|
-
}
|
|
899
|
-
/**
|
|
900
|
-
* Parse a single hand-written `alias <name>=<quote><body><quote>` line into an
|
|
901
|
-
* AdoptableAlias (sans `lineRange`/`others`, which the scanner fills in), or
|
|
902
|
-
* null when the line isn't a `claude`-wrapping alias we can tokenize.
|
|
903
|
-
*/
|
|
904
|
-
function parseAdoptableLine(line) {
|
|
905
|
-
const match = ANY_ALIAS_LINE_RE.exec(line.trim());
|
|
906
|
-
if (!match)
|
|
907
|
-
return null;
|
|
908
|
-
const [, name, , body] = match;
|
|
909
|
-
const tokens = tokenizeGeneralAliasBody(body);
|
|
910
|
-
if (!tokens || tokens.length === 0 || tokens[0] !== "claude")
|
|
911
|
-
return null;
|
|
912
|
-
const args = tokens.slice(1);
|
|
913
|
-
const { flags, leftovers } = argsToFlagValuesWithLeftovers(args);
|
|
914
|
-
// Fixpoint: render the parsed flags back to tokens and re-parse. If the
|
|
915
|
-
// result differs, a token was mis-bucketed (e.g. a select value mistaken
|
|
916
|
-
// for bare). Only an exact fixpoint with no leftovers is lossless.
|
|
917
|
-
const config = { aliasName: name, flags: withDefaults(flags) };
|
|
918
|
-
const reparsed = argsToFlagValues(renderArgsAsTokens(config));
|
|
919
|
-
const fixpoint = flagsDeepEqual(withDefaults(flags), withDefaults(reparsed));
|
|
920
|
-
const lossless = leftovers.length === 0 && fixpoint;
|
|
921
|
-
return { name, flags, leftovers, lossless, rawLine: line };
|
|
922
|
-
}
|
|
923
|
-
/**
|
|
924
|
-
* Scan rc text for a top-level, hand-written `claude`-wrapping alias OUTSIDE
|
|
925
|
-
* the managed block. Returns the first such alias (with any others noted), or
|
|
926
|
-
* null when none is found.
|
|
927
|
-
*
|
|
928
|
-
* "Top-level" = the line's indentation is zero. We deliberately skip indented
|
|
929
|
-
* lines: an alias nested in a function or `if` block can't be replaced by the
|
|
930
|
-
* managed block without dragging the block into that scope.
|
|
931
|
-
*
|
|
932
|
-
* Lines inside an existing managed block are ignored — adoption is only for
|
|
933
|
-
* the no-managed-block case (the screen's mount checks that separately, but we
|
|
934
|
-
* guard here too so the function is correct in isolation).
|
|
935
|
-
*/
|
|
936
|
-
export function findAdoptableAlias(rcText) {
|
|
937
|
-
const lines = rcText.split("\n");
|
|
938
|
-
// Compute the [begin, end] line span of the managed block, if present, so we
|
|
939
|
-
// can exclude any alias inside it.
|
|
940
|
-
let blockStart = -1;
|
|
941
|
-
let blockEnd = -1;
|
|
942
|
-
for (let i = 0; i < lines.length; i++) {
|
|
943
|
-
if (lines[i].includes(BLOCK_BEGIN))
|
|
944
|
-
blockStart = i;
|
|
945
|
-
else if (lines[i].includes(BLOCK_END)) {
|
|
946
|
-
blockEnd = i;
|
|
947
|
-
break;
|
|
948
|
-
}
|
|
949
|
-
}
|
|
950
|
-
const insideBlock = (i) => blockStart !== -1 && blockEnd !== -1 && i >= blockStart && i <= blockEnd;
|
|
951
|
-
let picked = null;
|
|
952
|
-
const others = [];
|
|
953
|
-
for (let i = 0; i < lines.length; i++) {
|
|
954
|
-
const line = lines[i];
|
|
955
|
-
if (insideBlock(i))
|
|
956
|
-
continue;
|
|
957
|
-
// Top-level only: no leading whitespace.
|
|
958
|
-
if (/^\s/.test(line))
|
|
959
|
-
continue;
|
|
960
|
-
const parsed = parseAdoptableLine(line);
|
|
961
|
-
if (!parsed)
|
|
962
|
-
continue;
|
|
963
|
-
if (picked === null) {
|
|
964
|
-
picked = { ...parsed, lineRange: [i, i], others: [] };
|
|
965
|
-
}
|
|
966
|
-
else {
|
|
967
|
-
others.push(line.trim());
|
|
968
|
-
}
|
|
969
|
-
}
|
|
970
|
-
if (picked)
|
|
971
|
-
picked.others = others;
|
|
972
|
-
return picked;
|
|
973
|
-
}
|
|
974
|
-
/**
|
|
975
|
-
* Replace a line range in `existing` (inclusive, zero-based) with `block`.
|
|
976
|
-
* Used to absorb an adopted hand-written alias: the original line is removed
|
|
977
|
-
* and the managed block takes its place, guaranteeing no duplicate alias.
|
|
978
|
-
* Pure function — no I/O. Falls back to {@link spliceManagedBlock} semantics
|
|
979
|
-
* (append) when the range is out of bounds.
|
|
980
|
-
*/
|
|
981
|
-
export function spliceManagedBlockAtRange(existing, block, range) {
|
|
982
|
-
const lines = existing.split("\n");
|
|
983
|
-
const [start, end] = range;
|
|
984
|
-
if (start < 0 || end >= lines.length || start > end) {
|
|
985
|
-
return spliceManagedBlock(existing, block);
|
|
986
|
-
}
|
|
987
|
-
// `block` ends with a newline; splice it as its own line(s) where the old
|
|
988
|
-
// alias line was. Rejoin and drop the duplicate trailing newline `block`
|
|
989
|
-
// would introduce when followed by more lines.
|
|
990
|
-
const before = lines.slice(0, start);
|
|
991
|
-
const after = lines.slice(end + 1);
|
|
992
|
-
const blockLines = block.replace(/\n$/, "").split("\n");
|
|
993
|
-
return [...before, ...blockLines, ...after].join("\n");
|
|
994
|
-
}
|
|
995
|
-
/** Fill any catalog flags missing from a partial map with their defaults. */
|
|
996
|
-
function withDefaults(partial) {
|
|
997
|
-
const out = {};
|
|
998
|
-
for (const flag of ALIAS_FLAGS) {
|
|
999
|
-
out[flag.id] = partial[flag.id] ?? defaultValueFor(flag);
|
|
1000
|
-
}
|
|
1001
|
-
return out;
|
|
1002
|
-
}
|
|
1003
|
-
/** Deep-equal two flag maps via per-key JSON compare (small maps). */
|
|
1004
|
-
function flagsDeepEqual(a, b) {
|
|
1005
|
-
const aKeys = Object.keys(a).sort();
|
|
1006
|
-
const bKeys = Object.keys(b).sort();
|
|
1007
|
-
if (aKeys.length !== bKeys.length)
|
|
1008
|
-
return false;
|
|
1009
|
-
for (let i = 0; i < aKeys.length; i++) {
|
|
1010
|
-
if (aKeys[i] !== bKeys[i])
|
|
1011
|
-
return false;
|
|
1012
|
-
}
|
|
1013
|
-
for (const k of aKeys) {
|
|
1014
|
-
if (JSON.stringify(a[k]) !== JSON.stringify(b[k]))
|
|
1015
|
-
return false;
|
|
1016
|
-
}
|
|
1017
|
-
return true;
|
|
1018
|
-
}
|