1 | import { existsSync, readFileSync } from 'fs';
|
2 | import { join, resolve } from 'path';
|
3 | import { DetailedError } from './errors';
|
4 | import { parseConfigFile } from './yml';
|
5 | import { Command } from 'commander';
|
6 | function getCustomConfigPath(cliFlags) {
|
7 | const configFile = cliFlags.config;
|
8 | if (configFile) {
|
9 | const configPath = resolve(process.cwd(), configFile);
|
10 | if (!existsSync(configPath)) {
|
11 | throw new DetailedError(`Config ${configPath} does not exist`, `
|
12 | Config ${configPath} does not exist.
|
13 |
|
14 | $ gql-gen --config ${configPath}
|
15 |
|
16 | Please make sure the --config points to a correct file.
|
17 | `);
|
18 | }
|
19 | return configPath;
|
20 | }
|
21 | return null;
|
22 | }
|
23 | function loadAndParseConfig(filepath) {
|
24 | const ext = filepath.substr(filepath.lastIndexOf('.') + 1);
|
25 | switch (ext) {
|
26 | case 'yml':
|
27 | return parseConfigFile(readFileSync(filepath, 'utf-8'));
|
28 | case 'json':
|
29 | return JSON.parse(readFileSync(filepath, 'utf-8'));
|
30 | case 'js':
|
31 | return require(resolve(process.cwd(), filepath));
|
32 | default:
|
33 | throw new DetailedError(`Extension '${ext}' is not supported`, `
|
34 | Config ${filepath} couldn't be parsed. Extension '${ext}' is not supported.
|
35 | `);
|
36 | }
|
37 | }
|
38 | export function createConfig(argv = process.argv) {
|
39 | const cliFlags = new Command()
|
40 | .usage('gql-gen [options]')
|
41 | .allowUnknownOption(true)
|
42 | .option('-c, --config <path>', 'Path to GraphQL codegen YAML config file, defaults to "codegen.yml" on the current directory')
|
43 | .option('-w, --watch', 'Watch for changes and execute generation automatically')
|
44 | .option('-o, --overwrite', 'Overwrites existing files')
|
45 | .parse(argv);
|
46 | const customConfigPath = getCustomConfigPath(cliFlags);
|
47 | const locations = [join(process.cwd(), './codegen.yml'), join(process.cwd(), './codegen.json')];
|
48 | if (customConfigPath) {
|
49 | locations.unshift(customConfigPath);
|
50 | }
|
51 | const filepath = locations.find(existsSync);
|
52 | if (!filepath) {
|
53 | throw new DetailedError(`Unable to find Codegen config file!`, `
|
54 | Please make sure that you have a configuration file under the current directory!
|
55 | `);
|
56 | }
|
57 | const parsedConfigFile = loadAndParseConfig(filepath);
|
58 | if (cliFlags.watch === true) {
|
59 | parsedConfigFile.watch = cliFlags.watch;
|
60 | }
|
61 | if (cliFlags.overwrite === true) {
|
62 | parsedConfigFile.overwrite = cliFlags.overwrite;
|
63 | }
|
64 | return parsedConfigFile;
|
65 | }
|
66 |
|
\ | No newline at end of file |