1 | #!/usr/bin/env node
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | require('pretty-error').start();
|
7 |
|
8 | const https = require('https');
|
9 | const path = require('path');
|
10 | const fs = require('fs');
|
11 |
|
12 | const argv = require('yargs').argv;
|
13 | const mkdirp = require('mkdirp');
|
14 |
|
15 | const optionsPath = argv.o || argv.options || './.swaggergenrc';
|
16 |
|
17 | const parseRcFile = () => {
|
18 | try {
|
19 | const absoluteOptionsPath = path.resolve(process.cwd(), optionsPath);
|
20 | const optionsFile = fs.readFileSync(absoluteOptionsPath, 'utf-8');
|
21 | return JSON.parse(optionsFile);
|
22 | } catch (error) {
|
23 | console.error(error);
|
24 | throw new Error(`Could not resolve ${optionsPath}`);
|
25 | }
|
26 | };
|
27 |
|
28 | const downloadFile = (url, destination, callback) => {
|
29 | console.info(`Downloading ${url} to ${destination}`);
|
30 | const timeMark = path.posix.basename(destination);
|
31 | console.time(timeMark);
|
32 | const absoluteDestination = path.resolve(process.cwd(), destination);
|
33 |
|
34 | mkdirp(path.dirname(absoluteDestination), (fsError) => {
|
35 | if (fsError) {
|
36 | console.log(`fsError: ${fsError}`);
|
37 | }
|
38 |
|
39 | const file = fs.createWriteStream(absoluteDestination);
|
40 |
|
41 | https.get(url, (response) => {
|
42 | response.pipe(file);
|
43 | file.on('finish', () => {
|
44 | file.close(callback);
|
45 | console.timeEnd(timeMark);
|
46 | });
|
47 | }).on('error', (error) => {
|
48 | fs.unlink(destination);
|
49 | if (callback) {
|
50 | callback(error);
|
51 | }
|
52 | });
|
53 | });
|
54 | };
|
55 |
|
56 | module.exports.default = (() => {
|
57 | const rc = parseRcFile();
|
58 |
|
59 | if (rc.specs && rc.specs instanceof Object) {
|
60 | return Promise.all(
|
61 | Object.keys(rc.specs)
|
62 | .map(destination => downloadFile(rc.specs[destination], destination)),
|
63 | );
|
64 | }
|
65 |
|
66 | throw new Error(`Couldn't parse specs. Should be a plain object, like { [destinationPath]: urlToDownload }. Got instead: ${JSON.stringify(rc.specs, null, 2)}`);
|
67 | })();
|