osenv.js 1.8 KB

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