The open and composable observability and data visualization platform. Visualize metrics, logs, and traces from multiple sources like Prometheus, Loki, Elasticsearch, InfluxDB, Postgres and many more.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
grafana/scripts/codemods/explicit-barrel-imports.cjs

40 lines
1.4 KiB

const path = require('path');
const isBareSpecifier = (importPath) => !importPath.startsWith('app/') && /^[^./]/.test(importPath);
const barrelFileNames = ['index.ts', 'index.tsx', 'index.js', 'index.jsx'];
const resolvePath = (fileDir, importPath) =>
importPath.startsWith('app/')
? require.resolve(path.join(__dirname, '..', '..', 'public', importPath))
: require.resolve(path.resolve(fileDir, importPath));
module.exports = function (fileInfo, api) {
const j = api.jscodeshift;
const root = j.withParser('tsx')(fileInfo.source);
const fileDir = path.dirname(fileInfo.path);
// Update import declarations that import from barrel files
root
.find(j.ImportDeclaration)
.filter((path) => !isBareSpecifier(path.node.source.value))
.forEach((path) => {
const resolvedPath = resolvePath(fileDir, path.node.source.value);
if (barrelFileNames.some((barrelFileName) => resolvedPath.endsWith(barrelFileName))) {
// Create a comment node
const comment = j.commentLine(' @todo: replace barrel import path');
// Attach the comment as a leading comment to the import declaration
if (!path.node.comments) {
path.node.comments = [];
}
path.node.comments.push(comment);
// Update the import path appending '/index'
path.node.source.value = path.node.source.value + '/index';
}
});
return root.toSource({
quote: 'single',
});
};