plugins-command.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. import { formatJson } from "@zcode/core";
  2. import type { GlobalOptions, RunContext } from "@zcode/shared-types";
  3. import type { SetZCodePluginEnabledResult, ZCodePluginInstallData } from "@zcode/bootstrap";
  4. import {
  5. formatAvailablePluginJson,
  6. formatDiagnosticJson,
  7. formatDiagnosticLines,
  8. formatHumanAvailableList,
  9. formatHumanPluginList,
  10. formatHumanPluginSet,
  11. formatHumanPluginUninstall,
  12. formatInstalledPluginJson,
  13. formatPluginJson,
  14. formatPluginSetJson,
  15. writeWarnings,
  16. } from "./plugins-command-format.js";
  17. import {
  18. ambiguousPluginError,
  19. baseOptions,
  20. confirmUninstall,
  21. hasErrors,
  22. type PluginListItem,
  23. PluginsUsageError,
  24. reportPluginsError,
  25. requireOne,
  26. resolveDep,
  27. resolveLoadedPluginId,
  28. resolveScope,
  29. splitPluginIdentifier,
  30. type PluginsCommandDependencies,
  31. type PluginsCommandFlags,
  32. } from "./plugins-command-shared.js";
  33. import { runMarketplaceCommand } from "./plugins-marketplace-command.js";
  34. export type {
  35. PluginsCommandDependencies,
  36. PluginsCommandFlags,
  37. PluginsCommandOverrides,
  38. } from "./plugins-command-shared.js";
  39. const PLUGINS_COMMAND_USAGE = `Usage: zcode plugins <command> [options]
  40. Commands:
  41. list [--json] [--available] List installed plugins; --available also lists the marketplace catalog
  42. install <plugin>[@marketplace] [-s <scope>] Install a plugin from a known marketplace
  43. uninstall <plugin> [-s <scope>] [--keep-data] [--force]
  44. Uninstall a plugin (--keep-data keeps its data directory)
  45. enable <plugin> [-s <scope>] Enable a plugin
  46. disable [plugin] [-a|--all] [-s <scope>] Disable a plugin, or every enabled plugin with --all
  47. update <plugin> [-s <scope>] Update a plugin to the latest marketplace version
  48. validate <path> Validate a plugin or marketplace manifest
  49. marketplace add <source> [--scope <scope>] [--sparse <path>]
  50. Add a marketplace from a URL, path, or GitHub repo
  51. marketplace list [--json] List configured marketplaces
  52. marketplace remove <name> Remove a configured marketplace
  53. marketplace update [name] Refresh one marketplace, or all when omitted
  54. Scopes: user (default), project. \`zcode plugin\` is an alias of \`zcode plugins\`.`;
  55. export async function runPluginsCommand(
  56. ctx: RunContext,
  57. options: GlobalOptions,
  58. deps: PluginsCommandDependencies,
  59. args: string[],
  60. flags: PluginsCommandFlags = {},
  61. ): Promise<number> {
  62. const [subcommand = "list", ...rest] = args;
  63. try {
  64. switch (subcommand) {
  65. case "list":
  66. if (rest.length > 0) throw new PluginsUsageError();
  67. return await runPluginsListCommand(ctx, options, deps, flags);
  68. case "install":
  69. return await runPluginsInstallCommand(ctx, options, deps, flags, requireOne(rest));
  70. case "uninstall":
  71. return await runPluginsUninstallCommand(ctx, options, deps, flags, requireOne(rest));
  72. case "enable":
  73. return await runPluginsSetCommand(ctx, options, deps, flags, requireOne(rest), true);
  74. case "disable":
  75. return await runPluginsDisableCommand(ctx, options, deps, flags, rest);
  76. case "update":
  77. return await runPluginsUpdateCommand(ctx, options, deps, flags, requireOne(rest));
  78. case "validate":
  79. return await runPluginsValidateCommand(ctx, options, deps, requireOne(rest));
  80. case "marketplace":
  81. return await runMarketplaceCommand(ctx, options, deps, flags, rest);
  82. default:
  83. throw new PluginsUsageError(`Unknown plugins command: ${subcommand}`);
  84. }
  85. } catch (error) {
  86. if (error instanceof PluginsUsageError) {
  87. ctx.stderr.write(`${error.message ? `${error.message}\n` : ""}${PLUGINS_COMMAND_USAGE}\n`);
  88. return 1;
  89. }
  90. return reportPluginsError(ctx, options, error);
  91. }
  92. }
  93. async function runPluginsListCommand(
  94. ctx: RunContext,
  95. options: GlobalOptions,
  96. deps: PluginsCommandDependencies,
  97. flags: PluginsCommandFlags,
  98. ): Promise<number> {
  99. const base = baseOptions(deps);
  100. const outcome = (await resolveDep(deps, "listPlugins"))(base);
  101. const installed = outcome.plugins.map((plugin) => formatPluginJson(plugin, outcome.diagnostics));
  102. if (!flags.available) {
  103. ctx.stdout.write(
  104. options.json ? formatJson(installed) : formatHumanPluginList(outcome, options),
  105. );
  106. // 市场刷新失败这类诊断的 pluginId 是市场 id 或为空,归不到任何条目;error 级不能静默丢掉。
  107. const knownIds = new Set(outcome.plugins.map((plugin) => plugin.id));
  108. const orphaned = outcome.diagnostics.filter(
  109. (diagnostic) =>
  110. diagnostic.severity === "error" && !(diagnostic.pluginId && knownIds.has(diagnostic.pluginId)),
  111. );
  112. if (orphaned.length === 0) return 0;
  113. ctx.stderr.write(formatDiagnosticLines(orphaned));
  114. return 1;
  115. }
  116. const overview = (await resolveDep(deps, "getPluginsOverview"))(base);
  117. if (options.json) {
  118. ctx.stdout.write(
  119. formatJson({
  120. installed,
  121. available: overview.availablePlugins.map(formatAvailablePluginJson),
  122. diagnostics: [...outcome.diagnostics, ...overview.diagnostics].map(formatDiagnosticJson),
  123. }),
  124. );
  125. return 0;
  126. }
  127. ctx.stdout.write(
  128. `${formatHumanPluginList(outcome, options)}\n${formatHumanAvailableList(overview.availablePlugins)}`,
  129. );
  130. return 0;
  131. }
  132. async function runPluginsInstallCommand(
  133. ctx: RunContext,
  134. options: GlobalOptions,
  135. deps: PluginsCommandDependencies,
  136. flags: PluginsCommandFlags,
  137. identifier: string,
  138. ): Promise<number> {
  139. const scope = resolveScope(flags.scope) ?? "user";
  140. const base = baseOptions(deps);
  141. const { name } = splitPluginIdentifier(identifier);
  142. let { marketplace } = splitPluginIdentifier(identifier);
  143. if (!marketplace) {
  144. const overview = (await resolveDep(deps, "getPluginsOverview"))(base);
  145. const matches = overview.availablePlugins.filter((plugin) => plugin.name === name);
  146. if (matches.length > 1) throw ambiguousPluginError(matches.map((plugin) => plugin.id));
  147. if (matches.length === 0 || !matches[0]) {
  148. throw new Error(`Plugin not found in any marketplace: ${name}`);
  149. }
  150. marketplace = matches[0].marketplace;
  151. }
  152. const result = await (await resolveDep(deps, "installPlugin"))({
  153. ...base,
  154. marketplace,
  155. pluginName: name,
  156. scope,
  157. });
  158. return reportInstallOutcome(ctx, options, result, `${name}@${marketplace}`);
  159. }
  160. async function runPluginsUpdateCommand(
  161. ctx: RunContext,
  162. options: GlobalOptions,
  163. deps: PluginsCommandDependencies,
  164. flags: PluginsCommandFlags,
  165. identifier: string,
  166. ): Promise<number> {
  167. resolveScope(flags.scope);
  168. const pluginId = await resolveLoadedPluginId(deps, identifier);
  169. const result = await (await resolveDep(deps, "updatePlugin"))({
  170. ...baseOptions(deps),
  171. pluginId,
  172. });
  173. const current = result.installedPlugins.find((plugin) => plugin.id === pluginId);
  174. const failed = hasErrors(result.diagnostics);
  175. if (options.json) {
  176. ctx.stdout.write(
  177. formatJson({
  178. pluginId,
  179. ok: !failed,
  180. previousVersion: result.previousVersion,
  181. ...(current?.version ? { version: current.version } : {}),
  182. installed: result.installedPlugins.map(formatInstalledPluginJson),
  183. diagnostics: result.diagnostics.map(formatDiagnosticJson),
  184. }),
  185. );
  186. return failed ? 1 : 0;
  187. }
  188. if (failed) {
  189. ctx.stderr.write(
  190. `Failed to update plugin ${pluginId}\n${formatDiagnosticLines(result.diagnostics)}`,
  191. );
  192. return 1;
  193. }
  194. const version = current?.version ?? "";
  195. ctx.stdout.write(
  196. version && version === result.previousVersion
  197. ? `Plugin ${pluginId} is already up to date (${version}).\n`
  198. : `Updated plugin ${pluginId} from ${result.previousVersion || "unknown"} to ${version || "unknown"}. Restart zcode to apply.\n`,
  199. );
  200. writeWarnings(ctx, result.diagnostics);
  201. return 0;
  202. }
  203. function reportInstallOutcome(
  204. ctx: RunContext,
  205. options: GlobalOptions,
  206. result: ZCodePluginInstallData,
  207. pluginId: string,
  208. ): number {
  209. const failed = hasErrors(result.diagnostics);
  210. if (options.json) {
  211. ctx.stdout.write(
  212. formatJson({
  213. pluginId,
  214. ok: !failed,
  215. installed: result.installedPlugins.map(formatInstalledPluginJson),
  216. dependencyClosure: result.dependencyClosure,
  217. diagnostics: result.diagnostics.map(formatDiagnosticJson),
  218. }),
  219. );
  220. return failed ? 1 : 0;
  221. }
  222. if (failed) {
  223. ctx.stderr.write(
  224. `Failed to install plugin ${pluginId}\n${formatDiagnosticLines(result.diagnostics)}`,
  225. );
  226. return 1;
  227. }
  228. for (const plugin of result.installedPlugins) {
  229. const version = plugin.version ? ` (${plugin.version})` : "";
  230. ctx.stdout.write(
  231. `Installed plugin ${plugin.id}${version} [${plugin.enabled ? "enabled" : "disabled"}]\n`,
  232. );
  233. }
  234. writeWarnings(ctx, result.diagnostics);
  235. return 0;
  236. }
  237. async function runPluginsSetCommand(
  238. ctx: RunContext,
  239. options: GlobalOptions,
  240. deps: PluginsCommandDependencies,
  241. flags: PluginsCommandFlags,
  242. plugin: string,
  243. enabled: boolean,
  244. ): Promise<number> {
  245. const scope = resolveScope(flags.scope);
  246. const result = await (await resolveDep(deps, "setPluginEnabled"))({
  247. ...baseOptions(deps),
  248. enabled,
  249. plugin,
  250. ...(scope ? { scope } : {}),
  251. });
  252. ctx.stdout.write(options.json ? formatPluginSetJson(result) : formatHumanPluginSet(result));
  253. return 0;
  254. }
  255. async function runPluginsDisableCommand(
  256. ctx: RunContext,
  257. options: GlobalOptions,
  258. deps: PluginsCommandDependencies,
  259. flags: PluginsCommandFlags,
  260. rest: string[],
  261. ): Promise<number> {
  262. if (flags.all && rest.length > 0) {
  263. throw new PluginsUsageError("Cannot use --all with a specific plugin");
  264. }
  265. if (!flags.all) {
  266. if (rest.length === 0) {
  267. throw new PluginsUsageError(
  268. "Please specify a plugin name or use --all to disable all plugins",
  269. );
  270. }
  271. return await runPluginsSetCommand(ctx, options, deps, flags, requireOne(rest), false);
  272. }
  273. if (flags.scope !== undefined) throw new PluginsUsageError("Cannot use --scope with --all");
  274. const base = baseOptions(deps);
  275. const listPlugins = await resolveDep(deps, "listPlugins");
  276. const setPluginEnabled = await resolveDep(deps, "setPluginEnabled");
  277. const entries: Array<{ plugin: PluginListItem; result?: SetZCodePluginEnabledResult; error?: string }> = [];
  278. for (const plugin of listPlugins(base).plugins) {
  279. if (!plugin.enabled) continue;
  280. try {
  281. entries.push({ plugin, result: await setPluginEnabled({ ...base, enabled: false, plugin: plugin.id }) });
  282. } catch (error) {
  283. entries.push({ plugin, error: error instanceof Error ? error.message : String(error) });
  284. }
  285. }
  286. // 写的是 user 层;workspace/project 层的 enabledPlugins=true 优先级更高、盖不掉,所以按 effective 态复查。
  287. const stillEnabled = new Set(listPlugins(base).plugins.filter((p) => p.enabled).map((p) => p.id));
  288. const failed = entries.filter((entry) => entry.error || stillEnabled.has(entry.plugin.id));
  289. if (options.json) {
  290. ctx.stdout.write(
  291. formatJson(
  292. entries.map((entry) => ({
  293. enabled: entry.result?.enabled ?? entry.plugin.enabled,
  294. effectiveEnabled: stillEnabled.has(entry.plugin.id),
  295. path: entry.result?.path ?? null,
  296. plugin: formatPluginJson(entry.result?.plugin ?? entry.plugin, []),
  297. ...(entry.error ? { error: entry.error } : {}),
  298. })),
  299. ),
  300. );
  301. return failed.length > 0 ? 1 : 0;
  302. }
  303. if (entries.length === 0) {
  304. ctx.stdout.write("No enabled plugins.\n");
  305. return 0;
  306. }
  307. for (const entry of entries) {
  308. if (entry.result && !failed.includes(entry)) ctx.stdout.write(formatHumanPluginSet(entry.result));
  309. }
  310. for (const entry of failed) {
  311. ctx.stderr.write(
  312. entry.error
  313. ? `Failed to disable plugin ${entry.plugin.id}: ${entry.error}\n`
  314. : `Warning: plugin ${entry.plugin.id} is still enabled by a higher-priority config layer (project/workspace); disable it there with --scope project.\n`,
  315. );
  316. }
  317. return failed.length > 0 ? 1 : 0;
  318. }
  319. async function runPluginsUninstallCommand(
  320. ctx: RunContext,
  321. options: GlobalOptions,
  322. deps: PluginsCommandDependencies,
  323. flags: PluginsCommandFlags,
  324. identifier: string,
  325. ): Promise<number> {
  326. resolveScope(flags.scope);
  327. const target = await resolveLoadedPluginId(deps, identifier);
  328. // 卸载是破坏性的彻底清除:交互终端下询问确认;非交互(管道/CI)且未带 --force 时拒绝执行,不静默卸载。
  329. if (!options.force) {
  330. if (!ctx.stdin.isTTY) {
  331. ctx.stderr.write(
  332. `Refusing to uninstall ${target} without confirmation. Re-run with --force in a non-interactive shell.\n`,
  333. );
  334. return 1;
  335. }
  336. const confirmed = await confirmUninstall(ctx, target);
  337. if (!confirmed) {
  338. ctx.stdout.write(`Aborted. ${target} was not uninstalled.\n`);
  339. return 0;
  340. }
  341. }
  342. const removed = await (await resolveDep(deps, "uninstallPlugin"))({
  343. ...baseOptions(deps),
  344. pluginId: target,
  345. ...(flags.keepData ? { keepData: true } : {}),
  346. });
  347. ctx.stdout.write(
  348. options.json
  349. ? formatJson({
  350. pluginId: removed?.id ?? target,
  351. removed: removed !== null,
  352. ...(flags.keepData ? { keptData: true } : {}),
  353. ...(removed ? { plugin: formatInstalledPluginJson(removed) } : {}),
  354. })
  355. : formatHumanPluginUninstall(removed, target),
  356. );
  357. return removed ? 0 : 1;
  358. }
  359. async function runPluginsValidateCommand(
  360. ctx: RunContext,
  361. options: GlobalOptions,
  362. deps: PluginsCommandDependencies,
  363. path: string,
  364. ): Promise<number> {
  365. const diagnostics = await (await resolveDep(deps, "validatePluginPath"))({
  366. ...baseOptions(deps),
  367. path,
  368. });
  369. const failed = hasErrors(diagnostics);
  370. if (options.json) {
  371. ctx.stdout.write(
  372. formatJson({ path, ok: !failed, diagnostics: diagnostics.map(formatDiagnosticJson) }),
  373. );
  374. return failed ? 1 : 0;
  375. }
  376. if (failed) {
  377. ctx.stderr.write(`Plugin manifest is invalid: ${path}\n${formatDiagnosticLines(diagnostics)}`);
  378. return 1;
  379. }
  380. ctx.stdout.write(`Plugin manifest is valid: ${path}\n`);
  381. writeWarnings(ctx, diagnostics);
  382. return 0;
  383. }