|
| 1 | +/* eslint no-console: 0 */ |
| 2 | + |
| 3 | +import chalk from "chalk"; |
| 4 | +import yargs from "yargs"; |
| 5 | + |
| 6 | +import fix from "./fix"; |
| 7 | +import check from "./check"; |
| 8 | +import expandGlob from "./expand-glob"; |
| 9 | +import filterIgnored from "./filter-ignored"; |
| 10 | + |
| 11 | +const cli = argv => { |
| 12 | + const yargsInstance = yargs |
| 13 | + // Fix |
| 14 | + .command("fix", "Fix one or more files") |
| 15 | + .example("prettier-tslint fix file1.ts file2.ts", "Fix provided files") |
| 16 | + .example("prettier-tslint fix '**/*.ts'", "Fix all .ts files") |
| 17 | + // Check |
| 18 | + .command("check", "List files that aren't formatted") |
| 19 | + .example("prettier-tslint check '**/*.ts'", "List unformatted .ts files") |
| 20 | + // Meta |
| 21 | + .demandCommand(1, "Command not provided.") |
| 22 | + .help(); |
| 23 | + |
| 24 | + const args = yargsInstance.parse(argv); |
| 25 | + const command = args._[0]; |
| 26 | + const patterns = args._.slice(1); |
| 27 | + |
| 28 | + switch (command) { |
| 29 | + case "fix": |
| 30 | + return patterns.forEach(fixFiles); |
| 31 | + case "check": |
| 32 | + return patterns.forEach(checkFiles); |
| 33 | + default: |
| 34 | + yargs.showHelp(); |
| 35 | + console.error(`Unknown command: ${command}`); |
| 36 | + } |
| 37 | +}; |
| 38 | + |
| 39 | +const fixFiles = filePattern => { |
| 40 | + const files = filterIgnored(expandGlob(filePattern)); |
| 41 | + files.forEach(file => { |
| 42 | + const changed = !fix(file); |
| 43 | + console.log(changed ? file : chalk.gray(file)); |
| 44 | + }); |
| 45 | +}; |
| 46 | + |
| 47 | +const checkFiles = filePattern => { |
| 48 | + const files = filterIgnored(expandGlob(filePattern)); |
| 49 | + const invalid = files.filter(file => !check(file)); |
| 50 | + if (invalid.length) { |
| 51 | + process.exitCode = 1; |
| 52 | + } |
| 53 | + invalid.forEach(file => console.error(chalk.red.bold(file))); |
| 54 | +}; |
| 55 | + |
| 56 | +export default cli; |
0 commit comments