/
ProjectActions.ts
568 lines (453 loc) · 18.3 KB
/
ProjectActions.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
import type { CodeGenType, MutationSetProjectPreferencesInGlobalCacheArgs, NexusGenObjects, NexusGenUnions } from '@packages/graphql/src/gen/nxs.gen'
import { InitializeProjectOptions, FoundBrowser, OpenProjectLaunchOptions, Preferences, TestingType, ReceivedCypressOptions, AddProject, FullConfig, AllowedState, SpecWithRelativeRoot, OpenProjectLaunchOpts, RUN_ALL_SPECS, RUN_ALL_SPECS_KEY } from '@packages/types'
import type { EventEmitter } from 'events'
import execa from 'execa'
import path from 'path'
import assert from 'assert'
import type { ProjectShape } from '../data/coreDataShape'
import type { DataContext } from '..'
import { codeGenerator, SpecOptions, hasNonExampleSpec } from '../codegen'
import templates from '../codegen/templates'
import { insertValuesInConfigFile } from '../util'
import { getError } from '@packages/errors'
import { resetIssuedWarnings } from '@packages/config'
import { WizardFrontendFramework, WIZARD_FRAMEWORKS } from '@packages/scaffold-config'
export interface ProjectApiShape {
/**
* "Initializes" the given mode, since plugins can define the browsers available
* TODO(tim): figure out what this is actually doing, it seems it's necessary in
* order for CT to startup
*/
openProjectCreate(args: InitializeProjectOptions, options: OpenProjectLaunchOptions): Promise<unknown>
launchProject(browser: FoundBrowser, spec: Cypress.Spec, options?: Partial<OpenProjectLaunchOpts>): Promise<void>
insertProjectToCache(projectRoot: string): Promise<void>
removeProjectFromCache(projectRoot: string): Promise<void>
getProjectRootsFromCache(): Promise<ProjectShape[]>
insertProjectPreferencesToCache(projectTitle: string, preferences: Preferences): void
getProjectPreferencesFromCache(): Promise<Record<string, Preferences>>
clearLatestProjectsCache(): Promise<unknown>
clearProjectPreferences(projectTitle: string): Promise<unknown>
clearAllProjectPreferences(): Promise<unknown>
closeActiveProject(shouldCloseBrowser?: boolean): Promise<unknown>
getConfig(): ReceivedCypressOptions | undefined
getRemoteStates(): { reset(): void, getPrimary(): Cypress.RemoteState } | undefined
getCurrentBrowser: () => Cypress.Browser | undefined
getCurrentProjectSavedState(): AllowedState | undefined
setPromptShown(slug: string): void
setProjectPreferences(stated: AllowedState): void
makeProjectSavedState(projectRoot: string): void
getDevServer (): {
updateSpecs(specs: SpecWithRelativeRoot[]): void
start(options: {specs: Cypress.Spec[], config: FullConfig}): Promise<{port: number}>
close(): void
emitter: EventEmitter
}
isListening: (url: string) => Promise<void>
resetBrowserTabsForNextTest(shouldKeepTabOpen: boolean): Promise<void>
resetServer(): void
}
export interface FindSpecs<T> {
projectRoot: string
testingType: Cypress.TestingType
/**
* This can be over-ridden by the --spec argument (run mode only)
* Otherwise it will be the same as `configSpecPattern`
*/
specPattern: T
/**
* The specPattern resolved from e2e.specPattern or component.specPattern
* inside of `cypress.config`.
*/
configSpecPattern: T
/**
* User can opt to exclude certain patterns in cypress.config.
*/
excludeSpecPattern: T
/**
* If in component testing mode, we exclude all specs matching the e2e.specPattern.
*/
additionalIgnorePattern: T
}
type SetForceReconfigureProjectByTestingType = {
forceReconfigureProject: boolean
testingType?: TestingType
}
export class ProjectActions {
constructor (private ctx: DataContext) {}
private get api () {
return this.ctx._apis.projectApi
}
async clearCurrentProject () {
this.ctx.update((d) => {
d.activeBrowser = null
d.currentProject = null
d.diagnostics = {
error: null,
warnings: [],
}
d.currentTestingType = null
d.forceReconfigureProject = null
d.scaffoldedFiles = null
d.app.browserStatus = 'closed'
})
await this.ctx.lifecycleManager.clearCurrentProject()
resetIssuedWarnings()
await this.api.closeActiveProject()
}
private get projects () {
return this.ctx.projectsList
}
private set projects (projects: ProjectShape[]) {
this.ctx.coreData.app.projects = projects
}
openDirectoryInIDE (projectPath: string) {
this.ctx.debug(`opening ${projectPath} in ${this.ctx.coreData.localSettings.preferences.preferredEditorBinary}`)
if (!this.ctx.coreData.localSettings.preferences.preferredEditorBinary) {
return
}
if (this.ctx.coreData.localSettings.preferences.preferredEditorBinary === 'computer') {
this.ctx.actions.electron.showItemInFolder(projectPath)
}
execa(this.ctx.coreData.localSettings.preferences.preferredEditorBinary, [projectPath])
}
setAndLoadCurrentTestingType (type: TestingType) {
this.ctx.lifecycleManager.setAndLoadCurrentTestingType(type)
}
async setCurrentProject (projectRoot: string) {
await this.updateProjectList(() => this.api.insertProjectToCache(projectRoot))
await this.clearCurrentProject()
await this.ctx.lifecycleManager.setCurrentProject(projectRoot)
}
// Temporary: remove after other refactor lands
async setCurrentProjectAndTestingTypeForTestSetup (projectRoot: string) {
await this.ctx.lifecycleManager.clearCurrentProject()
await this.ctx.lifecycleManager.setCurrentProject(projectRoot)
this.ctx.lifecycleManager.setCurrentTestingType('e2e')
// @ts-expect-error - we are setting this as a convenience for our integration tests
this.ctx._modeOptions = {}
}
async loadProjects () {
const projectRoots = await this.api.getProjectRootsFromCache()
this.ctx.update((d) => {
d.app.projects = [...projectRoots]
})
return this.projects
}
async initializeActiveProject (options: OpenProjectLaunchOptions = {}) {
assert(this.ctx.currentProject, 'Cannot initialize project without an active project')
assert(this.ctx.coreData.currentTestingType, 'Cannot initialize project without choosing testingType')
const allModeOptionsWithLatest: InitializeProjectOptions = {
...this.ctx.modeOptions,
projectRoot: this.ctx.currentProject,
testingType: this.ctx.coreData.currentTestingType,
}
try {
await this.api.closeActiveProject()
return await this.api.openProjectCreate(allModeOptionsWithLatest, {
...options,
ctx: this.ctx,
}).finally(async () => {
// When switching testing type, the project should be relaunched in the previously selected browser
if (this.ctx.coreData.app.relaunchBrowser) {
this.ctx.project.setRelaunchBrowser(false)
await this.ctx.actions.project.launchProject(this.ctx.coreData.currentTestingType)
}
})
} catch (e) {
// TODO(tim): remove / replace with ctx.log.error
// eslint-disable-next-line
console.error(e)
throw e
}
}
private async updateProjectList (updater: () => Promise<void>) {
return updater().then(() => this.loadProjects())
}
async addProjectFromElectronNativeFolderSelect () {
const path = await this.ctx.actions.electron.showOpenDialog()
if (!path) {
return
}
await this.addProject({ path, open: true })
this.ctx.emitter.toLaunchpad()
}
async addProject (args: AddProject) {
const projectRoot = await this.getDirectoryPath(args.path)
if (args.open) {
this.setCurrentProject(projectRoot).catch(this.ctx.onError)
} else {
await this.updateProjectList(() => this.api.insertProjectToCache(projectRoot))
}
}
private async getDirectoryPath (projectRoot: string) {
try {
const { dir, base } = path.parse(projectRoot)
const fullPath = path.join(dir, base)
const dirStat = await this.ctx.fs.stat(fullPath)
if (dirStat.isDirectory()) {
return fullPath
}
return dir
} catch (exception) {
throw Error(`Cannot add ${projectRoot} to projects as it does not exist in the file system`)
}
}
async launchProject (testingType: Cypress.TestingType | null, options?: Partial<OpenProjectLaunchOpts>, specPath?: string | null) {
if (!this.ctx.currentProject) {
return null
}
testingType = testingType || this.ctx.coreData.currentTestingType
// It's strange to have no testingType here, but `launchProject` is called when switching testing types,
// so it needs to short-circuit and return here.
// TODO: Untangle this. https://cypress-io.atlassian.net/browse/UNIFY-1528
if (!testingType) return
this.ctx.coreData.currentTestingType = testingType
const browser = this.ctx.coreData.activeBrowser
if (!browser) throw new Error('Missing browser in launchProject')
let activeSpec: Cypress.Spec | undefined
if (specPath) {
activeSpec = specPath === RUN_ALL_SPECS_KEY ? RUN_ALL_SPECS : this.ctx.project.getCurrentSpecByAbsolute(specPath)
}
// launchProject expects a spec when opening browser for url navigation.
// We give it an empty spec if none is passed so as to land on home page
const emptySpec: Cypress.Spec = {
name: '',
absolute: '',
relative: '',
specType: testingType === 'e2e' ? 'integration' : 'component',
}
// Used for run-all-specs feature
if (options?.shouldLaunchNewTab) {
await this.api.resetBrowserTabsForNextTest(true)
this.api.resetServer()
}
await this.api.launchProject(browser, activeSpec ?? emptySpec, options)
return
}
removeProject (projectRoot: string) {
return this.updateProjectList(() => this.api.removeProjectFromCache(projectRoot))
}
async createConfigFile (type?: 'component' | 'e2e' | null) {
const project = this.ctx.currentProject
if (!project) {
throw Error(`Cannot create config file without currentProject.`)
}
let obj: { [k: string]: object } = {
e2e: {},
component: {},
}
if (type) {
obj = {
[type]: {},
}
}
await this.ctx.fs.writeFile(this.ctx.lifecycleManager.configFilePath, `module.exports = ${JSON.stringify(obj, null, 2)}`)
}
async setProjectIdInConfigFile (projectId: string) {
return insertValuesInConfigFile(this.ctx.lifecycleManager.configFilePath, { projectId }, { get (id: string) {
return Error(id)
} })
}
async clearLatestProjectCache () {
await this.api.clearLatestProjectsCache()
}
async clearProjectPreferencesCache (projectTitle: string) {
await this.api.clearProjectPreferences(projectTitle)
}
async clearAllProjectPreferencesCache () {
await this.api.clearAllProjectPreferences()
}
setPromptShown (slug: string) {
this.api.setPromptShown(slug)
}
setSpecs (specs: SpecWithRelativeRoot[]) {
this.ctx.project.setSpecs(specs)
this.refreshSpecs(specs)
// only check for non-example specs when the specs change
this.hasNonExampleSpec().then((result) => {
this.ctx.project.setHasNonExampleSpec(result)
})
.catch((e) => {
this.ctx.project.setHasNonExampleSpec(false)
this.ctx.logTraceError(e)
})
if (this.ctx.coreData.currentTestingType === 'component') {
this.api.getDevServer().updateSpecs(specs)
}
this.ctx.emitter.specsChange()
}
refreshSpecs (specs: SpecWithRelativeRoot[]) {
this.ctx.lifecycleManager.git?.setSpecs(specs.map((s) => s.absolute))
}
setProjectPreferencesInGlobalCache (args: MutationSetProjectPreferencesInGlobalCacheArgs) {
if (!this.ctx.currentProject) {
throw Error(`Cannot save preferences without currentProject.`)
}
this.api.insertProjectPreferencesToCache(this.ctx.lifecycleManager.projectTitle, args)
}
async codeGenSpec (codeGenCandidate: string, codeGenType: CodeGenType): Promise<NexusGenUnions['GeneratedSpecResult']> {
const project = this.ctx.currentProject
assert(project, 'Cannot create spec without currentProject.')
const getCodeGenPath = () => {
return codeGenType === 'e2e'
? this.ctx.path.join(
project,
codeGenCandidate,
)
: codeGenCandidate
}
const codeGenPath = getCodeGenPath()
const { specPattern = [] } = await this.ctx.project.specPatterns()
const newSpecCodeGenOptions = new SpecOptions({
codeGenPath,
codeGenType,
framework: this.getWizardFrameworkFromConfig(),
isDefaultSpecPattern: await this.ctx.project.getIsDefaultSpecPattern(),
specPattern,
currentProject: this.ctx.currentProject,
specs: this.ctx.project.specs,
})
let codeGenOptions = await newSpecCodeGenOptions.getCodeGenOptions()
const codeGenResults = await codeGenerator(
{ templateDir: templates[codeGenOptions.templateKey], target: codeGenOptions.overrideCodeGenDir || path.parse(codeGenPath).dir },
codeGenOptions,
)
if (!codeGenResults.files[0] || codeGenResults.failed[0]) {
throw (codeGenResults.failed[0] || 'Unable to generate spec')
}
const [newSpec] = codeGenResults.files
const cfg = await this.ctx.project.getConfig()
if (cfg && this.ctx.currentProject) {
const testingType = (codeGenType === 'component') ? 'component' : 'e2e'
await this.setSpecsFoundBySpecPattern({
projectRoot: this.ctx.currentProject,
testingType,
specPattern: cfg.specPattern ?? [],
configSpecPattern: cfg.specPattern ?? [],
excludeSpecPattern: cfg.excludeSpecPattern,
additionalIgnorePattern: cfg.additionalIgnorePattern,
})
}
return {
status: 'valid',
file: { absolute: newSpec.file, contents: newSpec.content },
description: 'Generated spec',
}
}
async setSpecsFoundBySpecPattern ({ projectRoot, testingType, specPattern, configSpecPattern, excludeSpecPattern, additionalIgnorePattern }: FindSpecs<string | string[] | undefined>) {
const toArray = (val?: string | string[]) => val ? typeof val === 'string' ? [val] : val : []
configSpecPattern = toArray(configSpecPattern)
specPattern = toArray(specPattern)
excludeSpecPattern = toArray(excludeSpecPattern) || []
// exclude all specs matching e2e if in component testing
additionalIgnorePattern = toArray(additionalIgnorePattern) || []
if (!specPattern || !configSpecPattern) {
throw Error('could not find pattern to load specs')
}
const specs = await this.ctx.project.findSpecs({
projectRoot,
testingType,
specPattern,
configSpecPattern,
excludeSpecPattern,
additionalIgnorePattern,
})
this.ctx.actions.project.setSpecs(specs)
await this.ctx.project.startSpecWatcher({
projectRoot,
testingType,
specPattern,
configSpecPattern,
excludeSpecPattern,
additionalIgnorePattern,
})
}
setForceReconfigureProjectByTestingType ({ forceReconfigureProject, testingType }: SetForceReconfigureProjectByTestingType) {
const testingTypeToReconfigure = testingType ?? this.ctx.coreData.currentTestingType
if (!testingTypeToReconfigure) {
return
}
this.ctx.update((coreData) => {
coreData.forceReconfigureProject = {
...coreData.forceReconfigureProject,
[testingTypeToReconfigure]: forceReconfigureProject,
}
})
}
async reconfigureProject () {
await this.ctx.actions.browser.closeBrowser()
this.ctx.actions.wizard.resetWizard()
await this.ctx.actions.wizard.initialize()
this.ctx.actions.electron.refreshBrowserWindow()
this.ctx.actions.electron.showBrowserWindow()
}
get defaultE2EPath () {
const projectRoot = this.ctx.currentProject
assert(projectRoot, `Cannot create e2e directory without currentProject.`)
return path.join(projectRoot, 'cypress', 'e2e')
}
async scaffoldIntegration (): Promise<NexusGenObjects['ScaffoldedFile'][]> {
const projectRoot = this.ctx.currentProject
assert(projectRoot, `Cannot create spec without currentProject.`)
const results = await codeGenerator(
{ templateDir: templates['scaffoldIntegration'], target: this.defaultE2EPath },
{},
)
if (results.failed.length) {
throw new Error(`Failed generating files: ${results.failed.map((e) => `${e}`)}`)
}
return results.files.map(({ status, file, content }) => {
return {
status: (status === 'add' || status === 'overwrite') ? 'valid' : 'skipped',
file: { absolute: file, contents: content },
description: 'Generated spec',
}
})
}
async hasNonExampleSpec () {
const specs = this.ctx.project.specs?.map((spec) => spec.relativeToCommonRoot)
switch (this.ctx.coreData.currentTestingType) {
case 'e2e':
return hasNonExampleSpec(templates.scaffoldIntegration, specs)
case 'component':
return specs.length > 0
case null:
return false
default:
throw new Error(`Unsupported testing type ${this.ctx.coreData.currentTestingType}`)
}
}
async pingBaseUrl () {
const baseUrl = (await this.ctx.project.getConfig())?.baseUrl
// Should never happen
if (!baseUrl) {
return
}
const baseUrlWarning = this.ctx.warnings.find((e) => e.cypressError.type === 'CANNOT_CONNECT_BASE_URL_WARNING')
if (baseUrlWarning) {
this.ctx.actions.error.clearWarning(baseUrlWarning.id)
this.ctx.emitter.errorWarningChange()
}
return this.api.isListening(baseUrl)
.catch(() => this.ctx.onWarning(getError('CANNOT_CONNECT_BASE_URL_WARNING', baseUrl)))
}
async switchTestingTypesAndRelaunch (testingType: Cypress.TestingType): Promise<void> {
const isTestingTypeConfigured = this.ctx.lifecycleManager.isTestingTypeConfigured(testingType)
this.ctx.project.setRelaunchBrowser(isTestingTypeConfigured)
this.setAndLoadCurrentTestingType(testingType)
await this.reconfigureProject()
if (testingType === 'e2e' && !isTestingTypeConfigured) {
// E2E doesn't have a wizard, so if we have a testing type on load we just create/update their cypress.config.js.
await this.ctx.actions.wizard.scaffoldTestingType()
}
}
getWizardFrameworkFromConfig (): WizardFrontendFramework | undefined {
const config = this.ctx.lifecycleManager.loadedConfigFile
// If devServer is a function, they are using a custom dev server.
if (!config?.component?.devServer || typeof config?.component?.devServer === 'function') {
return undefined
}
// @ts-ignore - because of the conditional above, we know that devServer isn't a function
return WIZARD_FRAMEWORKS.find((framework) => framework.configFramework === config?.component?.devServer.framework)
}
}