osenv.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. var isWindows = process.platform === 'win32'
  2. var windir = isWindows ? process.env.windir || 'C:\\Windows' : null
  3. var path = require('path')
  4. var exec = require('child_process').exec
  5. // looking up envs is a bit costly.
  6. // Also, sometimes we want to have a fallback
  7. // Pass in a callback to wait for the fallback on failures
  8. // After the first lookup, always returns the same thing.
  9. function memo (key, lookup, fallback) {
  10. var fell = false
  11. var falling = false
  12. exports[key] = function (cb) {
  13. var val = lookup()
  14. if (!val && !fell && !falling && fallback) {
  15. fell = true
  16. falling = true
  17. exec(fallback, function (er, output, stderr) {
  18. falling = false
  19. if (er) return // oh well, we tried
  20. val = output.trim()
  21. })
  22. }
  23. exports[key] = function (cb) {
  24. if (cb) process.nextTick(cb.bind(null, null, val))
  25. return val
  26. }
  27. if (cb && !falling) process.nextTick(cb.bind(null, null, val))
  28. return val
  29. }
  30. }
  31. memo('user', function () {
  32. return ( isWindows
  33. ? process.env.USERDOMAIN + '\\' + process.env.USERNAME
  34. : process.env.USER
  35. )
  36. }, 'whoami')
  37. memo('prompt', function () {
  38. return isWindows ? process.env.PROMPT : process.env.PS1
  39. })
  40. memo('hostname', function () {
  41. return isWindows ? process.env.COMPUTERNAME : process.env.HOSTNAME
  42. }, 'hostname')
  43. memo('tmpdir', function () {
  44. var t = isWindows ? 'temp' : 'tmp'
  45. return process.env.TMPDIR ||
  46. process.env.TMP ||
  47. process.env.TEMP ||
  48. ( exports.home() ? path.resolve(exports.home(), t)
  49. : isWindows ? path.resolve(windir, t)
  50. : '/tmp'
  51. )
  52. })
  53. memo('home', function () {
  54. return ( isWindows ? process.env.USERPROFILE
  55. : process.env.HOME
  56. )
  57. })
  58. memo('path', function () {
  59. return (process.env.PATH ||
  60. process.env.Path ||
  61. process.env.path).split(isWindows ? ';' : ':')
  62. })
  63. memo('editor', function () {
  64. return process.env.EDITOR ||
  65. process.env.VISUAL ||
  66. (isWindows ? 'notepad.exe' : 'vi')
  67. })
  68. memo('shell', function () {
  69. return isWindows ? process.env.ComSpec || 'cmd'
  70. : process.env.SHELL || 'bash'
  71. })