outputPath.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. const utils = require("../../utils/ast-utils");
  2. /**
  3. *
  4. * Transform which adds `path.join` call to `output.path` literals
  5. *
  6. * @param {Object} j - jscodeshift top-level import
  7. * @param {Node} ast - jscodeshift ast to transform
  8. * @returns {Node} ast - jscodeshift ast
  9. */
  10. module.exports = function(j, ast) {
  11. const literalOutputPath = ast
  12. .find(j.ObjectExpression)
  13. .filter(
  14. p =>
  15. utils.safeTraverse(p, ["parentPath", "value", "key", "name"]) ===
  16. "output"
  17. )
  18. .find(j.Property)
  19. .filter(
  20. p =>
  21. utils.safeTraverse(p, ["value", "key", "name"]) === "path" &&
  22. utils.safeTraverse(p, ["value", "value", "type"]) === "Literal"
  23. );
  24. if (literalOutputPath) {
  25. let pathVarName = "path";
  26. let isPathPresent = false;
  27. const pathDeclaration = ast
  28. .find(j.VariableDeclarator)
  29. .filter(
  30. p =>
  31. utils.safeTraverse(p, ["value", "init", "callee", "name"]) ===
  32. "require"
  33. )
  34. .filter(
  35. p =>
  36. utils.safeTraverse(p, ["value", "init", "arguments"]) &&
  37. p.value.init.arguments.reduce((isPresent, a) => {
  38. return (a.type === "Literal" && a.value === "path") || isPresent;
  39. }, false)
  40. );
  41. if (pathDeclaration) {
  42. isPathPresent = true;
  43. pathDeclaration.forEach(p => {
  44. pathVarName = utils.safeTraverse(p, ["value", "id", "name"]);
  45. });
  46. }
  47. const finalPathName = pathVarName;
  48. literalOutputPath
  49. .find(j.Literal)
  50. .replaceWith(p => replaceWithPath(j, p, finalPathName));
  51. if (!isPathPresent) {
  52. const pathRequire = utils.getRequire(j, "path", "path");
  53. return ast
  54. .find(j.Program)
  55. .replaceWith(p =>
  56. j.program([].concat(pathRequire).concat(p.value.body))
  57. );
  58. }
  59. }
  60. return ast;
  61. };
  62. function replaceWithPath(j, p, pathVarName) {
  63. const convertedPath = j.callExpression(
  64. j.memberExpression(j.identifier(pathVarName), j.identifier("join"), false),
  65. [j.identifier("__dirname"), p.value]
  66. );
  67. return convertedPath;
  68. }