external-editor.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import { spawn } from 'node:child_process';
  2. import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
  3. import { tmpdir } from 'node:os';
  4. import { join } from 'node:path';
  5. export interface ResolveTuiExternalEditorCommandOptions {
  6. readonly configuredCommand?: string;
  7. readonly env?: NodeJS.ProcessEnv;
  8. readonly platform?: NodeJS.Platform;
  9. }
  10. export interface ParsedTuiExternalEditorCommand {
  11. readonly executable: string;
  12. readonly args: readonly string[];
  13. }
  14. export interface TuiExternalEditorProcessInvocation {
  15. readonly executable: string;
  16. readonly args: readonly string[];
  17. readonly cwd: string;
  18. readonly shell: boolean;
  19. }
  20. export interface TuiExternalEditorProcessResult {
  21. readonly exitCode: number | null;
  22. readonly signal: NodeJS.Signals | null;
  23. }
  24. export type TuiExternalEditorProcessRunner = (
  25. invocation: TuiExternalEditorProcessInvocation,
  26. ) => Promise<TuiExternalEditorProcessResult>;
  27. export interface EditTuiDraftInExternalEditorOptions {
  28. readonly command: string;
  29. readonly draft: string;
  30. readonly cwd: string;
  31. readonly platform?: NodeJS.Platform;
  32. readonly runProcess?: TuiExternalEditorProcessRunner;
  33. }
  34. export type EditTuiDraftInExternalEditor = (
  35. options: EditTuiDraftInExternalEditorOptions,
  36. ) => Promise<string>;
  37. export function resolveTuiExternalEditorCommand(
  38. options: ResolveTuiExternalEditorCommandOptions = {},
  39. ): string | undefined {
  40. const env = options.env ?? process.env;
  41. const configured = [options.configuredCommand, env.MCODE_EDITOR, env.VISUAL, env.EDITOR].find(
  42. (value) => value?.trim(),
  43. );
  44. if (configured) return configured.trim();
  45. return (options.platform ?? process.platform) === 'win32' ? 'notepad' : undefined;
  46. }
  47. export function parseTuiExternalEditorCommand(command: string): ParsedTuiExternalEditorCommand {
  48. const tokens: string[] = [];
  49. let current = '';
  50. let quote: "'" | '"' | undefined;
  51. let tokenStarted = false;
  52. for (let index = 0; index < command.length; index += 1) {
  53. const character = command[index] ?? '';
  54. if (quote) {
  55. if (character === quote) {
  56. quote = undefined;
  57. tokenStarted = true;
  58. continue;
  59. }
  60. if (character === '\\' && quote === '"') {
  61. const next = command[index + 1];
  62. if (next === '"' || next === '\\') {
  63. current += next;
  64. index += 1;
  65. tokenStarted = true;
  66. continue;
  67. }
  68. }
  69. current += character;
  70. tokenStarted = true;
  71. continue;
  72. }
  73. if (character === "'" || character === '"') {
  74. quote = character;
  75. tokenStarted = true;
  76. continue;
  77. }
  78. if (/\s/u.test(character)) {
  79. if (tokenStarted) {
  80. tokens.push(current);
  81. current = '';
  82. tokenStarted = false;
  83. }
  84. continue;
  85. }
  86. if (character === '\\') {
  87. const next = command[index + 1];
  88. if (next && (/\s/u.test(next) || next === "'" || next === '"' || next === '\\')) {
  89. current += next;
  90. index += 1;
  91. tokenStarted = true;
  92. continue;
  93. }
  94. }
  95. current += character;
  96. tokenStarted = true;
  97. }
  98. if (quote) throw new Error('External editor command has an unmatched quote.');
  99. if (tokenStarted) tokens.push(current);
  100. const [executable, ...args] = tokens;
  101. if (!executable) throw new Error('External editor command is empty.');
  102. return { executable, args };
  103. }
  104. export async function editTuiDraftInExternalEditor(
  105. options: EditTuiDraftInExternalEditorOptions,
  106. ): Promise<string> {
  107. const parsed = parseTuiExternalEditorCommand(options.command);
  108. const directory = await mkdtemp(join(tmpdir(), 'mcode-editor-'));
  109. const draftPath = join(directory, 'prompt.md');
  110. try {
  111. await writeFile(draftPath, normalizeLineEndings(options.draft), {
  112. encoding: 'utf8',
  113. mode: 0o600,
  114. });
  115. const result = await (options.runProcess ?? runExternalEditorProcess)({
  116. executable: parsed.executable,
  117. args: [...parsed.args, draftPath],
  118. cwd: options.cwd,
  119. shell: (options.platform ?? process.platform) === 'win32',
  120. });
  121. assertExternalEditorSucceeded(result);
  122. return normalizeLineEndings(await readFile(draftPath, 'utf8'));
  123. } finally {
  124. await rm(directory, { recursive: true, force: true });
  125. }
  126. }
  127. function runExternalEditorProcess(
  128. invocation: TuiExternalEditorProcessInvocation,
  129. ): Promise<TuiExternalEditorProcessResult> {
  130. return new Promise((resolve, reject) => {
  131. const child = spawn(invocation.executable, invocation.args, {
  132. cwd: invocation.cwd,
  133. stdio: 'inherit',
  134. // Match Pi's Windows path: an async shell child lets libuv release its
  135. // console read before the TUI re-enables raw input after the editor exits.
  136. shell: invocation.shell,
  137. });
  138. child.once('error', reject);
  139. child.once('close', (exitCode, signal) => resolve({ exitCode, signal }));
  140. });
  141. }
  142. function assertExternalEditorSucceeded(result: TuiExternalEditorProcessResult): void {
  143. if (result.exitCode === 0) return;
  144. if (result.signal) throw new Error(`External editor exited after signal ${result.signal}`);
  145. throw new Error(`External editor exited with code ${String(result.exitCode)}`);
  146. }
  147. function normalizeLineEndings(value: string): string {
  148. return value.replace(/^\uFEFF/u, '').replace(/\r\n?/gu, '\n');
  149. }