1 | #!/usr/bin/env node
|
2 |
|
3 | const fs = require('fs')
|
4 | const path = require('path')
|
5 | const yargs = require('yargs')
|
6 | const execSync = require('child_process').execSync
|
7 |
|
8 | const argv = yargs.usage('Usage: $0 [options]').option('fix', {
|
9 | describe: 'auto-fix problems',
|
10 | type: 'boolean',
|
11 | }).argv
|
12 |
|
13 | function scanFor(file, maxDepth = 3) {
|
14 | let pathToFile = path.join(process.cwd(), file)
|
15 | while (pathToFile.length > file.length + 1 && !fs.existsSync(pathToFile) && maxDepth >= 0) {
|
16 | const parentDir = path.dirname(pathToFile.substr(0, pathToFile.length - file.length))
|
17 | pathToFile = path.join(parentDir, file)
|
18 | maxDepth--
|
19 | }
|
20 |
|
21 | return fs.existsSync(pathToFile) ? pathToFile : ''
|
22 | }
|
23 |
|
24 | const TSCONFIG_PATH = scanFor('tsconfig.json')
|
25 | const TSLINT_PATH = scanFor('node_modules/.bin/tslint')
|
26 | const ESLINT_PATH = scanFor('node_modules/.bin/eslint')
|
27 | const PRETTIER_PATH = scanFor('node_modules/.bin/prettier')
|
28 | const TSLINTRC_PATH = scanFor('tslint.json')
|
29 | const ESLINTRC_PATH = scanFor('.eslintrc')
|
30 |
|
31 | if (!TSLINT_PATH && !ESLINT_PATH) {
|
32 | throw new Error('Must have either eslint or tslint installed')
|
33 | }
|
34 |
|
35 | if (!PRETTIER_PATH) {
|
36 | throw new Error('Must have prettier installed')
|
37 | }
|
38 |
|
39 | if (!TSLINTRC_PATH && !ESLINTRC_PATH) {
|
40 | throw new Error('Must have either eslint or tslint config')
|
41 | }
|
42 |
|
43 | function exec(command) {
|
44 | try {
|
45 | execSync(command, {stdio: 'inherit'})
|
46 | return true
|
47 | } catch (err) {
|
48 | process.stderr.write(err.message + '\n')
|
49 | return false
|
50 | }
|
51 | }
|
52 |
|
53 | const directories = `{packages/*/,./}{src/**/,lib/**/,bin/**/,test/**/,}`
|
54 |
|
55 | const lintFixArg = argv.fix ? '--fix' : ''
|
56 | const lintCommand = TSCONFIG_PATH
|
57 | ? `${TSLINT_PATH} --project . -c ${TSLINTRC_PATH}`
|
58 | : `${ESLINT_PATH} -c ${ESLINTRC_PATH} '${directories}*.js'`
|
59 | const lintPassed = exec(`${lintCommand} ${lintFixArg}`)
|
60 | const prettierFixArg = argv.fix ? '--write' : '--list-different'
|
61 | const prettierFiles = `${directories}*.{ts,css,scss,md,json}`
|
62 | const prettierPassed = exec(`${PRETTIER_PATH} ${prettierFixArg} '${prettierFiles}'`)
|
63 | process.exit(lintPassed && prettierPassed ? 0 : 1)
|