index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. 'use strict';
  2. const execa = require('execa');
  3. const lcid = require('lcid');
  4. const mem = require('mem');
  5. const defaultOpts = {spawn: true};
  6. const defaultLocale = 'en_US';
  7. function getEnvLocale(env) {
  8. env = env || process.env;
  9. return env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE;
  10. }
  11. function parseLocale(x) {
  12. const env = x.split('\n').reduce((env, def) => {
  13. def = def.split('=');
  14. env[def[0]] = def[1].replace(/^"|"$/g, '');
  15. return env;
  16. }, {});
  17. return getEnvLocale(env);
  18. }
  19. function getLocale(str) {
  20. return (str && str.replace(/[.:].*/, ''));
  21. }
  22. function getAppleLocale() {
  23. return execa.stdout('defaults', ['read', '-g', 'AppleLocale']);
  24. }
  25. function getAppleLocaleSync() {
  26. return execa.sync('defaults', ['read', '-g', 'AppleLocale']).stdout;
  27. }
  28. function getUnixLocale() {
  29. if (process.platform === 'darwin') {
  30. return getAppleLocale();
  31. }
  32. return execa.stdout('locale')
  33. .then(stdout => getLocale(parseLocale(stdout)));
  34. }
  35. function getUnixLocaleSync() {
  36. if (process.platform === 'darwin') {
  37. return getAppleLocaleSync();
  38. }
  39. return getLocale(parseLocale(execa.sync('locale').stdout));
  40. }
  41. function getWinLocale() {
  42. return execa.stdout('wmic', ['os', 'get', 'locale'])
  43. .then(stdout => {
  44. const lcidCode = parseInt(stdout.replace('Locale', ''), 16);
  45. return lcid.from(lcidCode);
  46. });
  47. }
  48. function getWinLocaleSync() {
  49. const stdout = execa.sync('wmic', ['os', 'get', 'locale']).stdout;
  50. const lcidCode = parseInt(stdout.replace('Locale', ''), 16);
  51. return lcid.from(lcidCode);
  52. }
  53. module.exports = mem(opts => {
  54. opts = opts || defaultOpts;
  55. const envLocale = getEnvLocale();
  56. let thenable;
  57. if (envLocale || opts.spawn === false) {
  58. thenable = Promise.resolve(getLocale(envLocale));
  59. } else if (process.platform === 'win32') {
  60. thenable = getWinLocale();
  61. } else {
  62. thenable = getUnixLocale();
  63. }
  64. return thenable.then(locale => locale || defaultLocale)
  65. .catch(() => defaultLocale);
  66. });
  67. module.exports.sync = mem(opts => {
  68. opts = opts || defaultOpts;
  69. const envLocale = getEnvLocale();
  70. let res;
  71. if (envLocale || opts.spawn === false) {
  72. res = getLocale(envLocale);
  73. } else {
  74. try {
  75. if (process.platform === 'win32') {
  76. res = getWinLocaleSync();
  77. } else {
  78. res = getUnixLocaleSync();
  79. }
  80. } catch (err) {}
  81. }
  82. return res || defaultLocale;
  83. });