launchEditor.js 9.45 KB
Newer Older
1
2
3
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
Sophie Alpert's avatar
Sophie Alpert committed
4
5
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
6
7
8
 */
'use strict';

9
10
11
12
13
14
const fs = require('fs');
const path = require('path');
const child_process = require('child_process');
const os = require('os');
const chalk = require('chalk');
const shellQuote = require('shell-quote');
15
16
17
18
19
20
21
22
23
24
25
26
27
28

function isTerminalEditor(editor) {
  switch (editor) {
    case 'vim':
    case 'emacs':
    case 'nano':
      return true;
  }
  return false;
}

// Map from full process name to binary that starts the process
// We can't just re-use full process name, because it will spawn a new instance
// of the app every time
29
const COMMON_EDITORS_OSX = {
30
  '/Applications/Atom.app/Contents/MacOS/Atom': 'atom',
31
32
  '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta':
    '/Applications/Atom Beta.app/Contents/MacOS/Atom Beta',
33
  '/Applications/Brackets.app/Contents/MacOS/Brackets': 'brackets',
34
35
36
37
  '/Applications/Sublime Text.app/Contents/MacOS/Sublime Text':
    '/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl',
  '/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2':
    '/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl',
38
  '/Applications/Visual Studio Code.app/Contents/MacOS/Electron': 'code',
39
40
41
42
43
  '/Applications/AppCode.app/Contents/MacOS/appcode':
    '/Applications/AppCode.app/Contents/MacOS/appcode',
  '/Applications/CLion.app/Contents/MacOS/clion':
    '/Applications/CLion.app/Contents/MacOS/clion',
  '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea':
44
    '/Applications/IntelliJ IDEA.app/Contents/MacOS/idea',
45
46
47
48
49
50
51
52
53
  '/Applications/PhpStorm.app/Contents/MacOS/phpstorm':
    '/Applications/PhpStorm.app/Contents/MacOS/phpstorm',
  '/Applications/PyCharm.app/Contents/MacOS/pycharm':
    '/Applications/PyCharm.app/Contents/MacOS/pycharm',
  '/Applications/PyCharm CE.app/Contents/MacOS/pycharm':
    '/Applications/PyCharm CE.app/Contents/MacOS/pycharm',
  '/Applications/RubyMine.app/Contents/MacOS/rubymine':
    '/Applications/RubyMine.app/Contents/MacOS/rubymine',
  '/Applications/WebStorm.app/Contents/MacOS/webstorm':
54
    '/Applications/WebStorm.app/Contents/MacOS/webstorm',
55
56
  '/Applications/MacVim.app/Contents/MacOS/MacVim':
    'mvim',
57
58
};

59
60
61
62
63
64
65
66
67
68
69
70
71
72
const COMMON_EDITORS_LINUX = {
  atom: 'atom',
  Brackets: 'brackets',
  code: 'code',
  emacs: 'emacs',
  'idea.sh': 'idea',
  'phpstorm.sh': 'phpstorm',
  'pycharm.sh': 'pycharm',
  'rubymine.sh': 'rubymine',
  sublime_text: 'sublime_text',
  vim: 'vim',
  'webstorm.sh': 'webstorm',
};

73
const COMMON_EDITORS_WIN = [
74
  'Brackets.exe',
75
76
77
78
  'Code.exe',
  'atom.exe',
  'sublime_text.exe',
  'notepad++.exe',
79
80
81
82
83
84
85
86
87
88
89
90
  'clion.exe',
  'clion64.exe',
  'idea.exe',
  'idea64.exe',
  'phpstorm.exe',
  'phpstorm64.exe',
  'pycharm.exe',
  'pycharm64.exe',
  'rubymine.exe',
  'rubymine64.exe',
  'webstorm.exe',
  'webstorm64.exe',
91
92
];

93
94
95
96
97
98
99
100
function addWorkspaceToArgumentsIfExists(args, workspace) {
  if (workspace) {
    args.unshift(workspace);
  }
  return args;
}

function getArgumentsForLineNumber(editor, fileName, lineNumber, workspace) {
101
  const editorBasename = path.basename(editor).replace(/\.(exe|cmd|bat)$/i, '');
102
  switch (editorBasename) {
103
104
105
106
107
    case 'atom':
    case 'Atom':
    case 'Atom Beta':
    case 'subl':
    case 'sublime':
108
    case 'sublime_text':
109
110
111
    case 'wstorm':
    case 'charm':
      return [fileName + ':' + lineNumber];
112
113
    case 'notepad++':
      return ['-n' + lineNumber, fileName];
114
115
    case 'vim':
    case 'mvim':
116
117
118
119
120
121
122
123
124
    case 'joe':
    case 'emacs':
    case 'emacsclient':
      return ['+' + lineNumber, fileName];
    case 'rmate':
    case 'mate':
    case 'mine':
      return ['--line', lineNumber, fileName];
    case 'code':
125
    case 'Code':
126
127
128
129
      return addWorkspaceToArgumentsIfExists(
        ['-g', fileName + ':' + lineNumber],
        workspace
      );
130
131
132
133
134
    case 'appcode':
    case 'clion':
    case 'clion64':
    case 'idea':
    case 'idea64':
135
136
    case 'phpstorm':
    case 'phpstorm64':
137
138
    case 'pycharm':
    case 'pycharm64':
139
140
141
142
    case 'rubymine':
    case 'rubymine64':
    case 'webstorm':
    case 'webstorm64':
143
144
145
146
      return addWorkspaceToArgumentsIfExists(
        ['--line', lineNumber, fileName],
        workspace
      );
147
148
149
150
151
152
153
154
155
156
157
158
159
160
  }

  // For all others, drop the lineNumber until we have
  // a mapping above, since providing the lineNumber incorrectly
  // can result in errors or confusing behavior.
  return [fileName];
}

function guessEditor() {
  // Explicit config always wins
  if (process.env.REACT_EDITOR) {
    return shellQuote.parse(process.env.REACT_EDITOR);
  }

161
162
163
  // We can find out which editor is currently running by:
  // `ps x` on macOS and Linux
  // `Get-Process` on Windows
164
165
166
167
168
169
  try {
    if (process.platform === 'darwin') {
      const output = child_process.execSync('ps x').toString();
      const processNames = Object.keys(COMMON_EDITORS_OSX);
      for (let i = 0; i < processNames.length; i++) {
        const processName = processNames[i];
170
        if (output.indexOf(processName) !== -1) {
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
          return [COMMON_EDITORS_OSX[processName]];
        }
      }
    } else if (process.platform === 'win32') {
      const output = child_process
        .execSync('powershell -Command "Get-Process | Select-Object Path"', {
          stdio: ['pipe', 'pipe', 'ignore'],
        })
        .toString();
      const runningProcesses = output.split('\r\n');
      for (let i = 0; i < runningProcesses.length; i++) {
        // `Get-Process` sometimes returns empty lines
        if (!runningProcesses[i]) {
          continue;
        }

        const fullProcessPath = runningProcesses[i].trim();
        const shortProcessName = path.basename(fullProcessPath);

        if (COMMON_EDITORS_WIN.indexOf(shortProcessName) !== -1) {
          return [fullProcessPath];
192
193
        }
      }
194
195
196
197
198
199
200
201
202
203
204
205
206
207
    } else if (process.platform === 'linux') {
      // --no-heading No header line
      // x List all processes owned by you
      // -o comm Need only names column
      const output = child_process
        .execSync('ps x --no-heading -o comm --sort=comm')
        .toString();
      const processNames = Object.keys(COMMON_EDITORS_LINUX);
      for (let i = 0; i < processNames.length; i++) {
        const processName = processNames[i];
        if (output.indexOf(processName) !== -1) {
          return [COMMON_EDITORS_LINUX[processName]];
        }
      }
208
    }
209
210
  } catch (error) {
    // Ignore...
211
212
213
214
215
216
217
218
219
220
221
222
  }

  // Last resort, use old skool env vars
  if (process.env.VISUAL) {
    return [process.env.VISUAL];
  } else if (process.env.EDITOR) {
    return [process.env.EDITOR];
  }

  return [null];
}

223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
function printInstructions(fileName, errorMessage) {
  console.log();
  console.log(
    chalk.red('Could not open ' + path.basename(fileName) + ' in the editor.')
  );
  if (errorMessage) {
    if (errorMessage[errorMessage.length - 1] !== '.') {
      errorMessage += '.';
    }
    console.log(
      chalk.red('The editor process exited with an error: ' + errorMessage)
    );
  }
  console.log();
  console.log(
    'To set up the editor integration, add something like ' +
      chalk.cyan('REACT_EDITOR=atom') +
      ' to the ' +
      chalk.green('.env.local') +
      ' file in your project folder ' +
243
244
      'and restart the development server. Learn more: ' +
      chalk.green('https://goo.gl/MMTaZt')
245
246
247
248
  );
  console.log();
}

249
let _childProcess = null;
250
251
252
253
254
255
256
257
258
259
260
261
function launchEditor(fileName, lineNumber) {
  if (!fs.existsSync(fileName)) {
    return;
  }

  // Sanitize lineNumber to prevent malicious use on win32
  // via: https://github.com/nodejs/node/blob/c3bb4b1aa5e907d489619fb43d233c3336bfc03d/lib/child_process.js#L333
  if (lineNumber && isNaN(lineNumber)) {
    return;
  }

  let [editor, ...args] = guessEditor();
262

263
  if (!editor) {
264
    printInstructions(fileName, null);
265
266
267
    return;
  }

268
269
270
271
  if (editor.toLowerCase() === 'none') {
    return;
  }

272
273
274
275
276
277
278
279
280
281
282
283
284
285
  if (
    process.platform === 'linux' &&
    fileName.startsWith('/mnt/') &&
    /Microsoft/i.test(os.release())
  ) {
    // Assume WSL / "Bash on Ubuntu on Windows" is being used, and
    // that the file exists on the Windows file system.
    // `os.release()` is "4.4.0-43-Microsoft" in the current release
    // build of WSL, see: https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364
    // When a Windows editor is specified, interop functionality can
    // handle the path translation, but only if a relative path is used.
    fileName = path.relative('', fileName);
  }

286
  let workspace = null;
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
  if (lineNumber) {
    args = args.concat(
      getArgumentsForLineNumber(editor, fileName, lineNumber, workspace)
    );
  } else {
    args.push(fileName);
  }

  if (_childProcess && isTerminalEditor(editor)) {
    // There's an existing editor process already and it's attached
    // to the terminal, so go kill it. Otherwise two separate editor
    // instances attach to the stdin/stdout which gets confusing.
    _childProcess.kill('SIGKILL');
  }

  if (process.platform === 'win32') {
    // On Windows, launch the editor in a shell because spawn can only
    // launch .exe files.
    _childProcess = child_process.spawn(
      'cmd.exe',
      ['/C', editor].concat(args),
      { stdio: 'inherit' }
    );
  } else {
    _childProcess = child_process.spawn(editor, args, { stdio: 'inherit' });
  }
313
  _childProcess.on('exit', function(errorCode) {
314
    _childProcess = null;
315
316
317
318
319
320
321
322

    if (errorCode) {
      printInstructions(fileName, '(code ' + errorCode + ')');
    }
  });

  _childProcess.on('error', function(error) {
    printInstructions(fileName, error.message);
323
324
325
326
  });
}

module.exports = launchEditor;