-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathextension.ts
325 lines (272 loc) · 9.54 KB
/
extension.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/* eslint-disable @typescript-eslint/no-explicit-any */
import * as vscode from 'vscode'
import * as graphqlCodegenCli from '@graphql-codegen/cli'
import * as path from 'path'
import multimatch from 'multimatch'
import cloneDeep from 'lodash.clonedeep'
import { YamlCliFlags } from '@graphql-codegen/cli'
import { globby } from 'globby'
let workspaceWithGraphqlCodegenCli: string | null = null
const makePathAbsolute = (fsPath: string): string => {
if (path.isAbsolute(fsPath) || fsPath.startsWith('http')) {
return fsPath
}
if (!workspaceWithGraphqlCodegenCli) {
throw new Error(
'workspaceWithGraphqlCodegenCli is not set. This should not happen, please report this as a bug.'
)
}
return path.join(workspaceWithGraphqlCodegenCli, fsPath)
}
const makePathOrPathArrayAbsolute = (
fsPath: string | string[]
): string | string[] => {
if (Array.isArray(fsPath)) {
return fsPath.map(makePathOrPathArrayAbsolute) as string[]
}
return makePathAbsolute(fsPath)
}
const makePathAbsoluteInSchema = (
schema: string | Record<string, any> | (string | Record<string, any>)[]
): string | Record<string, any> | (string | Record<string, any>)[] => {
if (Array.isArray(schema)) {
return schema.map(makePathAbsoluteInSchema)
}
if (typeof schema === 'string') {
return makePathAbsolute(schema)
}
const [path, configuration] = Object.entries(schema)[0]
return { [makePathAbsolute(path)]: configuration }
}
const PLUGIN_SETTINGS_ID = 'graphql-codegen'
const FILE_EXTENSIONS_WITH_DOCUMENTS_KEY =
'fileExtensionsDeclaringGraphQLDocuments'
const FILE_PATH_TO_WATCH_KEY = 'filePathToWatch'
const CONFIG_FILE_PATH = 'configFilePath'
function shouldRunGQLCodegenOnFile(filePath: string): boolean {
const configuration = vscode.workspace.getConfiguration(PLUGIN_SETTINGS_ID)
const fileExtensionsContainingGraphQLDocuments = configuration.get<string[]>(
FILE_EXTENSIONS_WITH_DOCUMENTS_KEY,
['graphql', 'gql']
)
const filePathToWatch = configuration.get<string | null>(
FILE_PATH_TO_WATCH_KEY,
null
)
const fileMatchesExtensions = fileExtensionsContainingGraphQLDocuments.some(
(ext) => filePath.endsWith(ext)
)
const fileInPathToWatch =
filePathToWatch == null || multimatch(filePath, filePathToWatch).length > 0
return fileMatchesExtensions && fileInPathToWatch
}
let cli: typeof graphqlCodegenCli | null = null
function requireGQLCodegenCli() {
if (cli) {
return cli
}
if (vscode.workspace.workspaceFolders === undefined) {
return
}
for (const dir of vscode.workspace.workspaceFolders) {
try {
cli = require(
path.join(dir.uri.fsPath, '/node_modules/@graphql-codegen/cli')
)
workspaceWithGraphqlCodegenCli = dir.uri.fsPath
return cli
} catch (err) {
// ignore-we only want to run if @graphql-codegen/cli is installed in node modules
}
}
}
const getConfigPath = async () => {
const configuration = vscode.workspace.getConfiguration(PLUGIN_SETTINGS_ID)
const userConfigPath = configuration.get<string | undefined>(
CONFIG_FILE_PATH,
undefined
)
if (userConfigPath) {
return makePathAbsolute(userConfigPath)
}
if (cli == null || !workspaceWithGraphqlCodegenCli) {
throw new Error(
'cli is not set. This should not happen, please report this as a bug.'
)
}
const foundConfigs = await globby(cli.generateSearchPlaces('codegen'), {
cwd: workspaceWithGraphqlCodegenCli
})
return path.join(workspaceWithGraphqlCodegenCli, foundConfigs[0])
}
// TODO figure out why we're getting Activating extension 'GraphQL.vscode-graphql-execution' failed: Cannot find module 'graphql-config'
// Require stack:
// - /home/capaj/.vscode/extensions/graphql.vscode-graphql-execution-0.1.7/dist/providers/exec-content.js
// - /home/capaj/.vscode/extensions/graphql.vscode-graphql-execution-0.1.7/dist/extension.js
// it does not seem to affect anything, just annoying spam in the console, generation works fine
export function activate(context: vscode.ExtensionContext) {
let cachedCtx: graphqlCodegenCli.CodegenContext | null = null
let originalGenerates: Record<string, unknown> | null = null
const getCodegenContextForVSCode = async () => {
if (cachedCtx) {
return cachedCtx
}
if (!cli) {
vscode.window.showWarningMessage(
`could not find '/node_modules/@graphql-codegen/cli'`
)
return
}
if (!workspaceWithGraphqlCodegenCli) {
vscode.window.showWarningMessage(
`could not find workspace with graphql-codegen-cli`
)
return
}
try {
const configFilePath = await getConfigPath()
const flags: Partial<graphqlCodegenCli.YamlCliFlags> = {
config: configFilePath
}
cachedCtx = await cli.createContext(flags as YamlCliFlags)
cachedCtx.cwd = workspaceWithGraphqlCodegenCli
const config = cachedCtx.getConfig()
if (!config) {
return
}
if (config.schema) {
// typically on a config for a single codegen artefact0
config.schema = makePathAbsoluteInSchema(config.schema)
}
const generates = config.generates
if (generates) {
originalGenerates = cloneDeep(generates)
const generatesWithAllAbsolutePaths: Record<string, any> = {}
// typically on a config for a codegen with multiple artifacts
for (const codegenGenerateOutput of Object.keys(generates)) {
const codegenGenerate = generates[codegenGenerateOutput] as any // as Types.ConfiguredOutput
if (codegenGenerate.schema) {
codegenGenerate.schema = makePathAbsoluteInSchema(
codegenGenerate.schema
)
}
if (
codegenGenerate.preset &&
typeof codegenGenerate.preset === 'string' &&
codegenGenerate.preset.includes('near-operation-file') &&
!codegenGenerate.presetConfig?.cwd
) {
if (!codegenGenerate.presetConfig) {
codegenGenerate.presetConfig = {}
}
codegenGenerate.presetConfig.cwd = workspaceWithGraphqlCodegenCli
}
codegenGenerate.originalOutputPath = codegenGenerateOutput
generatesWithAllAbsolutePaths[
makePathAbsolute(codegenGenerateOutput) // this is only needed for windows. Not sure why, but it works fine on linux even when these paths are relative
] = codegenGenerate
}
config.generates = generatesWithAllAbsolutePaths
}
cachedCtx.updateConfig(config)
// console.log('cached ctx', cachedCtx)
return cachedCtx
} catch (err) {
console.error(err)
throw err
}
}
vscode.workspace.onDidSaveTextDocument(
async (document: vscode.TextDocument) => {
if (shouldRunGQLCodegenOnFile(document.fileName)) {
requireGQLCodegenCli() // require the package lazily as late as possible-makes it possible to install the deps and get the generation working right away
const ctx = await getCodegenContextForVSCode()
if (!ctx) {
return
}
const config = ctx.getConfig()
if (!config) {
return
}
if (config.schema) {
config.documents = document.fileName
} else {
const { generates } = config
for (const codegenGenerateOutput of Object.keys(generates)) {
const codegenGenerate = generates[codegenGenerateOutput] as any // as Types.ConfiguredOutput
const matches = multimatch(
document.fileName.replace(
`${workspaceWithGraphqlCodegenCli}/`,
''
),
// @ts-expect-error
originalGenerates[codegenGenerate.originalOutputPath].documents
)
if (matches.length === 0) {
// this file does not match the glob. This will not generate so we can omit this
codegenGenerate.documents = []
} else {
codegenGenerate.documents = document.fileName
}
}
}
ctx.updateConfig(config)
await runCliGenerateWithUINotifications(ctx, document.fileName)
}
// const customConfig = customExtensionConfig()
}
)
const disposable = vscode.commands.registerCommand(
'graphql-codegen.generateGqlCodegen',
async () => {
requireGQLCodegenCli()
const ctx = await getCodegenContextForVSCode()
if (!ctx) {
return
}
const config = ctx.getConfig()
if (!config) {
vscode.window.showWarningMessage(
`could not find @graphql-codegen/cli config`
)
return
}
config.documents = makePathOrPathArrayAbsolute(
config.documents as string[]
)
ctx.updateConfig(config)
await runCliGenerateWithUINotifications(ctx)
}
)
context.subscriptions.push(disposable)
}
async function runCliGenerateWithUINotifications(
ctx: graphqlCodegenCli.CodegenContext,
file?: string
) {
if (!cli) {
vscode.window.showWarningMessage(
`could not find '/node_modules/@graphql-codegen/cli'`
)
return
}
try {
await cli.generate(ctx)
vscode.window.showInformationMessage(
`graphql codegen ${file ?? ''} successful!`
)
} catch (err) {
if (err.errors?.length) {
vscode.window.showErrorMessage(
`Codegen threw ${err.errors.length} ${
err.errors.length === 1 ? 'error' : 'errors'
}, first one: ${err.errors[0].message}`
)
} else {
vscode.window.showErrorMessage(`Codegen threw error: ${err.message}`)
}
}
}
export function deactivate() {
cli = null
}