|
| 1 | +import jscodeshift from 'jscodeshift'; |
| 2 | +import { |
| 3 | + DEFAULT_IMPORT, |
| 4 | + getImportIdentifierMap, |
| 5 | + removeImport, |
| 6 | +} from '../shared.js'; |
| 7 | + |
| 8 | +/** |
| 9 | + * @typedef {import('../../types.js').Codemod} Codemod |
| 10 | + * @typedef {import('../../types.js').CodemodOptions} CodemodOptions |
| 11 | + */ |
| 12 | + |
| 13 | +/** |
| 14 | + * @param {CodemodOptions} [options] |
| 15 | + * @returns {Codemod} |
| 16 | + */ |
| 17 | +export default function (options) { |
| 18 | + return { |
| 19 | + name: 'buffer-equal', |
| 20 | + transform: ({ file }) => { |
| 21 | + const j = jscodeshift; |
| 22 | + const root = j(file.source); |
| 23 | + let transformCount = 0; |
| 24 | + let dirtyFlag = false; |
| 25 | + |
| 26 | + const map = getImportIdentifierMap('buffer-equal', root, j); |
| 27 | + |
| 28 | + const identifier = map[DEFAULT_IMPORT]; |
| 29 | + |
| 30 | + const callExpressions = root.find(j.CallExpression, { |
| 31 | + callee: { |
| 32 | + name: identifier, |
| 33 | + }, |
| 34 | + }); |
| 35 | + |
| 36 | + if (!callExpressions.length) { |
| 37 | + removeImport('buffer-equal', root, j); |
| 38 | + return root.toSource(options); |
| 39 | + } |
| 40 | + |
| 41 | + callExpressions.forEach((p) => { |
| 42 | + const args = p.node.arguments; |
| 43 | + if (args.length === 2 && args[0].type !== 'SpreadElement') { |
| 44 | + const [firstArg, secondArg] = args; |
| 45 | + j(p).replaceWith( |
| 46 | + j.callExpression( |
| 47 | + j.memberExpression(firstArg, j.identifier('equals')), |
| 48 | + [secondArg], |
| 49 | + ), |
| 50 | + ); |
| 51 | + dirtyFlag = true; |
| 52 | + transformCount++; |
| 53 | + } |
| 54 | + }); |
| 55 | + |
| 56 | + if (transformCount === callExpressions.length) { |
| 57 | + removeImport('buffer-equal', root, j); |
| 58 | + } |
| 59 | + |
| 60 | + return dirtyFlag ? root.toSource(options) : file.source; |
| 61 | + }, |
| 62 | + }; |
| 63 | +} |
0 commit comments