Repository navigation
Expand file tree
/
Copy pathrust-release.mjs
More file actions
263 lines (245 loc) · 11.8 KB
/
Copy pathrust-release.mjs
File metadata and controls
263 lines (245 loc) · 11.8 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
// The Rust crates' part of a release (ADR-0065 Amendment 3): whether this cut publishes them,
// in what order, and the version edit that puts them on the shared line.
//
// Pure functions, so `scripts/test-rust-release.mjs` can hold every rule to cases;
// `scripts/release.mjs` supplies what git, cargo and crates.io answer.
//
// The rules are the ones every registry already follows (docs/RELEASING.md):
//
// - Publish what changed. The crates publish only when a file they ship changed since the last
// `rust-v<version>` tag, and adopt the shared version when they do, skipping the numbers they
// sat out. With no such tag the crates have never shipped, so the cut publishes them.
// - A change to `expected-registry.json` (the vocabulary every port byte-matches) publishes
// every registry, the crates included, changed file or not.
// - The crates publish in dependency order, each after the crates it depends on, because
// crates.io refuses a crate whose dependency is not yet there.
/**
* The part of `cargo metadata --format-version 1 --no-deps` the publish order reads.
*
* @typedef {{
* workspace_members?: string[],
* packages: {
* id: string,
* name: string,
* publish?: string[] | null,
* dependencies: {name: string, kind?: string | null}[],
* }[],
* }} CargoMetadata
*/
/** The workspace that holds the crates, relative to the repository root. */
export const RUST_DIR = "server/rust";
/** The tag a release cuts for the crates: `rust-v1.3.0`. */
export const RUST_TAG_PREFIX = "rust-v";
/** The manifest whose change makes every registry publish. */
export const EXPECTED_REGISTRY = "fixtures/registry-conformance/expected-registry.json";
/** What a crate directory holds that is not shipped in it: tests, examples, benches, baselines. */
const NOT_SHIPPED = new Set(["tests", "examples", "benches", "baselines"]);
/**
* Whether a repository path is part of what the Rust crates ship: a crate's sources, build
* script, data, manifest, README or licence, or the workspace manifest and lockfile. A
* crate's tests, examples, benches and benchmark baselines are not.
*
* @param {string} path
* @returns {boolean}
*/
export function isRustProductPath(path) {
const prefix = `${RUST_DIR}/`;
if (!path.startsWith(prefix)) return false;
const parts = path.slice(prefix.length).split("/");
if (parts.length === 1) return parts[0] === "Cargo.toml" || parts[0] === "Cargo.lock";
return !NOT_SHIPPED.has(parts[1] ?? "");
}
/**
* `1.3.0` or `1.3.0-rc.2` as numbers to compare: a final release sorts after its candidates.
*
* @param {string} v
* @returns {number[] | null}
*/
function versionKey(v) {
const m = v.match(/^(\d+)\.(\d+)\.(\d+)(?:-rc\.(\d+))?$/);
if (!m) return null;
return [Number(m[1]), Number(m[2]), Number(m[3]), m[4] === undefined ? Infinity : Number(m[4])];
}
/**
* @param {number[]} a
* @param {number[]} b
* @returns {number}
*/
function compareKeys(a, b) {
for (let i = 0; i < 4; i++) {
const x = a[i] ?? 0;
const y = b[i] ?? 0;
if (x !== y) return x < y ? -1 : 1;
}
return 0;
}
/**
* The newest `rust-v*` tag among `tags`, or null when the crates have never been tagged.
*
* @param {string[]} tags
* @returns {string | null}
*/
export function newestRustTag(tags) {
/** @type {{tag: string, key: number[]} | null} */
let best = null;
for (const t of tags) {
if (!t.startsWith(RUST_TAG_PREFIX)) continue;
const key = versionKey(t.slice(RUST_TAG_PREFIX.length));
if (key && (best === null || compareKeys(key, best.key) > 0)) best = { tag: t, key };
}
return best?.tag ?? null;
}
/**
* Whether this cut publishes the crates.
*
* @param {{lastTag: string|null, changedPaths: string[], mode?: "auto"|"publish"|"skip"}} input
* `changedPaths` are the repository paths changed since `lastTag` (ignored without one);
* `mode` is the release's `--crates` choice, `auto` unless the person cutting it overrode.
* @returns {{publish: boolean, reason: string}}
*/
export function rustPublishDecision({ lastTag, changedPaths, mode = "auto" }) {
if (mode === "publish") return { publish: true, reason: "--crates=publish" };
if (mode === "skip") return { publish: false, reason: "--crates=skip" };
if (mode !== "auto") throw new Error(`unknown --crates mode "${mode}" (auto, publish or skip)`);
if (lastTag === null) return { publish: true, reason: "the crates have never been published" };
if (changedPaths.includes(EXPECTED_REGISTRY)) {
return { publish: true, reason: `${EXPECTED_REGISTRY} changed since ${lastTag}, which publishes every registry` };
}
const shipped = changedPaths.filter(isRustProductPath);
if (shipped.length > 0) {
const more = shipped.length > 3 ? ` and ${shipped.length - 3} more` : "";
return { publish: true, reason: `changed since ${lastTag}: ${shipped.slice(0, 3).join(", ")}${more}` };
}
return { publish: false, reason: `no file the crates ship changed since ${lastTag}` };
}
/**
* The publishable workspace crates in the order they must publish: each after every crate it
* depends on. `metadata` is what `cargo metadata --format-version 1 --no-deps` prints. A
* dev-dependency does not order anything: cargo leaves one without a version out of the
* published manifest, and one with a version needs only to exist by the time someone runs
* the crate's tests. Ties break on the name, so the order is the same on every machine.
*
* @param {CargoMetadata} metadata
* @returns {string[]}
* @throws when the crates depend on each other in a cycle.
*/
export function rustPublishOrder(metadata) {
const members = new Set(metadata.workspace_members ?? []);
const crates = metadata.packages.filter(
(p) => (members.size === 0 || members.has(p.id)) && !(Array.isArray(p.publish) && p.publish.length === 0),
);
const names = new Set(crates.map((p) => p.name));
const needs = new Map(crates.map((p) => [p.name, new Set(
p.dependencies
.filter((d) => d.kind !== "dev" && names.has(d.name) && d.name !== p.name)
.map((d) => d.name),
)]));
/** @type {string[]} */
const order = [];
while (needs.size > 0) {
const ready = [...needs].filter(([, deps]) => [...deps].every((d) => !needs.has(d))).map(([n]) => n).sort();
if (ready.length === 0) {
throw new Error(`the Rust crates depend on each other in a cycle: ${[...needs.keys()].sort().join(", ")}`);
}
for (const n of ready) { order.push(n); needs.delete(n); }
}
return order;
}
/**
* A crate manifest with every version the release sets moved to `version`: the
* `[workspace.package]` version, and the version requirement on each dependency given by
* `path` (a sibling crate). Nothing else in the text changes.
*
* @param {string} text
* @param {string} version
* @returns {string}
*/
export function bumpRustManifest(text, version) {
let out = "";
let section = "";
for (const line of text.split(/(?<=\n)/)) {
const header = line.match(/^\s*\[([^\]]+)\]\s*$/);
if (header) section = (header[1] ?? "").trim();
let next = line;
if (section === "workspace.package") next = next.replace(/^(\s*version\s*=\s*")[^"]*(")/, `$1${version}$2`);
if (/\bpath\s*=/.test(next)) next = next.replace(/(\bversion\s*=\s*")[^"]*(")/, `$1${version}$2`);
out += next;
}
return out;
}
/**
* A crate manifest cut as a pre-release candidate for a PRIVATE registry: `bumpRustManifest`'s
* version edit, plus `registry = "<name>"` on every sibling dependency given by `path`. Without
* it a published crate's sibling dependency names no registry at all, and cargo resolves it from
* crates.io, where no candidate exists. Nothing else in the text changes.
*
* @param {string} text
* @param {string} version
* @param {string} registry the name the private registry is configured under in cargo
* @returns {string}
*/
export function candidateRustManifest(text, version, registry) {
return bumpRustManifest(text, version).split(/(?<=\n)/).map((line) =>
/\bpath\s*=/.test(line) && !/\bregistry\s*=/.test(line)
? line.replace(/(\bversion\s*=\s*"[^"]*")/, `$1, registry = "${registry}"`)
: line).join("");
}
/**
* Whether crates.io already holds `version` of a crate, from the JSON its
* `/api/v1/crates/<name>` endpoint answers. A crate that does not exist answers 404, which
* the caller reads as free before calling this.
*
* @param {{versions?: {num: string}[]}} json
* @param {string} version
* @returns {boolean}
*/
export function crateVersionTaken(json, version) {
return (json.versions ?? []).some((v) => v.num === version);
}
/**
* The environment variable cargo reads a named registry's index address from.
* @param {string} registry
* @returns {string}
*/
export const cargoIndexVar = (registry) => `CARGO_REGISTRIES_${registry.toUpperCase().replaceAll("-", "_")}_INDEX`;
/** Where crates.io lives, in each form cargo accepts: the sparse index and the retired git index. */
const CRATES_IO = /(^|[/@.])(crates\.io|index\.crates\.io|crates-io)([/:.]|$)|rust-lang\/crates\.io-index/;
/**
* Refuse a `cargo publish` invocation that could reach anywhere but the private registry.
* `args` is the argument list after `cargo publish`; `env` is the child environment.
* It proves the target from what cargo will be GIVEN, because a dry run prints no target.
*
* @param {{args: string[], env: Record<string, string | undefined>, registry: string, expectedIndex: string}} input
* @throws when the invocation is not bound to exactly the expected private registry.
*/
export function assertCargoPublishTarget({ args, env, registry, expectedIndex }) {
const at = args.indexOf("--registry");
if (at === -1 || args[at + 1] !== registry || args.indexOf("--registry", at + 1) !== -1)
throw new Error(`cargo publish must name exactly one --registry, "${registry}"; got [${args.join(" ")}]`);
const banned = args.filter((a) => a === "--index" || a === "--token" || a.startsWith("--index=") || a.startsWith("--token="));
if (banned.length) throw new Error(`cargo publish must not set ${banned.join(", ")}: the target is the named registry`);
const index = env[cargoIndexVar(registry)];
if (index !== expectedIndex)
throw new Error(`cargo would read registry "${registry}" from ${index ?? "nothing"}, not the configured ${expectedIndex}`);
if (CRATES_IO.test(expectedIndex)) throw new Error(`the expected index ${expectedIndex} is crates.io`);
for (const v of ["CARGO_REGISTRY_TOKEN", "CARGO_REGISTRY_DEFAULT", "CARGO_REGISTRIES_CRATES_IO_TOKEN", "CARGO_REGISTRIES_CRATES_IO_INDEX"])
if (env[v]) throw new Error(`${v} is set in the cargo environment: it could redirect or authorize a crates.io publish`);
}
/**
* Read what cargo printed and refuse anything that names a target other than the private registry.
* Cargo reports a publish as ``Uploaded <crate> to registry `<name>` `` and
* ``Published <crate> at registry `<name>` ``, and states a registry's index address in a
* ``name of alternative registry `<index>` `` note; each must match. A dry run prints none of the
* first two, so `published` demands them for a real publish.
*
* @param {{output: string, registry: string, expectedIndex: string, published?: boolean}} input
* @throws when the output names another registry, or a real publish never confirms this one.
*/
export function assertCargoPublishOutput({ output, registry, expectedIndex, published = false }) {
for (const m of output.matchAll(/\b(?:Uploaded|Published)\b[^\n]*?\b(?:to|at) registry `([^`]*)`/g))
if (m[1] !== registry) throw new Error(`cargo reports a publish to registry \`${m[1]}\`, not \`${registry}\`: ${m[0].trim()}`);
for (const m of output.matchAll(/alternative registry `([^`]*)`/g))
if (m[1] !== expectedIndex) throw new Error(`cargo reports registry index ${m[1]}, not the configured ${expectedIndex}`);
if (published && !new RegExp(`Published [^\\n]* at registry \`${registry}\``).test(output))
throw new Error(`cargo never confirmed a publish to registry \`${registry}\``);
}