1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | import * as fsExtra from 'fs-extra';
|
13 | import * as path from 'path';
|
14 |
|
15 | import {Config, generateDeclarations} from './gen-ts';
|
16 |
|
17 | const commandLineArgs = require('command-line-args') as any;
|
18 | const commandLineUsage = require('command-line-usage') as any;
|
19 |
|
20 | const argDefs = [
|
21 | {
|
22 | name: 'help',
|
23 | type: Boolean,
|
24 | description: 'Print this help text.',
|
25 | },
|
26 | {
|
27 | name: 'version',
|
28 | type: Boolean,
|
29 | description: 'Print the installed version.',
|
30 | },
|
31 | {
|
32 | name: 'root',
|
33 | type: String,
|
34 | defaultValue: '.',
|
35 | description: 'Root directory of the package to analyze (default ".").',
|
36 | },
|
37 | {
|
38 | name: 'config',
|
39 | type: String,
|
40 | description:
|
41 | 'JSON configuration file (default "<root>/gen-tsd.json" if exists).',
|
42 | },
|
43 | {
|
44 | name: 'outDir',
|
45 | type: String,
|
46 | description:
|
47 | 'Type declarations output directory (default concatenated to stdout).',
|
48 | },
|
49 | ];
|
50 |
|
51 | async function run(argv: string[]) {
|
52 | const args = commandLineArgs(argDefs, {argv});
|
53 |
|
54 | if (args.help) {
|
55 | console.log(commandLineUsage([
|
56 | {
|
57 | header: `gen-typescript-declarations`,
|
58 | content: 'https://github.com/Polymer/gen-typescript-declarations',
|
59 | },
|
60 | {
|
61 | header: `Options`,
|
62 | optionList: argDefs,
|
63 | }
|
64 | ]));
|
65 | return;
|
66 | }
|
67 |
|
68 | if (args.version) {
|
69 | console.log(require('../package.json').version);
|
70 | return;
|
71 | }
|
72 |
|
73 | if (!args.config) {
|
74 | const p = path.join(args.root, 'gen-tsd.json');
|
75 | if (await fsExtra.pathExists(p)) {
|
76 | args.config = p;
|
77 | }
|
78 | }
|
79 | let config: Config = {};
|
80 | if (args.config) {
|
81 | console.info(`Loading config from "${args.config}".`);
|
82 | config = JSON.parse(await fsExtra.readFile(args.config, 'utf8')) as Config;
|
83 | }
|
84 |
|
85 | const fileMap = await generateDeclarations(args.root, config);
|
86 |
|
87 | if (args.outDir) {
|
88 | console.log('Writing type declarations to ' + path.resolve(args.outDir));
|
89 | await writeFileMap(args.outDir, fileMap);
|
90 | } else {
|
91 | const concatenated = [...fileMap.values()].join('\n');
|
92 | process.stdout.write(concatenated);
|
93 | }
|
94 | }
|
95 |
|
96 | async function writeFileMap(
|
97 | rootDir: string, files: Map<string, string>): Promise<void> {
|
98 | const promises = [];
|
99 | for (const [relPath, contents] of files) {
|
100 | const fullPath = path.join(rootDir, relPath);
|
101 | promises.push(fsExtra.outputFile(fullPath, contents));
|
102 | }
|
103 | await Promise.all(promises);
|
104 | }
|
105 |
|
106 | (async () => {
|
107 | try {
|
108 | await run(process.argv);
|
109 | } catch (e) {
|
110 | console.error(e);
|
111 | process.exit(1);
|
112 | }
|
113 | })();
|