forked from microsoft/react-native-macos
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprepublish-check.mjs
More file actions
414 lines (366 loc) · 12.4 KB
/
prepublish-check.mjs
File metadata and controls
414 lines (366 loc) · 12.4 KB
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
// @ts-check
import { spawnSync } from "node:child_process";
import * as fs from "node:fs";
import * as util from "node:util";
const NX_CONFIG_FILE = "nx.json";
const NPM_DEFEAULT_REGISTRY = "https://registry.npmjs.org/"
const NPM_TAG_NEXT = "next";
const NPM_TAG_NIGHTLY = "nightly";
const RNMACOS_LATEST = "react-native-macos@latest";
const RNMACOS_NEXT = "react-native-macos@next";
/**
* @typedef {import("nx/src/config/nx-json").NxReleaseVersionConfiguration} NxReleaseVersionConfiguration;
* @typedef {{
* defaultBase: string;
* release: {
* version: NxReleaseVersionConfiguration;
* };
* }} NxConfig;
* @typedef {{
* "mock-branch"?: string;
* "skip-auth"?: boolean;
* tag?: string;
* update?: boolean;
* verbose?: boolean;
* }} Options;
* @typedef {{
* npmTag: string;
* prerelease?: string;
* isNewTag?: boolean;
* }} TagInfo;
*/
/**
* Exports a variable, `publish_react_native_macos`, to signal that we want to
* enable publishing on Azure Pipelines.
*
* Note that pipelines need to read this variable separately and do the actual
* work to publish bits.
*/
function enablePublishingOnAzurePipelines() {
console.log(`##vso[task.setvariable variable=publish_react_native_macos]1`);
}
/**
* Logs an error message to the console.
* @param {string} message
*/
function error(message) {
console.error("❌", message);
}
/**
* Logs an informational message to the console.
* @param {string} message
*/
function info(message) {
console.log("ℹ️", message);
}
/**
* Returns whether the given branch is considered main branch.
* @param {string} branch
*/
function isMainBranch(branch) {
// There is currently no good way to consistently get the main branch. We
// hardcode the value for now.
return branch === "main";
}
/**
* Returns whether the given branch is considered a stable branch.
* @param {string} branch
*/
function isStableBranch(branch) {
return /^\d+\.\d+-stable$/.test(branch);
}
/**
* Loads Nx configuration.
* @param {string} configFile
* @returns {NxConfig}
*/
function loadNxConfig(configFile) {
const nx = fs.readFileSync(configFile, { encoding: "utf-8" });
return JSON.parse(nx);
}
function verifyNpmAuth(registry = NPM_DEFEAULT_REGISTRY) {
const npmErrorRegex = /npm error code (\w+)/;
const spawnOptions = {
stdio: /** @type {const} */ ("pipe"),
shell: true,
windowsVerbatimArguments: true,
};
const whoamiArgs = ["whoami", "--registry", registry];
const whoami = spawnSync("npm", whoamiArgs, spawnOptions);
if (whoami.status !== 0) {
const error = whoami.stderr.toString();
const m = error.match(npmErrorRegex);
const errorCode = m && m[1];
switch (errorCode) {
case "EINVALIDNPMTOKEN":
throw new Error(`Invalid auth token for npm registry: ${registry}`);
case "ENEEDAUTH":
throw new Error(`Missing auth token for npm registry: ${registry}`);
default:
throw new Error(error);
}
}
const tokenArgs = ["token", "list", "--registry", registry];
const token = spawnSync("npm", tokenArgs, spawnOptions);
if (token.status !== 0) {
const error = token.stderr.toString();
const m = error.match(npmErrorRegex);
const errorCode = m && m[1];
// E403 means the token doesn't have permission to list tokens, but that's
// not required for publishing. Only fail for other error codes.
if (errorCode === "E403") {
info(`Token verification skipped: token doesn't have permission to list tokens (${errorCode})`);
} else {
throw new Error(m ? `Auth token for '${registry}' returned error code ${errorCode}` : error);
}
}
}
/**
* Returns a numerical value for a given version string.
* @param {string} version
* @returns {number}
*/
function versionToNumber(version) {
const [major, minor] = version.split("-")[0].split(".");
return Number(major) * 1000 + Number(minor);
}
/**
* Returns the target branch name. If not targetting any branches (e.g., when
* executing this script locally), `undefined` is returned.
* @returns {string | undefined}
*/
function getTargetBranch() {
// Azure Pipelines
if (process.env["TF_BUILD"] === "True") {
// https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml#build-variables-devops-services
const targetBranch = process.env["SYSTEM_PULLREQUEST_TARGETBRANCH"];
return targetBranch?.replace(/^refs\/heads\//, "");
}
// GitHub Actions
if (process.env["GITHUB_ACTIONS"] === "true") {
// https://docs.github.com/en/actions/learn-github-actions/variables#default-environment-variables
return process.env["GITHUB_BASE_REF"];
}
return undefined;
}
/**
* Returns the current branch name. In a pull request, the target branch name is
* returned.
* @param {Options} options
* @returns {string}
*/
function getCurrentBranch(options) {
const targetBranch = getTargetBranch();
if (targetBranch) {
return targetBranch;
}
// Azure DevOps Pipelines
if (process.env["TF_BUILD"] === "True") {
// https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml#build-variables-devops-services
const sourceBranch = process.env["BUILD_SOURCEBRANCHNAME"];
if (sourceBranch) {
return sourceBranch.replace(/^refs\/heads\//, "");
}
}
// GitHub Actions
if (process.env["GITHUB_ACTIONS"] === "true") {
// https://docs.github.com/en/actions/learn-github-actions/variables#default-environment-variables
const headRef = process.env["GITHUB_HEAD_REF"];
if (headRef) {
return headRef; // For pull requests
}
const ref = process.env["GITHUB_REF"];
if (ref) {
return ref.replace(/^refs\/heads\//, ""); // For push events
}
}
const { "mock-branch": mockBranch } = options;
if (mockBranch) {
return mockBranch;
}
// Depending on how the repo was cloned, HEAD may not exist. We only use this
// method as fallback.
const { stdout } = spawnSync("git", ["rev-parse", "--abbrev-ref", "HEAD"]);
return stdout.toString().trim();
}
/**
* Returns the latest published version of `react-native-macos` from npm.
* @param {"latest" | "next"} tag
* @returns {number}
*/
function getPublishedVersion(tag) {
const { stdout } = spawnSync("npm", ["view", `react-native-macos@${tag}`, "version"]);
return versionToNumber(stdout.toString().trim());
}
/**
* Returns the npm tag and prerelease identifier for the specified branch.
*
* @privateRemarks
* Note that the current implementation treats minor versions as major. If
* upstream ever decides to change the versioning scheme, we will need to make
* changes accordingly.
*
* @param {string} branch
* @param {Options} options
* @param {typeof info} log
* @returns {TagInfo}
*/
function getTagForStableBranch(branch, { tag }, log) {
if (!isStableBranch(branch)) {
throw new Error("Expected a stable branch");
}
const latestVersion = getPublishedVersion("latest");
const currentVersion = versionToNumber(branch);
log(`${RNMACOS_LATEST}: ${latestVersion}`);
log(`Current version: ${currentVersion}`);
// Patching latest version
if (currentVersion === latestVersion) {
const npmTag = "latest";
log(`Expected npm tag: ${npmTag}`);
return { npmTag };
}
// Demoting or patching an older stable version
if (currentVersion < latestVersion) {
const npmTag = "v" + branch;
log(`Expected npm tag: ${npmTag}`);
// If we're demoting a branch, we will need to create a new tag. This will
// make Nx trip if we don't specify a fallback. In all other scenarios, the
// tags should exist and therefore prefer it to fail.
return { npmTag, isNewTag: true };
}
// Publishing a new latest version
if (tag === "latest") {
log(`Expected npm tag: ${tag}`);
return { npmTag: tag };
}
// Publishing a release candidate
const nextVersion = getPublishedVersion("next");
log(`${RNMACOS_NEXT}: ${nextVersion}`);
log(`Expected npm tag: ${NPM_TAG_NEXT}`);
if (currentVersion < nextVersion) {
throw new Error(`Current version cannot be a release candidate because it is too old: ${currentVersion} < ${nextVersion}`);
}
return { npmTag: NPM_TAG_NEXT, prerelease: "rc" };
}
/**
* Verifies the configuration and enables publishing on CI.
* @param {NxConfig} config
* @param {string} currentBranch
* @param {TagInfo} tag
* @param {Options} options
* @returns {asserts config is NxConfig["release"]}
*/
function enablePublishing(config, currentBranch, { npmTag: tag, prerelease, isNewTag }, options) {
/** @type {string[]} */
const errors = [];
const { defaultBase, release } = config;
// `defaultBase` determines what we diff against when looking for tags or
// released version and must therefore be set to either the main branch or one
// of the stable branches.
if (currentBranch !== defaultBase) {
errors.push(`'defaultBase' must be set to '${currentBranch}'`);
config.defaultBase = currentBranch;
}
// Determines whether we need to add "nightly" or "rc" to the version string.
const { versionActionsOptions = {} } = release.version;
if (versionActionsOptions.preid !== prerelease) {
if (prerelease) {
errors.push(`'release.version.versionActionsOptions.preid' must be set to '${prerelease}'`);
versionActionsOptions.preid = prerelease;
} else {
errors.push(`'release.version.versionActionsOptions.preid' must be removed`);
versionActionsOptions.preid = undefined;
}
}
// What the published version should be tagged as e.g., "latest" or "nightly".
const currentVersionResolverMetadata = /** @type {{ tag?: string }} */ (versionActionsOptions.currentVersionResolverMetadata || {});
if (currentVersionResolverMetadata.tag !== tag) {
errors.push(`'release.version.versionActionsOptions.currentVersionResolverMetadata.tag' must be set to '${tag}'`);
versionActionsOptions.currentVersionResolverMetadata ??= {};
/** @type {any} */ (versionActionsOptions.currentVersionResolverMetadata).tag = tag;
}
// If we're demoting a branch, we will need to create a new tag. This will
// make Nx trip if we don't specify a fallback. In all other scenarios, the
// tags should exist and therefore prefer it to fail.
if (isNewTag) {
if (versionActionsOptions.fallbackCurrentVersionResolver !== "disk") {
errors.push("'release.version.versionActionsOptions.fallbackCurrentVersionResolver' must be set to 'disk'");
versionActionsOptions.fallbackCurrentVersionResolver = "disk";
}
} else if (typeof versionActionsOptions.fallbackCurrentVersionResolver === "string") {
errors.push("'release.version.versionActionsOptions.fallbackCurrentVersionResolver' must be removed");
versionActionsOptions.fallbackCurrentVersionResolver = undefined;
}
if (errors.length > 0) {
errors.forEach(error);
throw new Error("Nx Release is not correctly configured for the current branch");
}
if (options["skip-auth"]) {
info("Skipped npm auth validation");
} else {
verifyNpmAuth();
}
// Don't enable publishing in PRs
if (!getTargetBranch()) {
enablePublishingOnAzurePipelines();
}
}
/**
* @param {Options} options
* @returns {number}
*/
function main(options) {
const branch = getCurrentBranch(options);
if (!branch) {
error("Could not get current branch");
return 1;
}
const logger = options.verbose ? info : () => undefined;
const config = loadNxConfig(NX_CONFIG_FILE);
try {
if (isMainBranch(branch)) {
const info = { npmTag: NPM_TAG_NIGHTLY, prerelease: NPM_TAG_NIGHTLY };
enablePublishing(config, branch, info, options);
} else if (isStableBranch(branch)) {
const tag = getTagForStableBranch(branch, options, logger);
enablePublishing(config, branch, tag, options);
}
} catch (e) {
if (options.update) {
const fd = fs.openSync(NX_CONFIG_FILE, "w");
fs.writeSync(fd, JSON.stringify(config, undefined, 2));
fs.writeSync(fd, "\n");
fs.closeSync(fd)
} else {
error(`${e.message}`);
}
return 1;
}
return 0;
}
const { values } = util.parseArgs({
args: process.argv.slice(2),
options: {
"mock-branch": {
type: "string",
},
"skip-auth": {
type: "boolean",
default: false,
},
tag: {
type: "string",
default: NPM_TAG_NEXT,
},
update: {
type: "boolean",
default: false,
},
verbose: {
type: "boolean",
default: false,
},
},
strict: true,
});
process.exitCode = main(values);