-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfixer.js
More file actions
104 lines (92 loc) · 2.43 KB
/
fixer.js
File metadata and controls
104 lines (92 loc) · 2.43 KB
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
let fs = require('fs')
let { merge } = require('lodash')
let os = require('os')
let { fromDir } = require('./list-files')
let prettier = require('prettier')
let { extname } = require('path')
let npm = require('npm')
let { promisify } = require('util')
function addPrettierRc(projectPath = '') {
let globalPrettierRcStr
try {
globalPrettierRcStr = fs.readFileSync(`${os.homedir()}/.prettierrc`, {
encoding: 'utf8',
})
} catch (err) {}
let prettierRc
if (globalPrettierRcStr) {
try {
prettierRc = JSON.parse(globalPrettierRcStr)
} catch (err) {
throw err
}
} else {
prettierRc = {}
}
let prettierRcStr = JSON.stringify(prettierRc, null, 2)
let filepath = projectPath + '.prettierrc'
fs.writeFileSync(filepath, prettierRcStr)
}
function getPrettierRc() {
let prc
try {
let prcStr = fs.readFileSync('./.prettierrc', { encoding: 'utf8' })
prc = JSON.parse(prcStr)
} catch (err) {
throw err
}
return prc
}
function format(projectPath = './') {
let files = fromDir(projectPath)
for (let filename of files) {
let content = fs.readFileSync(filename, { encoding: 'utf8' })
let parser = {
'.js': 'babylon',
'.ts': 'typescript',
'.json': 'json',
}
let res = prettier.format(content, {
parser: parser[extname(filename)],
...getPrettierRc(),
})
fs.writeFileSync(filename, res)
}
}
async function installDeps() {
await promisify(npm.load)({ loaded: false, 'save-dev': true })
return promisify(npm.commands.install)(['husky', 'prettier', 'lint-staged'])
}
function run(projectPath = '') {
let filepath = projectPath + 'package.json'
let packageMerge = {
scripts: {
precommit: 'lint-staged',
},
'lint-staged': {
'*.{js,json,css}': ['prettier --write', 'git add'],
'*.ts': [
'prettier --write',
"tslint --fix -c ./tslint.json 'src/**/*.ts'",
'git add',
],
},
}
let package
try {
let fileStr = fs.readFileSync(filepath, { encoding: 'utf8' })
package = JSON.parse(fileStr)
} catch (err) {
console.error('package.json is not an actual .json')
throw err
}
let merged = merge({}, package, packageMerge)
let mergedStr = JSON.stringify(merged, null, 2)
fs.writeFileSync(filepath, mergedStr)
addPrettierRc(projectPath)
return merged
}
exports.addPrettierRc = addPrettierRc
exports.run = run
exports.format = format
exports.installDeps = installDeps