123456789101112131415161718192021222324252627282930313233343536373839
  1. "use strict";
  2. const path = require("path");
  3. const looksLikeAbsolutePath = (maybeAbsolutePath) => {
  4. return /^(?:[a-z]:\\|\/)/i.test(maybeAbsolutePath);
  5. };
  6. const normalizePathSeparator = (p) => p.replace(/\\/g, "/");
  7. const _makePathsRelative = (context, identifier) => {
  8. return identifier
  9. .split(/([|! ])/)
  10. .map(str => looksLikeAbsolutePath(str) ?
  11. normalizePathSeparator(path.relative(context, str)) : str)
  12. .join("");
  13. };
  14. exports.makePathsRelative = (context, identifier, cache) => {
  15. if(!cache) return _makePathsRelative(context, identifier);
  16. const relativePaths = cache.relativePaths || (cache.relativePaths = new Map());
  17. let cachedResult;
  18. let contextCache = relativePaths.get(context);
  19. if(typeof contextCache === "undefined") {
  20. relativePaths.set(context, contextCache = new Map());
  21. } else {
  22. cachedResult = contextCache.get(identifier);
  23. }
  24. if(typeof cachedResult !== "undefined") {
  25. return cachedResult;
  26. } else {
  27. const relativePath = _makePathsRelative(context, identifier);
  28. contextCache.set(identifier, relativePath);
  29. return relativePath;
  30. }
  31. };