@atlaskit/eslint-plugin-design-system
Version:
The essential plugin for use with the Atlassian Design System.
64 lines (59 loc) • 2.13 kB
JavaScript
/* eslint-disable @repo/internal/react/require-jsdoc */
import { hasImportDeclaration, insertImportDeclaration, isNodeOfType } from 'eslint-codemod-utils';
import { getSourceCode } from '@atlaskit/eslint-utils/context-compat';
import { Import } from './import';
// Little bit unreadable, but better than duplicating the type
export const Root = {
/**
* Note: This can return multiple ImportDeclarations for cases like:
* ```
* import { Stack } from '@atlaskit/primitives'
* import type { StackProps } from '@atlaskit/primitives'
* ```
*/
findImportsByModule(root, name) {
return root.filter(node => {
if (!isNodeOfType(node, 'ImportDeclaration')) {
return false;
}
let names = typeof name === 'string' ? [name] : name;
if (!names.some(name => hasImportDeclaration(node, name))) {
return false;
}
return true;
});
},
insertImport(root, data, fixer) {
return fixer.insertTextBefore(root[0], `${insertImportDeclaration(data.module, data.specifiers)};\n`);
},
upsertNamedImportDeclaration({
module,
specifiers
}, context, fixer) {
// Find any imports that match the packageName
const root = getSourceCode(context).ast.body;
const importDeclarations = this.findImportsByModule(root, module);
// The named import doesn't exist yet, we can just insert a whole new one
if (importDeclarations.length === 0) {
return this.insertImport(root, {
module,
specifiers
}, fixer);
}
// The import exists so, modify the existing one
return Import.insertNamedSpecifiers(importDeclarations[0], specifiers, fixer);
},
upsertDefaultImportDeclaration({
module,
localName
}, context, fixer) {
// Find any imports that match the packageName
const root = getSourceCode(context).ast.body;
const importDeclarations = this.findImportsByModule(root, module);
// The import already exist exist
if (importDeclarations.length > 0) {
return undefined;
}
return fixer.insertTextBefore(root[0], `import ${localName} from '${module}';\n`);
}
};