|
| 1 | +import { |
| 2 | + template, |
| 3 | + types, |
| 4 | + operator, |
| 5 | +} from 'putout'; |
| 6 | + |
| 7 | +const { |
| 8 | + remove, |
| 9 | + rename, |
| 10 | + insertBefore, |
| 11 | + getPathAfterImports, |
| 12 | +} = operator; |
| 13 | + |
| 14 | +const { |
| 15 | + isVariableDeclaration, |
| 16 | + expressionStatement, |
| 17 | + objectProperty, |
| 18 | + identifier, |
| 19 | +} = types; |
| 20 | +const {entries} = Object; |
| 21 | + |
| 22 | +const createHoisted = template('const hoisted = vi.hoisted({})'); |
| 23 | +const createMockClear = template('NAME.mockClear();'); |
| 24 | +const createBeforeEach = template('beforeEach(() => {})'); |
| 25 | + |
| 26 | +export const report = () => `Use 'vi.hoisted()'`; |
| 27 | + |
| 28 | +export const fix = ({path, names}) => { |
| 29 | + const hoistedNode = createHoisted(); |
| 30 | + const beforeEach = createBeforeEach(); |
| 31 | + |
| 32 | + const [object] = hoistedNode.declarations[0].init.arguments; |
| 33 | + const {body} = beforeEach.arguments[0].body; |
| 34 | + |
| 35 | + for (const name of names) { |
| 36 | + const key = identifier(name); |
| 37 | + const value = template.ast('vi.fn()'); |
| 38 | + const property = objectProperty(key, value); |
| 39 | + |
| 40 | + object.properties.push(property); |
| 41 | + body.push(expressionStatement(createMockClear({ |
| 42 | + NAME: name, |
| 43 | + }))); |
| 44 | + } |
| 45 | + |
| 46 | + const afterImportsPath = getPathAfterImports(path.get('body')); |
| 47 | + |
| 48 | + insertBefore(afterImportsPath, hoistedNode); |
| 49 | + insertBefore(afterImportsPath, expressionStatement(beforeEach)); |
| 50 | +}; |
| 51 | + |
| 52 | +export const traverse = ({push}) => ({ |
| 53 | + Program(path) { |
| 54 | + const names = []; |
| 55 | + |
| 56 | + for (const [name, binding] of entries(path.scope.bindings)) { |
| 57 | + const {parentPath} = binding.path; |
| 58 | + |
| 59 | + if (!isVariableDeclaration(parentPath)) |
| 60 | + continue; |
| 61 | + |
| 62 | + if (parentPath.node.declarations[0].init) |
| 63 | + continue; |
| 64 | + |
| 65 | + rename(path, name, `hoisted.${name}`); |
| 66 | + remove(binding.path); |
| 67 | + names.push(name); |
| 68 | + } |
| 69 | + |
| 70 | + if (names.length) |
| 71 | + push({ |
| 72 | + path, |
| 73 | + names, |
| 74 | + }); |
| 75 | + }, |
| 76 | +}); |
0 commit comments