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