command.js 1.4 KB

1234567891011121314151617181920212223242526272829303132
  1. const path = require('path')
  2. const isWindows = require('./is-windows')
  3. module.exports = commandConvert
  4. /**
  5. * Converts an environment variable usage to be appropriate for the current OS
  6. * @param {String} command Command to convert
  7. * @param {Object} env Map of the current environment variable names and their values
  8. * @param {boolean} normalize If the command should be normalized using `path`
  9. * after converting
  10. * @returns {String} Converted command
  11. */
  12. function commandConvert(command, env, normalize = false) {
  13. if (!isWindows()) {
  14. return command
  15. }
  16. const envUnixRegex = /\$(\w+)|\${(\w+)}/g // $my_var or ${my_var}
  17. const convertedCmd = command.replace(envUnixRegex, (match, $1, $2) => {
  18. const varName = $1 || $2
  19. // In Windows, non-existent variables are not replaced by the shell,
  20. // so for example "echo %FOO%" will literally print the string "%FOO%", as
  21. // opposed to printing an empty string in UNIX. See kentcdodds/cross-env#145
  22. // If the env variable isn't defined at runtime, just strip it from the command entirely
  23. return env[varName] ? `%${varName}%` : ''
  24. })
  25. // Normalization is required for commands with relative paths
  26. // For example, `./cmd.bat`. See kentcdodds/cross-env#127
  27. // However, it should not be done for command arguments.
  28. // See https://github.com/kentcdodds/cross-env/pull/130#issuecomment-319887970
  29. return normalize === true ? path.normalize(convertedCmd) : convertedCmd
  30. }