UNPKG

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