Skip to content

Instantly share code, notes, and snippets.

@keepitterron
Created June 22, 2020 09:39
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 keepitterron/f7cbae353cc14a101227b72f950b978b to your computer and use it in GitHub Desktop.
Save keepitterron/f7cbae353cc14a101227b72f950b978b to your computer and use it in GitHub Desktop.
// yarn install -D jscodeshift
module.exports = function(fileInfo, { jscodeshift: j }) {
const ast = j(fileInfo.source);
ast // import * as Sentry from 'sentry'
.find(j.ImportDeclaration, isSentryImport)
.replaceWith(nodePath => {
// get the underlying Node
const { node } = nodePath;
node.specifiers.forEach(specifier => (specifier.local.name = 'loggerx'));
node.source.value = node.source.value.replace('sentry', 'loggerx');
// change to our new prop
// node.property.name = 'getCircleArea';
// replaceWith should return a Node, not a NodePath
return node;
});
ast
.find(j.CallExpression, {
callee: {
property: { name: 'logException' },
},
})
.replaceWith(nodePath => {
// get the underlying Node
const { node } = nodePath;
node.callee.object.name = 'loggerx';
node.callee.property.name = 'error';
let [err, message, context] = node.arguments;
if (!context) {
context = j.objectExpression([]);
}
if (err.type === 'TemplateLiteral') {
err.expressions.forEach(exp =>
context.properties.push(
j.property('init', j.identifier(exp.name), j.identifier(exp.name))
)
);
const msg = err.quasis[0].value.raw.trim();
err = j.callExpression(j.identifier('Error'), [j.literal(msg)]);
}
node.arguments = [err];
if (message) {
context.properties.push(
j.property('init', j.identifier('message'), j.literal(message.value))
);
}
if (context.properties.length) {
context.properties.forEach(prop => {
prop.key.name = snakeToCamel(prop.key.name);
});
node.arguments.push(context);
}
return node;
});
return ast.toSource();
};
function isSentryImport(node) {
return (
node.type === 'ImportDeclaration' && node.source.value.endsWith('sentry')
);
}
const snakeToCamel = str =>
str.replace(/([-_][a-z])/g, group =>
group
.toUpperCase()
.replace('-', '')
.replace('_', '')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment