cwd.js 1012 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. import {statSync} from 'node:fs';
  2. import path from 'node:path';
  3. import process from 'node:process';
  4. import {safeNormalizeFileUrl} from './file-url.js';
  5. // Normalize `cwd` option
  6. export const normalizeCwd = (cwd = getDefaultCwd()) => {
  7. const cwdString = safeNormalizeFileUrl(cwd, 'The "cwd" option');
  8. return path.resolve(cwdString);
  9. };
  10. const getDefaultCwd = () => {
  11. try {
  12. return process.cwd();
  13. } catch (error) {
  14. error.message = `The current directory does not exist.\n${error.message}`;
  15. throw error;
  16. }
  17. };
  18. // When `cwd` option has an invalid value, provide with a better error message
  19. export const fixCwdError = (originalMessage, cwd) => {
  20. if (cwd === getDefaultCwd()) {
  21. return originalMessage;
  22. }
  23. let cwdStat;
  24. try {
  25. cwdStat = statSync(cwd);
  26. } catch (error) {
  27. return `The "cwd" option is invalid: ${cwd}.\n${error.message}\n${originalMessage}`;
  28. }
  29. if (!cwdStat.isDirectory()) {
  30. return `The "cwd" option is not a directory: ${cwd}.\n${originalMessage}`;
  31. }
  32. return originalMessage;
  33. };