You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.4 KiB

4 years ago
  1. 'use strict';
  2. var path = require('path'),
  3. fs = require('fs');
  4. var getContextDirectory = require('./utility/get-context-directory'),
  5. enhancedRelative = require('./utility/enhanced-relative');
  6. /**
  7. * Codec for relative paths with respect to the context directory.
  8. * @type {{name:string, decode: function, encode: function, root: function}}
  9. */
  10. module.exports = {
  11. name : 'project-relative',
  12. decode: decode,
  13. encode: encode,
  14. root : getContextDirectory
  15. };
  16. /**
  17. * Decode the given uri.
  18. * Any path with or without leading slash is tested against context directory.
  19. * @this {{options: object}} A loader or compilation
  20. * @param {string} uri A source uri to decode
  21. * @returns {boolean|string} False where unmatched else the decoded path
  22. */
  23. function decode(uri) {
  24. /* jshint validthis:true */
  25. var base = getContextDirectory.call(this),
  26. absFile = path.normalize(path.join(base, uri)),
  27. isValid = !!absFile && fs.existsSync(absFile) && fs.statSync(absFile).isFile();
  28. return isValid && absFile;
  29. }
  30. /**
  31. * Encode the given file path.
  32. * @this {{options: object}} A loader or compilation
  33. * @param {string} absolute An absolute file path to encode
  34. * @returns {string} A uri
  35. */
  36. function encode(absolute) {
  37. /* jshint validthis:true */
  38. var base = getContextDirectory.call(this);
  39. if (!base) {
  40. throw new Error('Cannot locate the Webpack project directory');
  41. }
  42. else {
  43. return '/' + enhancedRelative(base, absolute);
  44. }
  45. }