Skip to content

Instantly share code, notes, and snippets.

@SevInf
Created September 30, 2016 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SevInf/007cbce5c5ad6898dc28c279998445ac to your computer and use it in GitHub Desktop.
Save SevInf/007cbce5c5ad6898dc28c279998445ac to your computer and use it in GitHub Desktop.
Codemod to migrate from Q to Bluebird
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