index.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. /**
  2. * Copyright (c) 2015-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file at
  6. * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE
  7. *
  8. * Modified by Yuxi Evan You
  9. */
  10. const fs = require('fs')
  11. const os = require('os')
  12. const path = require('path')
  13. const colors = require('picocolors')
  14. const childProcess = require('child_process')
  15. const guessEditor = require('./guess')
  16. const getArgumentsForPosition = require('./get-args')
  17. function wrapErrorCallback (cb) {
  18. return (fileName, errorMessage) => {
  19. console.log()
  20. console.log(
  21. colors.red('Could not open ' + path.basename(fileName) + ' in the editor.')
  22. )
  23. if (errorMessage) {
  24. if (errorMessage[errorMessage.length - 1] !== '.') {
  25. errorMessage += '.'
  26. }
  27. console.log(
  28. colors.red('The editor process exited with an error: ' + errorMessage)
  29. )
  30. }
  31. console.log()
  32. if (cb) cb(fileName, errorMessage)
  33. }
  34. }
  35. function isTerminalEditor (editor) {
  36. switch (editor) {
  37. case 'vim':
  38. case 'emacs':
  39. case 'nano':
  40. return true
  41. }
  42. return false
  43. }
  44. const positionRE = /:(\d+)(:(\d+))?$/
  45. function parseFile (file) {
  46. const fileName = file.replace(positionRE, '')
  47. const match = file.match(positionRE)
  48. const lineNumber = match && match[1]
  49. const columnNumber = match && match[3]
  50. return {
  51. fileName,
  52. lineNumber,
  53. columnNumber
  54. }
  55. }
  56. let _childProcess = null
  57. function launchEditor (file, specifiedEditor, onErrorCallback) {
  58. const parsed = parseFile(file)
  59. let { fileName } = parsed
  60. const { lineNumber, columnNumber } = parsed
  61. if (!fs.existsSync(fileName)) {
  62. return
  63. }
  64. if (typeof specifiedEditor === 'function') {
  65. onErrorCallback = specifiedEditor
  66. specifiedEditor = undefined
  67. }
  68. onErrorCallback = wrapErrorCallback(onErrorCallback)
  69. const [editor, ...args] = guessEditor(specifiedEditor)
  70. if (!editor) {
  71. onErrorCallback(fileName, null)
  72. return
  73. }
  74. if (
  75. process.platform === 'linux' &&
  76. fileName.startsWith('/mnt/') &&
  77. /Microsoft/i.test(os.release())
  78. ) {
  79. // Assume WSL / "Bash on Ubuntu on Windows" is being used, and
  80. // that the file exists on the Windows file system.
  81. // `os.release()` is "4.4.0-43-Microsoft" in the current release
  82. // build of WSL, see: https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364
  83. // When a Windows editor is specified, interop functionality can
  84. // handle the path translation, but only if a relative path is used.
  85. fileName = path.relative('', fileName)
  86. }
  87. if (lineNumber) {
  88. const extraArgs = getArgumentsForPosition(editor, fileName, lineNumber, columnNumber)
  89. args.push.apply(args, extraArgs)
  90. } else {
  91. args.push(fileName)
  92. }
  93. if (_childProcess && isTerminalEditor(editor)) {
  94. // There's an existing editor process already and it's attached
  95. // to the terminal, so go kill it. Otherwise two separate editor
  96. // instances attach to the stdin/stdout which gets confusing.
  97. _childProcess.kill('SIGKILL')
  98. }
  99. if (process.platform === 'win32') {
  100. // On Windows, we need to use `exec` with the `shell: true` option,
  101. // and some more sanitization is required.
  102. // However, CMD.exe on Windows is vulnerable to RCE attacks given a file name of the
  103. // form "C:\Users\myusername\Downloads\& curl 172.21.93.52".
  104. // `create-react-app` used a safe file name pattern to validate user-provided file names:
  105. // - https://github.com/facebook/create-react-app/pull/4866
  106. // - https://github.com/facebook/create-react-app/pull/5431
  107. // But that's not a viable solution for this package because
  108. // it's depended on by so many meta frameworks that heavily rely on
  109. // special characters in file names for filesystem-based routing.
  110. // We need to at least:
  111. // - Support `+` because it's used in SvelteKit and Vike
  112. // - Support `$` because it's used in Remix
  113. // - Support `(` and `)` because they are used in Analog, SolidStart, and Vike
  114. // - Support `@` because it's used in Vike
  115. // - Support `[` and `]` because they are widely used for [slug]
  116. // So here we choose to use `^` to escape special characters instead.
  117. // According to https://ss64.com/nt/syntax-esc.html,
  118. // we can use `^` to escape `&`, `<`, `>`, `|`, `%`, and `^`
  119. // I'm not sure if we have to escape all of these, but let's do it anyway
  120. function escapeCmdArgs (cmdArgs) {
  121. return cmdArgs.replace(/([&|<>,;=^])/g, '^$1')
  122. }
  123. // Need to double quote the editor path in case it contains spaces;
  124. // If the fileName contains spaces, we also need to double quote it in the arguments
  125. // However, there's a case that it's concatenated with line number and column number
  126. // which is separated by `:`. We need to double quote the whole string in this case.
  127. // Also, if the string contains the escape character `^`, it needs to be quoted, too.
  128. function doubleQuoteIfNeeded(str) {
  129. if (str.includes('^')) {
  130. // If a string includes an escaped character, not only does it need to be quoted,
  131. // but the quotes need to be escaped too.
  132. return `^"${str}^"`
  133. } else if (str.includes(' ')) {
  134. return `"${str}"`
  135. }
  136. return str
  137. }
  138. const launchCommand = [editor, ...args.map(escapeCmdArgs)]
  139. .map(doubleQuoteIfNeeded)
  140. .join(' ')
  141. _childProcess = childProcess.exec(launchCommand, {
  142. stdio: 'inherit',
  143. shell: true
  144. })
  145. } else {
  146. _childProcess = childProcess.spawn(editor, args, { stdio: 'inherit' })
  147. }
  148. _childProcess.on('exit', function (errorCode) {
  149. _childProcess = null
  150. if (errorCode) {
  151. onErrorCallback(fileName, '(code ' + errorCode + ')')
  152. }
  153. })
  154. _childProcess.on('error', function (error) {
  155. let { code, message } = error
  156. if ('ENOENT' === code) {
  157. message = `${message} ('${editor}' command does not exist in 'PATH')`
  158. }
  159. onErrorCallback(fileName, message);
  160. })
  161. }
  162. module.exports = launchEditor