|
| 1 | +const utils = require('../utils'); |
| 2 | + |
| 3 | +module.exports = function(j, ast) { |
| 4 | + const literalOutputPath = ast |
| 5 | + .find(j.ObjectExpression) |
| 6 | + .filter(p => utils.safeTraverse(p, ['parentPath', 'value', 'key', 'name']) === 'output') |
| 7 | + .find(j.Property) |
| 8 | + .filter(p => utils.safeTraverse(p, ['value', 'key', 'name']) === 'path' |
| 9 | + && utils.safeTraverse(p, ['value', 'value', 'type']) === 'Literal'); |
| 10 | + |
| 11 | + if (literalOutputPath) { |
| 12 | + let pathVarName = 'path'; |
| 13 | + let isPathPresent = false; |
| 14 | + const pathDecalaration = ast |
| 15 | + .find(j.VariableDeclarator) |
| 16 | + .filter(p => utils.safeTraverse(p, ['value', 'init', 'callee', 'name']) === 'require') |
| 17 | + .filter(p => utils.safeTraverse(p, ['value', 'init', 'arguments']) |
| 18 | + && p.value.init.arguments.reduce((isPresent, a) => { |
| 19 | + return a.type === 'Literal' && a.value === 'path' || isPresent; |
| 20 | + }, false)); |
| 21 | + |
| 22 | + if (pathDecalaration) { |
| 23 | + isPathPresent = true; |
| 24 | + pathDecalaration.forEach(p => { |
| 25 | + pathVarName = utils.safeTraverse(p, ['value', 'id', 'name']); |
| 26 | + }); |
| 27 | + } |
| 28 | + |
| 29 | + literalOutputPath |
| 30 | + .find(j.Literal) |
| 31 | + .replaceWith(p => replaceWithPath(j, p, pathVarName)); |
| 32 | + |
| 33 | + if(!isPathPresent){ |
| 34 | + const pathRequire = utils.getRequire(j, 'path', 'path'); |
| 35 | + return ast.find(j.Program) |
| 36 | + .replaceWith(p => j.program([].concat(pathRequire).concat(p.value.body))); |
| 37 | + } |
| 38 | + } |
| 39 | + return ast; |
| 40 | +}; |
| 41 | + |
| 42 | +function replaceWithPath(j, p, pathVarName) { |
| 43 | + const convertedPath = j.callExpression( |
| 44 | + j.memberExpression( |
| 45 | + j.identifier(pathVarName), |
| 46 | + j.identifier('join'), |
| 47 | + false), |
| 48 | + [j.identifier('__dirname'), p.value]); |
| 49 | + return convertedPath; |
| 50 | +} |
| 51 | + |
0 commit comments