-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·406 lines (392 loc) · 15.3 KB
/
Copy pathindex.js
File metadata and controls
executable file
·406 lines (392 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
import bump from "./lib/release/bump.js";
import chalk from "chalk";
import { generateFScripts, generateToc } from "./lib/generators/index.js";
import parseScriptFile from "./lib/parsers/parseScriptsMd.js";
import upgradePackages from "./lib/upgradePackages.js";
import { runCLICommand, runParallel, runSequence } from "./lib/running/index.js";
import { clearRecent, startPackageScripts, startScripts } from "./lib/startScripts.js";
import parseTask from "./lib/running/parseTask.js";
import { selectPlugin } from "./lib/taskList.js";
import validateNotInDev from "./lib/git/validateNotDev.js";
import encrypt from "./lib/encryption/encryption.js";
import { clear, getEnvArg } from "./lib/utils/index.js";
import doctor from "./lib/doctor/doctor.js";
import completion from "./lib/completions/completion.js";
import {
loadPlugins,
registerPluginCommands,
findExternalPluginDirs
} from "./lib/plugins/loader.js";
import { fireHook } from "./lib/plugins/hooks.js";
import yargs from "yargs";
import fsrLog from "./lib/utils/console.js";
import commit from "./lib/git/commit.js";
import greet from "./lib/shell/greet.js";
const taskName = chalk.rgb(39, 173, 96).bold.underline;
const textDescription = chalk.rgb(159, 161, 181);
/**
* Single source of truth for all built-in fsr commands.
*
* Fields:
* cmd — yargs command string (e.g. "run [task]")
* desc — description shown in --help and the interactive picker
* builder — optional yargs builder fn for positionals/options
* handler — async (argv) => void
* examples — optional [[usage, description], ...] for multi-variant commands
* menu — include in the bare-`fsr` interactive picker (default false)
*/
const COMMANDS = [
{
cmd: "branch",
desc: "Create a new branch — prevents commits directly on master or development",
handler: async () => validateNotInDev()
},
{
cmd: "commit",
desc: "Stage and commit changes with AI-generated conventional commit messages",
handler: async () => commit()
},
{
cmd: "start",
desc: "Choose a category then a task to run interactively",
handler: async (argv) => startScripts(true, argv.env || null),
menu: true
},
{
cmd: "scripts",
desc: "Choose a script from package.json",
handler: async () => startPackageScripts(),
menu: true
},
{
cmd: "list",
desc: "Select any task with text autocompletion",
handler: async (argv) => startScripts(false, argv.env || null),
menu: true
},
{
cmd: "run [task]",
desc: "Run a specific task by name",
builder: (y) => y.positional("task", { describe: "task name", default: "" }),
handler: async (argv) => {
const { task } = argv;
const parsed = await parseScriptFile(argv.env ? { env: argv.env } : {});
if (!parsed) {
fsrLog.error(chalk.bold.underline.red("No fscripts.md file found"));
return;
}
const taskData = parsed.allTasks.find((t) => t.name === task);
if (!taskData) {
fsrLog.error(`${chalk.bold.underline.red("Task not found")} ${task}`);
return;
}
await runCLICommand(parseTask(taskData));
},
examples: [["$0 run start:web", "Run task 'start:web'"]],
menu: true
},
{
cmd: "upgrade",
desc: "Upgrade all packages except those listed in 'ignore-upgrade'",
handler: async () => upgradePackages(),
menu: true
},
{
cmd: "bump",
desc: "Bump the version in package.json and beautify it",
handler: async (argv) => bump(argv.type, argv.skipGit === "true"),
menu: true
},
{
cmd: "run-s [tasks..]",
desc: "Run a set of tasks sequentially",
handler: async (argv) =>
runSequence(argv.tasks || [], await parseScriptFile(argv.env ? { env: argv.env } : {})),
examples: [["$0 run-s start:web start:desktop", "Run start:web then start:desktop"]],
menu: true
},
{
cmd: "run-p [tasks..]",
desc: "Run tasks in parallel",
handler: async (argv) =>
runParallel(argv.tasks || [], await parseScriptFile(argv.env ? { env: argv.env } : {})),
examples: [
["$0 run-p start:web start:desktop", "Run start:web and start:desktop simultaneously"]
],
menu: true
},
{
cmd: "encryption",
desc: "Encrypt or decrypt secret files interactively",
handler: async () => encrypt.init(),
menu: true
},
{
cmd: "encrypt",
desc: "Encrypt secret files",
handler: async () => encrypt.encrypt()
},
{
cmd: "decrypt",
desc: "Decrypt secret files",
handler: async () => encrypt.decrypt()
},
{
cmd: "clear",
desc: "Clear recent task history",
handler: async () => clearRecent()
},
{
cmd: "generate",
desc: "Generate a sample fscripts.md from package.json",
handler: async () => generateFScripts(),
menu: true
},
{
cmd: "toc",
desc: "Regenerate the Table of Contents in fscripts.md",
handler: async (argv) => generateToc(argv._[1]),
menu: true
},
{
cmd: "doctor",
desc: "Run diagnostics and check system health",
builder: (y) =>
y
.option("fix", {
alias: "f",
type: "boolean",
description: "Auto-fix issues when possible",
default: false
})
.option("json", {
type: "boolean",
description: "Output results as JSON",
default: false
})
.option("verbose", {
alias: "v",
type: "boolean",
description: "Show verbose output",
default: false
}),
handler: async (argv) => doctor(argv),
examples: [
["$0 doctor --fix", "Run diagnostics and auto-fix issues"],
["$0 doctor --json", "Output results as JSON"]
],
menu: true
},
{
cmd: "plugins",
desc: "List all installed plugins (built-in and npm fscr-plugin-*)",
handler: async () => {
const { runnablePlugins, commands: pluginCmds } = await loadPlugins();
const external = findExternalPluginDirs();
const allPlugins = [
...runnablePlugins,
...pluginCmds
.filter((c) => !runnablePlugins.some((p) => p.name === c.name))
.map((c) => ({
name: c.name,
description: c.description || "",
source: "builtin"
}))
];
if (allPlugins.length === 0) {
fsrLog.log(chalk.yellow("No plugins found."));
return;
}
fsrLog.log(chalk.bold(`\nInstalled plugins (${allPlugins.length}):`));
fsrLog.log(chalk.dim("─".repeat(60)));
for (const p of allPlugins) {
const badge =
p.source === "npm"
? chalk.blue("[npm]")
: p.source === "local"
? chalk.green("[local]")
: chalk.dim("[builtin]");
fsrLog.log(` ${badge} ${chalk.bold(p.name)} ${chalk.dim(p.description)}`);
}
if (external.length > 0) {
fsrLog.log(
chalk.dim(`\n${external.length} npm plugin(s) discovered in node_modules.`)
);
}
fsrLog.log("");
},
menu: true
},
{
cmd: "completion [action]",
desc: "Manage shell tab completions",
builder: (y) =>
y
.positional("action", {
describe: "Action to perform",
type: "string",
choices: ["install", "uninstall", "status", "generate"]
})
.option("shell", {
alias: "s",
type: "string",
description: "Target shell",
choices: ["bash", "zsh", "fish", "powershell"]
})
.option("force", {
alias: "f",
type: "boolean",
description: "Force reinstall",
default: false
}),
handler: async (argv) => completion(argv),
examples: [
["$0 completion install", "Install completions for your shell"],
["$0 completion status", "Check completion installation status"],
["$0 completion --shell zsh", "Install completions for zsh"]
],
menu: true
},
{
cmd: "greet [action]",
desc: "Install a shell greeting that reminds you to use yarn fsr when fscripts.md is present",
builder: (y) =>
y
.positional("action", {
describe: "Action to perform",
type: "string",
choices: ["install", "uninstall", "status"]
})
.option("shell", {
alias: "s",
type: "string",
description: "Target shell (bash or zsh)",
choices: ["bash", "zsh"]
})
.option("force", {
alias: "f",
type: "boolean",
description: "Force reinstall",
default: false
}),
handler: async (argv) => greet(argv),
examples: [
["$0 greet install", "Install the greeting hook for your shell"],
["$0 greet uninstall", "Remove the greeting hook"],
["$0 greet status", "Check if the greeting hook is installed"]
],
menu: true
}
];
(async () => {
// ------------------------------------------------------------------
// Inject NODE_ENV and FSR_ENV as early as possible — before yargs
// invokes any command handler and before any child process spawns —
// so that all subsequent code and spawned children inherit the value.
//
// We scan process.argv directly (rather than waiting for yargs) to
// guarantee the assignment happens before yi.argv triggers handlers.
// Handles both "--env staging" / "-e staging" and "--env=staging" forms.
// ------------------------------------------------------------------
const { env: _envProfile } = getEnvArg(process.argv.slice(2));
const _profile = _envProfile || "development";
process.env.NODE_ENV = _profile;
process.env.FSR_ENV = _profile;
// NOTE: We intentionally do NOT overwrite process.argv here.
// --env / -e is registered as a global yargs option, so yargs will parse
// it correctly from the original argv. Stripping it was preventing
// argv.env from being set inside command handlers (run-p, run-s, etc.).
// clear();
const { commands: pluginCommands, runnablePlugins } = await loadPlugins();
// Build yargs from COMMANDS — single source of truth for registration,
// examples, BUILTIN_COMMANDS, and the interactive picker menu.
let yi = yargs(process.argv.slice(2)).usage("Usage: $0 <command> [options]");
for (const { cmd, desc, builder, handler, examples } of COMMANDS) {
yi = yi.command(cmd, desc, builder || (() => {}), handler);
// Auto-generate a base example from the command name and description.
const base = cmd.split(" ")[0];
yi = yi.example(taskName(`$0 ${base}`), textDescription(desc));
for (const [ex, exDesc] of examples || []) {
yi = yi.example(taskName(ex), textDescription(exDesc));
}
}
yi = yi
.option("env", {
alias: "e",
type: "string",
description:
"Filter scripts to the named environment profile (defined via `## [env:name]` sections in fscripts.md)",
global: true
})
.help();
registerPluginCommands(yi, pluginCommands);
// Derived from COMMANDS — no manual maintenance required.
const BUILTIN_COMMANDS = new Set([
...COMMANDS.map((c) => c.cmd.split(" ")[0]),
"help",
...pluginCommands.map((c) => c.name)
]);
const argv = yi.argv;
if (argv && argv._ && argv._.length === 0) {
// Interactive picker: menu-flagged commands + plugins.
const commandItems = COMMANDS.filter((c) => c.menu).map((c) => ({
name: c.cmd.split(" ")[0],
message: c.desc
}));
const pluginItems = runnablePlugins.map((p) => ({
name: `plugin:${p.name}`,
message: p.description
}));
const choice = await selectPlugin([...commandItems, ...pluginItems]);
if (!choice) {
fsrLog.log(chalk.green.bold("See you soon!"));
return;
}
if (choice.startsWith("plugin:")) {
const pluginName = choice.replace("plugin:", "");
const pluginMatch = runnablePlugins.find((p) => p.name === pluginName);
if (pluginMatch) {
const start = Date.now();
await fireHook("pre-task", { taskName: pluginMatch.name });
try {
await pluginMatch.run();
await fireHook("post-task", {
taskName: pluginMatch.name,
duration: Date.now() - start,
success: true
});
} catch (err) {
await fireHook("task-error", {
taskName: pluginMatch.name,
duration: Date.now() - start,
error: err
});
}
}
} else {
// Run the built-in command in-process instead of spawning a second
// `yarn fsr <choice>`. Spawning a child renders a second Ink app on
// the same inherited TTY, and the raw-mode handoff between the two
// Ink runtimes intermittently swallows the first keypress (the
// "press Enter twice to load a script" bug).
const command = COMMANDS.find((c) => c.cmd.split(" ")[0] === choice);
if (command) {
await command.handler({ _: [choice], $0: "fsr", env: argv.env || null });
}
}
} else if (argv._ && argv._.length > 0 && !BUILTIN_COMMANDS.has(argv._[0])) {
// Bare task shorthand: `fsr release:publish` → same as `fsr run release:publish`
const taskArg = argv._[0];
const parsed = await parseScriptFile(argv.env ? { env: argv.env } : {});
if (!parsed) {
fsrLog.error(chalk.bold.underline.red("No fscripts.md file found"));
return;
}
const taskData = parsed.allTasks.find((t) => t.name === taskArg);
if (!taskData) {
fsrLog.error(`${chalk.bold.underline.red("Task not found:")} ${taskArg}`);
return;
}
await runCLICommand(parseTask(taskData));
}
})();