-
Notifications
You must be signed in to change notification settings - Fork 0
/
transform.js
105 lines (90 loc) · 2.84 KB
/
transform.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
module.exports = function transformer (file, api) {
// setup
const j = api.jscodeshift
const root = j(file.source)
// "main"
if (hasAnyFakerImports(root)) { // if faker isn't used in this file, skip it
if (importsAnythingFromFakerAlready(root)) {
insertIntoFaker(root)
} else {
insertFakerAfterMirage(root)
}
removeFakerFromMirage(root)
}
return root.toSource({quote: 'single'})
// global checks
function importsAnythingFromFakerAlready (root) {
return root
.find(j.ImportDeclaration)
.some(isImportingFromFaker)
}
function hasAnyFakerImports (root) {
return root
.find(j.ImportSpecifier)
.some(isImportingFaker)
}
// manipulations
function insertIntoFaker (root) {
root
.find(j.ImportDeclaration)
.filter(isImportingFromFaker)
.forEach(path => {
insertSpecifier(path, fakerSpecifier())
})
}
function insertFakerAfterMirage (root) {
root
.find(j.ImportDeclaration)
.filter(path => {
return path.node.source.value === 'ember-cli-mirage'
})
.insertAfter(standardFakerImport())
}
function removeFakerFromMirage (root) {
root
.find(j.ImportSpecifier)
.forEach(path => {
if (isImportingFaker(path) && isImportingFromEmberCliMirage(path.parent)) {
removeSpecifierOrImportDeclaration(path)
}
})
}
// node generation
function standardFakerImport () {
return j.importDeclaration(
[
fakerSpecifier()
],
j.literal('faker')
)
}
function fakerSpecifier () {
return j.importDefaultSpecifier(j.identifier('faker'))
}
// node checks - importSpecifierPath
function isImportingFaker (importSpecifierPath) {
return importSpecifierPath.node.imported.name === 'faker'
}
function isImportingFromEmberCliMirage (importSpecifierPath) {
return importSpecifierPath.node.source.value === 'ember-cli-mirage'
}
function isImportingFromFaker (importSpecifierPath) {
return importSpecifierPath.node.source.value === 'faker'
}
// node checks - importDeclarationPath
function isOnlySpecifierInImportDeclaration (importDeclarationPath) {
return importDeclarationPath.node.specifiers.length === 1
}
// general utility
function removeSpecifierOrImportDeclaration (importSpecifierPath) {
const importDeclarationPath = importSpecifierPath.parent
if (isOnlySpecifierInImportDeclaration(importDeclarationPath)) {
j(importDeclarationPath).remove() // remove entire import declaration
} else {
j(importSpecifierPath).remove() // remove just the one specifier
}
}
function insertSpecifier (importDeclarationPath, specifier) {
importDeclarationPath.get('specifiers').push(specifier)
}
}