xref: /expo/packages/@expo/cli/src/utils/editor.ts (revision dad749c2)
1import spawnAsync from '@expo/spawn-async';
2import editors from 'env-editor';
3
4import * as Log from '../log';
5
6/** Guess what the default editor is and default to VSCode. */
7export function guessEditor(): editors.Editor {
8  try {
9    return editors.defaultEditor();
10  } catch {
11    return editors.getEditor('vscode');
12  }
13}
14
15/** Open a file path in a given editor. */
16export async function openInEditorAsync(path: string): Promise<boolean> {
17  const editor = guessEditor();
18
19  Log.debug(`Opening ${path} in ${editor?.name} (bin: ${editor?.binary}, id: ${editor?.id})`);
20  if (editor) {
21    try {
22      await spawnAsync(editor.binary, [path]);
23      return true;
24    } catch (error: any) {
25      Log.debug(
26        `Failed to auto open path in editor (path: ${path}, binary: ${editor.binary}):`,
27        error
28      );
29    }
30  }
31
32  Log.error(
33    'Could not open editor, you can set it by defining the $EDITOR environment variable with the binary of your editor. (e.g. "vscode" or "atom")'
34  );
35  return false;
36}
37