forked from eclipse-zenoh/ci
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcargo.ts
More file actions
442 lines (388 loc) · 14.4 KB
/
cargo.ts
File metadata and controls
442 lines (388 loc) · 14.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
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
import * as os from "os";
import { join } from "path";
import * as core from "@actions/core";
import * as cache from "@actions/cache";
import { TOML } from "./toml";
import { sh, CommandOptions } from "./command";
import { config } from "./config";
import * as cargo from "./cargo";
const toml = await TOML.init();
export type Package = {
name: string;
version: string;
manifestPath: string;
publish?: false;
workspaceDependencies: WorkspaceDependency[];
};
export type WorkspaceDependency = {
name: string;
req: string;
path: string;
};
type CargoMetadataDependency = {
name: string;
req: string;
path?: string;
[key: string]: unknown;
};
type CargoMetadataPackage = {
name: string;
version: string;
manifest_path: string;
dependencies: CargoMetadataDependency[];
publish: string[] | null;
[key: string]: unknown;
};
type CargoMetadata = {
packages: CargoMetadataPackage[];
};
/**
* Uses the cargo-metadata command to list all packages in a Cargo workspace or crate.
* @param path Path to the Cargo workspace or crate.
* @returns The list of Cargo packages present in the workspace or crate.
*/
export function packages(path: string): Package[] {
const metadataContents = sh("cargo metadata --no-deps --format-version=1", { cwd: path });
const metadata = JSON.parse(metadataContents) as CargoMetadata;
const result = [] as Package[];
for (const elem of metadata.packages) {
result.push({
name: elem.name,
version: elem.version,
manifestPath: elem.manifest_path,
publish: elem.publish == null ? undefined : false,
workspaceDependencies: elem.dependencies
.filter(dep => "path" in dep)
.map(dep => ({
name: dep.name,
req: dep.req,
path: dep.path,
})),
});
}
return result;
}
/**
* Yields packages in topological (suitable for publishing) order in a workspace.
* @param path Path to the Cargo workspace.
*/
export function* packagesOrdered(path: string): Generator<Package> {
const allPackages = packages(path);
const seen = [];
const isReady = (package_: Package) => package_.workspaceDependencies.every(dep => seen.includes(dep.name));
while (allPackages.length != 0) {
for (const [index, package_] of allPackages.entries()) {
if (isReady(package_)) {
seen.push(package_.name);
allPackages.splice(index, 1);
yield package_;
}
}
}
}
type CargoManifestPackage = {
version: string | { workspace: boolean };
metadata?: {
deb?: CargoManifestMetadataDebianVariant | { variants: { [key: string]: CargoManifestMetadataDebianVariant } };
};
};
type CargoManifestMetadataDebianVariant = {
name: string;
depends?: string;
};
type CargoManifestDependencyTable = {
version: string;
git?: string;
branch?: string;
registry?: string;
};
type CargoManifestDependencies = {
[key: string]: string | CargoManifestDependencyTable;
};
type CargoManifest = {
package: CargoManifestPackage;
dependencies: CargoManifestDependencies;
};
/**
* Bump this workspaces's version to @param version.
*
* This function assumes that the workspace's root manifest is either (1) a
* virtual manifest from which all workspace members inherit their version (e.g.
* eclipse-zenoh/zenoh and eclipse-zenoh/zenoh-plugin-influxdb), or (2) a
* manifest without a workspace section with only one member (e.g.
* eclipse-zenoh/zenoh-plugin-webserver).
*
* @param path Path to the Cargo workspace.
* @param version New version.
*/
export async function bump(path: string, version: string) {
core.startGroup(`Bumping package versions in ${path} to ${version}`);
const manifestPath = `${path}/Cargo.toml`;
const manifestRaw = toml.get(manifestPath);
if ("workspace" in manifestRaw) {
await toml.set(manifestPath, ["workspace", "package", "version"], version);
} else {
await toml.set(manifestPath, ["package", "version"], version);
}
core.endGroup();
}
/**
* Bumps select workspace dependencies to @param version.
*
* This function assumes that the workspace's root manifest is either (1) a
* virtual manifest from which all workspace members inherit their dependencies
* (e.g. eclipse-zenoh/zenoh and eclipse-zenoh/zenoh-plugin-influxdb), or (2) a
* manifest without a workspace section with only one member (e.g.
* eclipse-zenoh/zenoh-plugin-webserver). It also assumes that all matching
* dependencies define a version, a git repository remote and a git branch.
*
* @param path Path to the Cargo workspace.
* @param pattern A regular expression that matches the dependencies to be
* @param version New version.
* @param git Git repository location.
* @param branch Branch of git repository location. bumped to @param version.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export async function bumpDependencies(path: string, pattern: RegExp, version: string, _branch?: string) {
core.startGroup(`Bumping ${pattern} dependencies in ${path} to ${version}`);
const manifestPath = `${path}/Cargo.toml`;
const manifestRaw = toml.get(manifestPath);
let manifest: CargoManifest;
let prefix: string[];
if ("workspace" in manifestRaw) {
prefix = ["workspace"];
manifest = manifestRaw["workspace"] as CargoManifest;
} else {
prefix = [];
manifest = manifestRaw as CargoManifest;
}
for (const dep in manifest.dependencies) {
if (pattern.test(dep)) {
await toml.set(manifestPath, prefix.concat("dependencies", dep, "version"), version);
// FIXME(fuzzypixelz): Previously, we set the branch of the git source in dependencies,
// but as all dependencies are assumed to be on crates.io anyway, this is not necessary.
// Still, the API of all related actions/workflows should be updated to reflect this.
//
// if (branch != undefined) {
// await toml.set(manifestPath, prefix.concat("dependencies", dep, "branch"), branch);
// }
await toml.unset(manifestPath, prefix.concat("dependencies", dep, "git"));
await toml.unset(manifestPath, prefix.concat("dependencies", dep, "branch"));
}
}
for (const package_ of packages(path)) {
const manifest = toml.get(package_.manifestPath) as CargoManifest;
if (
"metadata" in manifest.package &&
"deb" in manifest.package.metadata &&
"depends" in manifest.package.metadata.deb &&
manifest.package.metadata.deb.depends != "$auto" &&
pattern.test(manifest.package.metadata.deb.name)
) {
const deb = manifest.package.metadata.deb;
const depends = deb.depends.replaceAll(/\(=[^\(\)]+\)/g, `(=${cargo.toDebianVersion(version)})`);
core.info(`Changing ${deb.depends} to ${depends} in ${package_.name}`);
await toml.set(package_.manifestPath, ["package", "metadata", "deb", "depends"], depends);
}
}
core.endGroup();
}
/**
* Sets the Cargo registry of select dependencies.
*
* @param path Path to the Cargo workspace.
* @param pattern A regular expression that matches the dependencies to be
* switched to using @param registry.
* @param registry The name of the Cargo alternative registry.
*/
export async function setRegistry(path: string, pattern: RegExp, registry: string): Promise<void> {
core.startGroup(`Changing ${pattern} dependencies' registry ${registry}`);
const manifestPath = `${path}/Cargo.toml`;
const manifestRaw = toml.get(manifestPath);
let manifest: CargoManifest;
let prefix: string[];
if ("workspace" in manifestRaw) {
prefix = ["workspace"];
manifest = manifestRaw["workspace"] as CargoManifest;
} else {
prefix = [];
manifest = manifestRaw as CargoManifest;
}
for (const dep in manifest.dependencies) {
if (pattern.test(dep)) {
await toml.set(manifestPath, prefix.concat("dependencies", dep, "registry"), registry);
// NOTE: Only one of `git` or `registry` is allowed, otherwise the specification is ambiguous
await toml.unset(manifestPath, prefix.concat("dependencies", dep, "git"));
await toml.unset(manifestPath, prefix.concat("dependencies", dep, "branch"));
}
}
core.endGroup();
}
/**
* Sets the git/branch config of select dependencies.
*
* @param path Path to the Cargo workspace.
* @param pattern A regular expression that matches the dependencies to be
* @param gitUrl git url to set in Cargo.toml dependency
* @param gitBranch git branch to set in Cargo.toml dependency
* updated
*/
export async function setGitBranch(path: string, pattern: RegExp, gitUrl: string, gitBranch: string): Promise<void> {
core.startGroup(`Setting ${pattern} dependencies' git/branch config`);
const manifestPath = `${path}/Cargo.toml`;
const manifestRaw = toml.get(manifestPath);
let manifest: CargoManifest;
let prefix: string[];
if ("workspace" in manifestRaw) {
prefix = ["workspace"];
manifest = manifestRaw["workspace"] as CargoManifest;
} else {
prefix = [];
manifest = manifestRaw as CargoManifest;
}
for (const dep in manifest.dependencies) {
if (pattern.test(dep)) {
// if the dep has a path set or is part of workspace, don't set the git/branch to avoid ambiguities
if (
!toml.get(manifestPath, prefix.concat("dependencies", dep, "path")) ||
!toml.get(manifestPath, prefix.concat("dependencies", dep, "workspace"))
) {
await toml.set(manifestPath, prefix.concat("dependencies", dep, "git"), gitUrl);
await toml.set(manifestPath, prefix.concat("dependencies", dep, "branch"), gitBranch);
}
}
}
}
/**
* Stores Cargo registry configuration in `.cargo/config.toml`.
* @param path Path to the Cargo workspace.
* @param name Name of the Cargo alternative registry.
* @param index Index of the Cargo alternative registry.
*/
export async function configRegistry(path: string, name: string, index: string) {
const configPath = `${path}/.cargo/config.toml`;
await toml.set(configPath, ["registries", name, "index"], index);
}
/**
* Returns a list of all workspace packages which contain Debian package metadata.
* @param path Path to the Cargo workspace.
*/
export function packagesDebian(path: string): Package[] {
const result = [] as Package[];
for (const package_ of packages(path)) {
const manifestRaw = toml.get(package_.manifestPath);
const manifest = ("workspace" in manifestRaw ? manifestRaw["workspace"] : manifestRaw) as CargoManifest;
if ("metadata" in manifest.package && "deb" in manifest.package.metadata) {
result.push(package_);
}
}
return result;
}
export function installBinaryFromGit(name: string, gitUrl: string, gitBranch: string) {
sh(`cargo +stable install --git ${gitUrl} --branch ${gitBranch} ${name} --locked`);
}
/**
* Installs a cargo binary by compiling it from source using `cargo install`.
* The executable is cached using GitHub's `@actions/cache`.
* @param name Name of the cargo binary on crates.io
*/
export async function installBinaryCached(name: string) {
if (process.env["GITHUB_ACTIONS"] != undefined) {
const paths = [join(os.homedir(), ".cargo", "bin")];
const version = config.lock.cratesio[name];
const key = `${os.platform()}-${os.release()}-${os.arch()}-${name}-${version}`;
// NOTE: We specify the Stable toolchain to override the current Rust
// toolchain file in the current directory, as the caller can use this
// function with an arbitrary Rust toolchain, often resulting in build
// failure
const hit = await cache.restoreCache(paths, key);
if (hit == undefined) {
sh(`cargo +stable install ${name} --force`);
await cache.saveCache(paths, key);
}
} else {
sh(`cargo +stable install ${name}`);
}
}
type CrossManifest = {
target: { [target: string]: { image: string } };
};
export function build(path: string, target: string) {
const crossManifest = toml.get(join(path, "Cross.toml")) as CrossManifest;
sh(`rustup target add ${target}`, { cwd: path });
const command = target in crossManifest.target ? ["cross"] : ["cargo"];
command.push("build", "--release", "--bins", "--lib", "--target", target);
sh(command.join(" "), { cwd: path });
}
export function hostTarget(): string {
return sh("rustc --version --verbose").match(/host: (?<target>.*)/).groups["target"];
}
export function buildDebian(path: string, target: string, version: string) {
for (const package_ of packagesDebian(path)) {
const manifest = toml.get(package_.manifestPath) as CargoManifest;
if ("variants" in manifest.package.metadata.deb) {
for (const variant in manifest.package.metadata.deb.variants) {
sh(
`cargo deb --no-build --no-strip \
--target ${target} \
--package ${package_.name} \
--deb-version ${cargo.toDebianVersion(version)} \
--variant ${variant}`,
{
cwd: path,
},
);
}
} else {
sh(
`cargo deb --no-build --no-strip \
--target ${target} \
--package ${package_.name} \
--deb-version ${cargo.toDebianVersion(version)}`,
{
cwd: path,
},
);
}
}
}
/**
* Transforms a version number to a version number that conforms to the Debian Policy.
* @param version Version number.
* @param revision Package revision number.
* @returns Modified version.
*/
export function toDebianVersion(version: string, revision?: number): string {
let debVersion = version;
// Check if version is semver or cmake version
if (version.includes("-")) {
// HACK(fuzzypixelz): This is an oversimplification of the Debian Policy
debVersion = `${version.replace("-", "~")}-${revision ?? 1}`;
} else {
// check cmake version has tweak component
if (version.split(".").length == 4) {
if (version.endsWith(".0")) {
const pos = version.lastIndexOf(".0");
debVersion = `${version.substring(0, pos)}~dev-${revision ?? 1}`;
} else if (parseInt(version.substring(version.lastIndexOf(".") + 1)) > 0) {
const pos = version.lastIndexOf(".");
debVersion = `${version.substring(0, pos)}~pre.${version.substring(pos + 1)}-${revision ?? 1}`;
}
}
}
return `${debVersion}`;
}
/**
* Check if Package is already published
* @param pkg Package to check.
*/
export function isPublished(pkg: Package, options?: CommandOptions): boolean {
options.check = false;
// Hackish but registries don't have a stable api anyway.
const results = sh(`cargo search ${pkg.name}`, options);
if (!results || results.startsWith("error:")) {
return false;
}
const publishedVersion = results.split("\n").at(0).match(/".*"/g).at(0).slice(1, -1);
return publishedVersion === pkg.version;
}