environment.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. 'use strict';
  5. module.metadata = {
  6. "stability": "stable"
  7. };
  8. const { Cc, Ci } = require('chrome');
  9. const { get, set, exists } = Cc['@mozilla.org/process/environment;1'].
  10. getService(Ci.nsIEnvironment);
  11. exports.env = Proxy.create({
  12. // XPCOM does not provides a way to enumerate environment variables, so we
  13. // just don't support enumeration.
  14. getPropertyNames: function() [],
  15. getOwnPropertyNames: function() [],
  16. enumerate: function() [],
  17. keys: function() [],
  18. // We do not support freezing, cause it would make it impossible to set new
  19. // environment variables.
  20. fix: function() undefined,
  21. // We present all environment variables as own properties of this object,
  22. // so we just delegate this call to `getOwnPropertyDescriptor`.
  23. getPropertyDescriptor: function(name) this.getOwnPropertyDescriptor(name),
  24. // If environment variable with this name is defined, we generate proprety
  25. // descriptor for it, otherwise fall back to `undefined` so that for consumer
  26. // this property does not exists.
  27. getOwnPropertyDescriptor: function(name) {
  28. return !exists(name) ? undefined : {
  29. value: get(name),
  30. enumerable: false, // Non-enumerable as we don't support enumeration.
  31. configurable: true, // Configurable as it may be deleted.
  32. writable: true // Writable as we do support set.
  33. }
  34. },
  35. // New environment variables can be defined just by defining properties
  36. // on this object.
  37. defineProperty: function(name, { value }) set(name, value),
  38. delete: function(name) {
  39. set(name, null);
  40. return true;
  41. },
  42. // We present all properties as own, there for we just delegate to `hasOwn`.
  43. has: function(name) this.hasOwn(name),
  44. // We do support checks for existence of an environment variable, via `in`
  45. // operator on this object.
  46. hasOwn: function(name) exists(name),
  47. // On property get / set we do read / write appropriate environment variables,
  48. // please note though, that variables with names of standard object properties
  49. // intentionally (so that this behaves as normal object) can not be
  50. // read / set.
  51. get: function(proxy, name) Object.prototype[name] || get(name) || undefined,
  52. set: function(proxy, name, value) Object.prototype[name] || set(name, value)
  53. });