/
project.ts
232 lines (205 loc) · 7.72 KB
/
project.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
import * as fs from 'fs';
import * as path from 'path';
import { prerelease, SemVer } from 'semver';
import yargsParser from 'yargs-parser';
import { getGlobalVariable } from './env';
import { prependToFile, readFile, replaceInFile, writeFile } from './fs';
import { gitCommit } from './git';
import { findFreePort } from './network';
import { installWorkspacePackages, PkgInfo } from './packages';
import { exec, execAndWaitForOutputToMatch, git, ng } from './process';
export function updateJsonFile(filePath: string, fn: (json: any) => any | void) {
return readFile(filePath).then((tsConfigJson) => {
// Remove single and multiline comments
const tsConfig = JSON.parse(tsConfigJson.replace(/\/\*\s(.|\n|\r)*\s\*\/|\/\/.*/g, ''));
const result = fn(tsConfig) || tsConfig;
return writeFile(filePath, JSON.stringify(result, null, 2));
});
}
export function updateTsConfig(fn: (json: any) => any | void) {
return updateJsonFile('tsconfig.json', fn);
}
export async function ngServe(...args: string[]) {
const port = await findFreePort();
await execAndWaitForOutputToMatch(
'ng',
['serve', '--port', String(port), ...args],
/ Compiled successfully./,
);
return port;
}
export async function prepareProjectForE2e(name: string) {
const argv: yargsParser.Arguments = getGlobalVariable('argv');
await git('config', 'user.email', 'angular-core+e2e@google.com');
await git('config', 'user.name', 'Angular CLI E2E');
await git('config', 'commit.gpgSign', 'false');
await git('config', 'core.longpaths', 'true');
if (argv['ng-snapshots'] || argv['ng-tag']) {
await useSha();
}
console.log(`Project ${name} created... Installing packages.`);
await installWorkspacePackages();
await ng('generate', 'e2e', '--related-app-name', name);
const protractorPath = require.resolve('protractor');
const webdriverUpdatePath = require.resolve('webdriver-manager/selenium/update-config.json', {
paths: [protractorPath],
});
const webdriverUpdate = JSON.parse(await readFile(webdriverUpdatePath)) as {
chrome: { last: string };
};
const chromeDriverVersion = webdriverUpdate.chrome.last.match(/chromedriver_([\d|\.]+)/)?.[1];
if (!chromeDriverVersion) {
throw new Error('Could not extract chrome webdriver version.');
}
// Initialize selenium webdriver.
// Often fails the first time so attempt twice if necessary.
const runWebdriverUpdate = () =>
exec(
'node',
'node_modules/protractor/bin/webdriver-manager',
'update',
'--standalone',
'false',
'--gecko',
'false',
'--versions.chrome',
chromeDriverVersion,
);
try {
await runWebdriverUpdate();
} catch {
await runWebdriverUpdate();
}
await useCIChrome(name, 'e2e');
await useCIChrome(name, '');
await useCIDefaults(name);
// Force sourcemaps to be from the root of the filesystem.
await updateJsonFile('tsconfig.json', (json) => {
json['compilerOptions']['sourceRoot'] = '/';
});
await gitCommit('prepare-project-for-e2e');
}
export function useBuiltPackagesVersions(): Promise<void> {
const packages: { [name: string]: PkgInfo } = getGlobalVariable('package-tars');
return updateJsonFile('package.json', (json) => {
json['dependencies'] ??= {};
json['devDependencies'] ??= {};
for (const packageName of Object.keys(packages)) {
if (packageName in json['dependencies']) {
json['dependencies'][packageName] = packages[packageName].version;
} else if (packageName in json['devDependencies']) {
json['devDependencies'][packageName] = packages[packageName].version;
}
}
});
}
export function useSha() {
const argv = getGlobalVariable('argv');
if (argv['ng-snapshots'] || argv['ng-tag']) {
// We need more than the sha here, version is also needed. Examples of latest tags:
// 7.0.0-beta.4+dd2a650
// 6.1.6+4a8d56a
const label = argv['ng-tag'] ? argv['ng-tag'] : '';
const ngSnapshotVersions = require('../ng-snapshot/package.json');
return updateJsonFile('package.json', (json) => {
// Install over the project with snapshot builds.
function replaceDependencies(key: string) {
const missingSnapshots: string[] = [];
Object.keys(json[key] || {})
.filter((name) => name.match(/^@angular\//))
.forEach((name) => {
const pkgName = name.split(/\//)[1];
if (pkgName == 'cli') {
return;
}
if (label) {
json[key][`@angular/${pkgName}`] = `github:angular/${pkgName}-builds${label}`;
} else {
const replacement = ngSnapshotVersions.dependencies[`@angular/${pkgName}`];
if (!replacement) {
missingSnapshots.push(`missing @angular/${pkgName}`);
}
json[key][`@angular/${pkgName}`] = replacement;
}
});
if (missingSnapshots.length > 0) {
throw new Error(
'e2e test with --ng-snapshots requires all angular packages be ' +
'listed in tests/legacy-cli/e2e/ng-snapshot/package.json.\nErrors:\n' +
missingSnapshots.join('\n '),
);
}
}
try {
replaceDependencies('dependencies');
replaceDependencies('devDependencies');
} catch (e) {
return Promise.reject(e);
}
});
} else {
return Promise.resolve();
}
}
export function useCIDefaults(projectName = 'test-project'): Promise<void> {
return updateJsonFile('angular.json', (workspaceJson) => {
// Disable progress reporting on CI to reduce spam.
const project = workspaceJson.projects[projectName];
const appTargets = project.targets || project.architect;
appTargets.build.options.progress = false;
appTargets.test.options.progress = false;
if (appTargets.e2e) {
// Disable auto-updating webdriver in e2e.
appTargets.e2e.options.webdriverUpdate = false;
// Use a random port in e2e.
appTargets.e2e.options.port = 0;
}
if (appTargets.serve) {
// Use a random port in serve.
appTargets.serve.options ??= {};
appTargets.serve.options.port = 0;
}
});
}
export async function useCIChrome(projectName: string, projectDir = ''): Promise<void> {
const protractorConf = path.join(projectDir, 'protractor.conf.js');
const chromePath = require('puppeteer').executablePath();
// Use Puppeteer in protractor if a config is found on the project.
if (fs.existsSync(protractorConf)) {
const protractorPath = require.resolve('protractor');
const webdriverUpdatePath = require.resolve('webdriver-manager/selenium/update-config.json', {
paths: [protractorPath],
});
const webdriverUpdate = JSON.parse(await readFile(webdriverUpdatePath)) as {
chrome: { last: string };
};
const chromeDriverPath = webdriverUpdate.chrome.last;
await replaceInFile(
protractorConf,
`browserName: 'chrome'`,
`browserName: 'chrome',
chromeOptions: {
args: ['--headless'],
binary: String.raw\`${chromePath}\`,
}`,
);
await replaceInFile(
protractorConf,
'directConnect: true,',
`directConnect: true, chromeDriver: String.raw\`${chromeDriverPath}\`,`,
);
}
// Use ChromeHeadless.
return updateJsonFile('angular.json', (workspaceJson) => {
const project = workspaceJson.projects[projectName];
const appTargets = project.targets || project.architect;
appTargets.test.options.browsers = 'ChromeHeadless';
});
}
export function getNgCLIVersion(): SemVer {
const packages: { [name: string]: PkgInfo } = getGlobalVariable('package-tars');
return new SemVer(packages['@angular/cli'].version);
}
export function isPrereleaseCli(): boolean {
return (prerelease(getNgCLIVersion())?.length ?? 0) > 0;
}