default-tmp.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // The default temporary folder location for use in the windows algorithm.
  2. // It's TEMPting to use dirname(path), since that's guaranteed to be on the
  3. // same device. However, this means that:
  4. // rimraf(path).then(() => rimraf(dirname(path)))
  5. // will often fail with EBUSY, because the parent dir contains
  6. // marked-for-deletion directory entries (which do not show up in readdir).
  7. // The approach here is to use os.tmpdir() if it's on the same drive letter,
  8. // or resolve(path, '\\temp') if it exists, or the root of the drive if not.
  9. // On Posix (not that you'd be likely to use the windows algorithm there),
  10. // it uses os.tmpdir() always.
  11. import { tmpdir } from 'os';
  12. import { parse, resolve } from 'path';
  13. import { promises, statSync } from './fs.js';
  14. import platform from './platform.js';
  15. const { stat } = promises;
  16. const isDirSync = (path) => {
  17. try {
  18. return statSync(path).isDirectory();
  19. }
  20. catch (er) {
  21. return false;
  22. }
  23. };
  24. const isDir = (path) => stat(path).then(st => st.isDirectory(), () => false);
  25. const win32DefaultTmp = async (path) => {
  26. const { root } = parse(path);
  27. const tmp = tmpdir();
  28. const { root: tmpRoot } = parse(tmp);
  29. if (root.toLowerCase() === tmpRoot.toLowerCase()) {
  30. return tmp;
  31. }
  32. const driveTmp = resolve(root, '/temp');
  33. if (await isDir(driveTmp)) {
  34. return driveTmp;
  35. }
  36. return root;
  37. };
  38. const win32DefaultTmpSync = (path) => {
  39. const { root } = parse(path);
  40. const tmp = tmpdir();
  41. const { root: tmpRoot } = parse(tmp);
  42. if (root.toLowerCase() === tmpRoot.toLowerCase()) {
  43. return tmp;
  44. }
  45. const driveTmp = resolve(root, '/temp');
  46. if (isDirSync(driveTmp)) {
  47. return driveTmp;
  48. }
  49. return root;
  50. };
  51. const posixDefaultTmp = async () => tmpdir();
  52. const posixDefaultTmpSync = () => tmpdir();
  53. export const defaultTmp = platform === 'win32' ? win32DefaultTmp : posixDefaultTmp;
  54. export const defaultTmpSync = platform === 'win32' ? win32DefaultTmpSync : posixDefaultTmpSync;
  55. //# sourceMappingURL=default-tmp.js.map