forked from dotansimha/graphql-code-generator
/
generate-and-save.ts
177 lines (145 loc) · 6.28 KB
/
generate-and-save.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import { lifecycleHooks } from './hooks.js';
import { Types } from '@graphql-codegen/plugin-helpers';
import { executeCodegen } from './codegen.js';
import { createWatcher } from './utils/watcher.js';
import { readFile, writeFile, unlinkFile, mkdirp } from './utils/file-system.js';
import { dirname, join, isAbsolute } from 'path';
import { debugLog } from './utils/debugging.js';
import { CodegenContext, ensureContext } from './config.js';
import { createHash } from 'crypto';
const hash = (content: string): string => createHash('sha1').update(content).digest('base64');
export async function generate(
input: CodegenContext | (Types.Config & { cwd?: string }),
saveToFile = true
): Promise<Types.FileOutput[] | any> {
const context = ensureContext(input);
const config = context.getConfig();
await context.profiler.run(() => lifecycleHooks(config.hooks).afterStart(), 'Lifecycle: afterStart');
let previouslyGeneratedFilenames: string[] = [];
function removeStaleFiles(config: Types.Config, generationResult: Types.FileOutput[]) {
const filenames = generationResult.map(o => o.filename);
// find stale files from previous build which are not present in current build
const staleFilenames = previouslyGeneratedFilenames.filter(f => !filenames.includes(f));
staleFilenames.forEach(filename => {
if (shouldOverwrite(config, filename)) {
return unlinkFile(filename, err => {
const prettyFilename = filename.replace(`${input.cwd || process.cwd()}/`, '');
if (err) {
debugLog(`Cannot remove stale file: ${prettyFilename}\n${err}`);
} else {
debugLog(`Removed stale file: ${prettyFilename}`);
}
});
}
});
previouslyGeneratedFilenames = filenames;
}
const recentOutputHash = new Map<string, string>();
async function writeOutput(generationResult: Types.FileOutput[]) {
if (!saveToFile) {
return generationResult;
}
if (config.watch) {
removeStaleFiles(config, generationResult);
}
await context.profiler.run(async () => {
await lifecycleHooks(config.hooks).beforeAllFileWrite(generationResult.map(r => r.filename));
}, 'Lifecycle: beforeAllFileWrite');
await context.profiler.run(
() =>
Promise.all(
generationResult.map(async (result: Types.FileOutput) => {
const previousHash = recentOutputHash.get(result.filename) || (await hashFile(result.filename));
const exists = previousHash !== null;
// Store previous hash to avoid reading from disk again
if (previousHash) {
recentOutputHash.set(result.filename, previousHash);
}
if (!shouldOverwrite(config, result.filename) && exists) {
return;
}
let content = result.content || '';
const currentHash = hash(content);
if (previousHash && currentHash === previousHash) {
debugLog(`Skipping file (${result.filename}) writing due to indentical hash...`);
return;
}
// skip updating file in dry mode
if (context.checkMode) {
context.checkModeStaleFiles.push(result.filename);
return;
}
if (content.length === 0) {
return;
}
const absolutePath = isAbsolute(result.filename)
? result.filename
: join(input.cwd || process.cwd(), result.filename);
const basedir = dirname(absolutePath);
await mkdirp(basedir);
content = await lifecycleHooks(result.hooks).beforeOneFileWrite(absolutePath, content);
content = await lifecycleHooks(config.hooks).beforeOneFileWrite(absolutePath, content);
if (content !== result.content) {
result.content = content;
// compare the prettified content with the previous hash
// to compare the content with an existing prettified file
if (hash(content) === previousHash) {
debugLog(`Skipping file (${result.filename}) writing due to indentical hash after prettier...`);
// the modified content is NOT stored in recentOutputHash
// so a diff can already be detected before executing the hook
return;
}
}
await writeFile(absolutePath, result.content);
recentOutputHash.set(result.filename, currentHash);
await lifecycleHooks(result.hooks).afterOneFileWrite(result.filename);
await lifecycleHooks(config.hooks).afterOneFileWrite(result.filename);
})
),
'Write files'
);
await context.profiler.run(
() => lifecycleHooks(config.hooks).afterAllFileWrite(generationResult.map(r => r.filename)),
'Lifecycle: afterAllFileWrite'
);
return generationResult;
}
// watch mode
if (config.watch) {
return createWatcher(context, writeOutput);
}
const outputFiles = await context.profiler.run(() => executeCodegen(context), 'executeCodegen');
await context.profiler.run(() => writeOutput(outputFiles), 'writeOutput');
await context.profiler.run(() => lifecycleHooks(config.hooks).beforeDone(), 'Lifecycle: beforeDone');
if (context.profilerOutput) {
await writeFile(join(context.cwd, context.profilerOutput), JSON.stringify(context.profiler.collect()));
}
return outputFiles;
}
function shouldOverwrite(config: Types.Config, outputPath: string): boolean {
const globalValue = config.overwrite === undefined ? true : !!config.overwrite;
const outputConfig = config.generates[outputPath];
if (!outputConfig) {
debugLog(`Couldn't find a config of ${outputPath}`);
return globalValue;
}
if (isConfiguredOutput(outputConfig) && typeof outputConfig.overwrite === 'boolean') {
return outputConfig.overwrite;
}
return globalValue;
}
function isConfiguredOutput(output: any): output is Types.ConfiguredOutput {
return typeof output.plugins !== 'undefined';
}
async function hashFile(filePath: string): Promise<string | null> {
try {
return hash(await readFile(filePath));
} catch (err) {
if (err && err.code === 'ENOENT') {
// return null if file does not exist
return null;
}
// rethrow unexpected errors
throw err;
}
}