Debian Codegraph @

cli/tools-cli/test/versioning/fixtures/case-4/expected-spec/old-spec/shared.ts

raw symbols SCIP
1 const SETTINGS_PATH = "~/.fig/tools/all-settings.json";
2 const ACTIONS_PATH = "~/.fig/apps/autocomplete/actions.json";
3
4 interface Setting {
5 settingName: string;
6 description: string;
7 type: "boolean" | "text" | "single_select" | "multiselect";
8 options?: Array<string | { name: string; description: string }>;
9 default?: string;
10 }
11
12 interface Action {
13 identifier: string;
14 name: string;
15 description: string;
16 availability: string;
17 defaultBindings: string[];
18 }
19
20 const devCompletionsFolderGenerator: Fig.Generator = {
21 script: '\\ls -d -1 "$PWD/"**/',
22 postProcess: (out) =>
23 out.split("\n").map((folder) => {
24 const paths = folder.split("/");
25 paths.pop();
26
27 return {
28 name: paths.pop(),
29 insertValue: folder,
30 icon: `fig://${folder}`,
31 };
32 }),
33 };
34
35 const disableForCommandsGenerator: Fig.Generator = {
36 script: "fig settings autocomplete.disableForCommands",
37 postProcess: (out) => {
38 const existing = out.split("\n").filter((item) => item.length > 0);
39
40 const append: Fig.Suggestion = {
41 name: "Disable new CLI...",
42 description: `You must pass a valid JSON array of CLI tools contained within single quotes. e.g. '["npm","cd","ls"]'`,
43 icon: "fig://icon?type=box",
44 insertValue: JSON.stringify(existing.concat(["{cursor}"])),
45 };
46
47 const enabledAll: Fig.Suggestion = {
48 name: "Enable all commands",
49 icon: "fig://icon?type=box",
50 insertValue: "'[]'",
51 };
52
53 return [append, enabledAll].concat(
54 existing.map((disabledCommand) => {
55 return {
56 name: `Enable ${disabledCommand}`,
57 icon: "fig://icon?type=box",
58 insertValue: JSON.stringify(
59 existing.filter((cmd) => cmd != disabledCommand)
60 ),
61 };
62 })
63 );
64 },
65 };
66
67 export const themesGenerator: Fig.Generator = {
68 script: "fig theme --list",
69 postProcess: (output) => {
70 const builtinThemes = [
71 {
72 name: "system",
73 icon: "💻",
74 priority: 51,
75 },
76 {
77 name: "light",
78 icon: "fig://template?color=ffffff&badge=☀️",
79 priority: 51,
80 },
81 {
82 name: "dark",
83 icon: "fig://template?color=000000&badge=🌙",
84 priority: 51,
85 },
86 ];
87 return output
88 .split("\n")
89 .map((theme) => ({ name: theme.replace(".json", "") }))
90 .concat(builtinThemes);
91 },
92 };
93
94 export const SETTINGS_GENERATOR: Record<string, Fig.Generator> = {
95 "autocomplete.devCompletionsFolder": devCompletionsFolderGenerator,
96 "autocomplete.disableForCommands": disableForCommandsGenerator,
97 "autocomplete.theme": themesGenerator,
98 };
99
100 export const subsystemsGenerator: Fig.Generator = {
101 script: "\\ls ~/.fig/logs",
102 trigger: (curr, prev) => {
103 // trigger on new token
104 return curr.length === 0 && prev.length > 0;
105 },
106 postProcess: (out, tokens) => {
107 const insertedLogFiles = new Set(tokens.slice(0, -1));
108 return out
109 .split("\n")
110 .map((name) => name.replace(".log", ""))
111 .concat("figterm")
112 .map((name) => ({ name, icon: "🪵" }))
113 .filter((suggestion) => !insertedLogFiles.has(suggestion.name));
114 },
115 };
116
117 export const settingsSpecGenerator: Fig.Subcommand["generateSpec"] = async (
118 _,
119 executeShellCommand
120 ) => {
121 const text = await executeShellCommand(
122 "fig _ request --method GET --route '/settings/all'"
123 );
124 const { settings, actions } = JSON.parse(text) as {
125 settings: Setting[];
126 actions: Action[];
127 };
128
129 const actionSuggestions: Fig.Suggestion[] = actions.map((action) => ({
130 name: action.identifier.startsWith("autocomplete.")
131 ? action.identifier.slice(13)
132 : action.identifier,
133 description: action.description,
134 icon: "⚡️",
135 }));
136
137 return {
138 name: "settings",
139 subcommands: settings.map(
140 ({
141 settingName: name,
142 description,
143 type,
144 options,
145 default: defaultValue,
146 }) => {
147 const suggestions =
148 type === "boolean"
149 ? ["true", "false"]
150 : name.startsWith("autocomplete.keybindings.")
151 ? actionSuggestions
152 : options?.map((option) => ({
153 name: option["name"] || option,
154 description: option["description"] || "",
155 }));
156 // const insertValue =
157 // type === "multiselect" ? `${name} '{cursor}'` : undefined;
158
159 const generators = SETTINGS_GENERATOR[name];
160
161 return {
162 name,
163 description,
164 icon: "fig://icon?type=commandkey",
165 // insertValue,
166 args: {
167 name: type,
168 default: defaultValue,
169 suggestions: generators ? [] : suggestions,
170 generators,
171 },
172 };
173 }
174 ),
175 };
176 };
177
178 interface Plugin {
179 name: string;
180 icon: string;
181 description: string;
182 }
183
184 export const pluginsGenerator = (init: {
185 installed: boolean;
186 }): Fig.Generator => ({
187 cache: {
188 strategy: "stale-while-revalidate",
189 },
190 custom: async (_tokens, executeShellCommand) => {
191 const script = init.installed
192 ? "fig plugins list --format json --installed"
193 : "fig plugins list --format json";
194 const out = await executeShellCommand(script);
195 const json = JSON.parse(out) as Plugin[];
196 return json.map((plugin) => ({
197 name: plugin.name,
198 icon: !plugin.icon?.startsWith("https://") ? plugin.icon : "📦",
199 description: plugin.description,
200 }));
201 },
202 });
203
204 /**
205 * Fig team
206 */
207
208 // For insertions like `fig user tokens <subcommand> --team <team name> <arg holding this generator>`
209 export const tokensGenerators: Fig.Generator = {
210 cache: {
211 strategy: "stale-while-revalidate",
212 },
213 custom: async (tokens, executeShellCommand) => {
214 const teamOptionIndex = tokens.findIndex((value) =>
215 value.startsWith("--team")
216 );
217 if (teamOptionIndex === -1) return [];
218 let teamName: string;
219 if (tokens[teamOptionIndex].includes("=")) {
220 teamName = tokens[teamOptionIndex + 1].split("=")[1];
221 } else {
222 teamName = tokens[teamOptionIndex + 1];
223 }
224 const out = JSON.parse(
225 await executeShellCommand(
226 `fig user tokens list --team ${teamName} --format json`
227 )
228 ) as {
229 createdAt: string;
230 description?: string;
231 expiresAt?: string;
232 lastUsedAt: string;
233 name: string;
234 namespace: { username: string };
235 }[];
236 return out.map((token) => {
237 return {
238 name: token.name,
239 description: `Team: ${token.namespace.username}.${
240 token.description ? " " + token.description : ""
241 }`,
242 };
243 });
244 },
245 };
246
247 export const teamsGenerators: Fig.Generator = {
248 cache: {
249 strategy: "stale-while-revalidate",
250 },
251 script: "fig team --list --format json",
252 postProcess: (out) => {
253 return (
254 JSON.parse(out) as { id: number; name: string; specs: string[] }[]
255 ).map((team) => ({ name: team.name, priority: 75 }));
256 },
257 };
258
259 // For insertions like `fig teams <team name> <members subcommand> <arg holding this generator>`
260 export const membersGenerators: Fig.Generator = {
261 cache: {
262 strategy: "stale-while-revalidate",
263 ttl: 1000 * 60,
264 },
265 custom: async (tokens, executeShellCommand) => {
266 const teamName = tokens.at(-3);
267 const out = JSON.parse(
268 await executeShellCommand(`fig team --format json ${teamName} members`)
269 ) as { email: string; role: string }[];
270 return out.map((member) => {
271 return {
272 name: member.email,
273 description: `Role: ${member.role}`,
274 };
275 });
276 },
277 };
278
279 // For insertions like `fig teams <team name> <invitations subcommand>`
280 export const invitationsGenerators: Fig.Generator = {
281 cache: {
282 strategy: "stale-while-revalidate",
283 ttl: 1000 * 60,
284 },
285 custom: async (tokens, executeShellCommand) => {
286 const teamName = tokens.at(-3);
287 const out = JSON.parse(
288 await executeShellCommand(
289 `fig team --format json ${teamName} invitations`
290 )
291 ) as { email: string; role: string }[];
292 return out.map((invitation) => {
293 return {
294 name: invitation.email,
295 description: `Role: ${invitation.role}`,
296 };
297 });
298 },
299 };
300
301 /**
302 * Fig workflows
303 */
304
305 export const workflowsSpecGenerator: Fig.Subcommand["generateSpec"] = async (
306 _,
307 exec
308 ) => {
309 const response = await exec(
310 "fig _ request --route '/workflows' --method GET"
311 );
312 const workflows = JSON.parse(response);
313 const subcommands = workflows.map((workflow) => {
314 const displayName = `${workflow.displayName ?? workflow.name} | @${
315 workflow.namespace
316 }`;
317
318 const options = workflow.parameters.map((param) => {
319 const option: Fig.Option = {
320 name: `--${param.name}`,
321 description: param.description,
322 };
323 switch (param.type) {
324 case "text":
325 option.args = {
326 name: param.name,
327 };
328 case "selector":
329 let generators: Fig.Generator[] = [];
330 if (param.typeData.generators) {
331 generators = param.typeData.generators
332 .filter((generator) => generator.type === "script")
333 .map((generator) => ({
334 script: generator.script,
335 splitOn: "\n",
336 }));
337 }
338 option.args = {
339 name: param.name,
340 suggestions: param.typeData.suggestions,
341 generators,
342 };
343 }
344 return option;
345 });
346
347 // Add @namespace/name and name (if this workflow is associated with user's namespace)
348 const name = [`@${workflow.namespace}/${workflow.name}`];
349 if (workflow.isOwnedByUser) {
350 name.push(workflow.name);
351 }
352
353 return {
354 displayName,
355 icon: workflow.icon ?? "⚡️",
356 name,
357 insertValue: workflow.isOwnedByUser ? workflow.name : name[0],
358 description: workflow.description,
359 options,
360 };
361 });
362 return {
363 name: "run",
364 subcommands,
365 filterStrategy: "fuzzy",
366 };
367 };
368
369 export const sshHostsGenerator: Fig.Generator = {
370 script: "fig _ request --method GET --route /access/hosts/all",
371 cache: {
372 strategy: "stale-while-revalidate",
373 },
374 postProcess: (out) => {
375 return (
376 JSON.parse(out) as {
377 nickName: string;
378 namespace: string;
379 description: string;
380 }[]
381 ).map((host) => ({
382 insertValue: `@${host.namespace}/${host.nickName}`,
383 displayName: `${host.nickName} (@${host.namespace})`,
384 name: `@${host.namespace}/${host.nickName}`,
385 description: host.description,
386 }));
387 },
388 };
389
390 export const sshIdentityGenerator: Fig.Generator = {
391 custom: async (tokens, executeShellCommand) => {
392 const host = tokens.slice(2).find((value) => !value.startsWith("-"));
393 if (host === undefined) {
394 return [];
395 }
396 const hosts = JSON.parse(
397 await executeShellCommand(`fig ssh ${host} --get-identities`)
398 ) as { displayName: string; username: string }[];
399
400 return hosts.map((host) => ({
401 name: host.displayName,
402 }));
403 },
404 };
405
406 export const userGenerator: Fig.Generator = {
407 script: "fig user list-accounts",
408 postProcess: (out) => {
409 if (out.startsWith("error: ")) {
410 return [];
411 }
412 return out
413 .trim()
414 .split("\n")
415 .map((name) => ({ name, icon: "👤" }));
416 },
417 };
418
419 export default {};