-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
helpers.ts
73 lines (59 loc) · 2.12 KB
/
helpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import chalk from 'chalk';
import { resolve, relative } from 'path';
import { writeFileSync, readFileSync } from 'fs';
import { Types } from '@graphql-codegen/plugin-helpers';
import detectIndent from 'detect-indent';
import { Answers } from './types';
import getLatestVersion from 'latest-version';
// Parses config and writes it to a file
export async function writeConfig(answers: Answers, config: Types.Config) {
const YAML = await import('json-to-pretty-yaml').then(m => ('default' in m ? m.default : m));
const ext = answers.config.toLocaleLowerCase().endsWith('.json') ? 'json' : 'yml';
const content = ext === 'json' ? JSON.stringify(config) : YAML.stringify(config);
const fullPath = resolve(process.cwd(), answers.config);
const relativePath = relative(process.cwd(), answers.config);
writeFileSync(fullPath, content, {
encoding: 'utf-8',
});
return {
relativePath,
fullPath,
};
}
// Updates package.json (script and plugins as dependencies)
export async function writePackage(answers: Answers, configLocation: string) {
// script
const pkgPath = resolve(process.cwd(), 'package.json');
const pkgContent = readFileSync(pkgPath, {
encoding: 'utf-8',
});
const pkg = JSON.parse(pkgContent);
const { indent } = detectIndent(pkgContent);
if (!pkg.scripts) {
pkg.scripts = {};
}
pkg.scripts[answers.script] = `graphql-codegen --config ${configLocation}`;
// plugin
if (!pkg.devDependencies) {
pkg.devDependencies = {};
}
await Promise.all(
answers.plugins.map(async plugin => {
pkg.devDependencies[plugin.package] = await getLatestVersion(plugin.package);
})
);
if (answers.introspection) {
pkg.devDependencies['@graphql-codegen/introspection'] = await getLatestVersion('@graphql-codegen/introspection');
}
pkg.devDependencies['@graphql-codegen/cli'] = await getLatestVersion('@graphql-codegen/cli');
writeFileSync(pkgPath, JSON.stringify(pkg, null, indent));
}
export function bold(str: string) {
return chalk.bold(str);
}
export function grey(str: string) {
return chalk.grey(str);
}
export function italic(str: string) {
return chalk.italic(str);
}