posix.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. /**
  3. * This is the Posix implementation of isexe, which uses the file
  4. * mode and uid/gid values.
  5. *
  6. * @module
  7. */
  8. Object.defineProperty(exports, "__esModule", { value: true });
  9. exports.sync = exports.isexe = void 0;
  10. const fs_1 = require("fs");
  11. const promises_1 = require("fs/promises");
  12. /**
  13. * Determine whether a path is executable according to the mode and
  14. * current (or specified) user and group IDs.
  15. */
  16. const isexe = async (path, options = {}) => {
  17. const { ignoreErrors = false } = options;
  18. try {
  19. return checkStat(await (0, promises_1.stat)(path), options);
  20. }
  21. catch (e) {
  22. const er = e;
  23. if (ignoreErrors || er.code === 'EACCES')
  24. return false;
  25. throw er;
  26. }
  27. };
  28. exports.isexe = isexe;
  29. /**
  30. * Synchronously determine whether a path is executable according to
  31. * the mode and current (or specified) user and group IDs.
  32. */
  33. const sync = (path, options = {}) => {
  34. const { ignoreErrors = false } = options;
  35. try {
  36. return checkStat((0, fs_1.statSync)(path), options);
  37. }
  38. catch (e) {
  39. const er = e;
  40. if (ignoreErrors || er.code === 'EACCES')
  41. return false;
  42. throw er;
  43. }
  44. };
  45. exports.sync = sync;
  46. const checkStat = (stat, options) => stat.isFile() && checkMode(stat, options);
  47. const checkMode = (stat, options) => {
  48. const myUid = options.uid ?? process.getuid?.();
  49. const myGroups = options.groups ?? process.getgroups?.() ?? [];
  50. const myGid = options.gid ?? process.getgid?.() ?? myGroups[0];
  51. if (myUid === undefined || myGid === undefined) {
  52. throw new Error('cannot get uid or gid');
  53. }
  54. const groups = new Set([myGid, ...myGroups]);
  55. const mod = stat.mode;
  56. const uid = stat.uid;
  57. const gid = stat.gid;
  58. const u = parseInt('100', 8);
  59. const g = parseInt('010', 8);
  60. const o = parseInt('001', 8);
  61. const ug = u | g;
  62. return !!(mod & o ||
  63. (mod & g && groups.has(gid)) ||
  64. (mod & u && uid === myUid) ||
  65. (mod & ug && myUid === 0));
  66. };
  67. //# sourceMappingURL=posix.js.map