Created
September 30, 2016 13:20
-
-
Save SevInf/007cbce5c5ad6898dc28c279998445ac to your computer and use it in GitHub Desktop.
Codemod to migrate from Q to Bluebird
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const replacements = { | |
'thenResolve': 'thenReturn', | |
'thenReject': 'thenThrow', | |
'fcall': 'try' | |
} | |
export default function transformer(file, api) { | |
const j = api.jscodeshift; | |
const sourceCalls = []; | |
const f = j(file.source); | |
function replaceMethod(path) { | |
const {callee, arguments: args} = path.node; | |
const {object, property} = callee; | |
const replacement = replacements[property.name]; | |
j(path).replaceWith( | |
j.callExpression(j.memberExpression( | |
object, | |
j.identifier(replacement) | |
), args) | |
) | |
} | |
function replaceQCall(path) { | |
const {arguments: args} = path.node; | |
j(path).replaceWith( | |
j.callExpression( | |
j.memberExpression(j.identifier('Promise'), j.identifier('resolve')), | |
args | |
) | |
) | |
} | |
function replaceQ(path) { | |
j(path).replaceWith(j.identifier('Promise')) | |
} | |
function isRequireQ(node) { | |
return node.callee.name === 'require' && | |
node.arguments.length === 1 && | |
node.arguments[0].value === 'q'; | |
} | |
function replaceRequire(path) { | |
j(path).replaceWith( | |
j.callExpression( | |
path.node.callee, | |
[j.literal('bluebird')] | |
) | |
) | |
} | |
f.find(j.CallExpression, node => { | |
return node.callee.type === 'MemberExpression' && | |
replacements.hasOwnProperty(node.callee.property.name) | |
}) | |
.forEach(replaceMethod); | |
f.find(j.CallExpression, { callee: { name: 'q' }}) | |
.forEach(replaceQCall); | |
f.find(j.Identifier, { name: 'q'} ) | |
.forEach(replaceQ); | |
f.find(j.CallExpression, isRequireQ) | |
.forEach(replaceRequire) | |
return f.toSource({quote: 'single'}) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment