Debian Codegraph @

ci/publish.rs

raw
1 //! Helper script to publish this repository's suites of crates
2 //!
3 //! In a nutshell
4 //!
5 //! * `./publish bump` - bump crate versions as a major release
6 //! * `./publish bump-patch` - bump crate versions as a patch release
7 //! * `./publish publish` - actually publish crates to crates.io
8 //! * `./publish verify` - verify that crates can be published, like a dry run
9
10 use std::collections::HashMap;
11 use std::env;
12 use std::fs;
13 use std::path::{Path, PathBuf};
14 use std::process::{Command, Output, Stdio};
15 use std::thread;
16 use std::time::Duration;
17
18 // note that this list must be topologically sorted by dependencies
19 const CRATES_TO_PUBLISH: &[&str] = &[
20 "wasmparser",
21 "wasmprinter",
22 "wasm-encoder",
23 "wast",
24 "wat",
25 "wasm-smith",
26 "wasm-mutate",
27 "wasm-shrink",
28 "wit-parser",
29 "wasm-metadata",
30 "wit-component",
31 "wit-encoder",
32 "wasm-compose",
33 "wit-smith",
34 "json-from-wast",
35 "wasm-wave",
36 "wasm-tools",
37 ];
38
39 // These crates are "API stable" and breaking changes are vetted during review.
40 // Bumps to their version number do not increment the major version number.
41 // Currently these are `1.X.Y` versioned crates.
42 const API_STABLE_CRATES: &[&str] = &["wasm-tools", "wat"];
43
44 struct Workspace {
45 version: String,
46 }
47
48 struct Crate {
49 manifest: PathBuf,
50 name: String,
51 version: String,
52 publish: bool,
53 workspace_version: Option<String>,
54 }
55
56 fn main() {
57 let mut crates = Vec::new();
58 let root = read_crate(None, "./Cargo.toml".as_ref());
59 let ws = Workspace {
60 version: root.workspace_version.clone().unwrap(),
61 };
62 crates.push(root);
63 find_crates("crates".as_ref(), &ws, &mut crates);
64
65 let pos = CRATES_TO_PUBLISH
66 .iter()
67 .enumerate()
68 .map(|(i, c)| (*c, i))
69 .collect::<HashMap<_, _>>();
70 crates.sort_by_key(|krate| pos.get(&krate.name[..]));
71
72 match &env::args().nth(1).expect("must have one argument")[..] {
73 name @ "bump" | name @ "bump-patch" => {
74 for krate in crates.iter() {
75 bump_version(&krate, &crates, name == "bump-patch");
76 }
77 // update the lock file
78 assert!(
79 Command::new("cargo")
80 .arg("fetch")
81 .status()
82 .unwrap()
83 .success()
84 );
85 }
86
87 "publish" => {
88 // We have so many crates to publish we're frequently either
89 // rate-limited or we run into issues where crates can't publish
90 // successfully because they're waiting on the index entries of
91 // previously-published crates to propagate. This means we try to
92 // publish in a loop and we remove crates once they're successfully
93 // published. Failed-to-publish crates get enqueued for another try
94 // later on.
95 for _ in 0..10 {
96 crates.retain(|krate| !publish(krate));
97
98 if crates.is_empty() {
99 break;
100 }
101
102 println!(
103 "{} crates failed to publish, waiting for a bit to retry",
104 crates.len(),
105 );
106 thread::sleep(Duration::from_secs(40));
107 }
108
109 assert!(crates.is_empty(), "failed to publish all crates");
110 }
111
112 "verify" => {
113 verify(&crates);
114 }
115
116 s => panic!("unknown command: {}", s),
117 }
118 }
119
120 fn find_crates(dir: &Path, ws: &Workspace, dst: &mut Vec<Crate>) {
121 if dir.join("Cargo.toml").exists() {
122 let krate = read_crate(Some(ws), &dir.join("Cargo.toml"));
123 if !krate.publish || CRATES_TO_PUBLISH.iter().any(|c| krate.name == *c) {
124 dst.push(krate);
125 } else {
126 panic!("failed to find {:?} in whitelist or blacklist", krate.name);
127 }
128 }
129
130 for entry in dir.read_dir().unwrap() {
131 let entry = entry.unwrap();
132 if entry.file_type().unwrap().is_dir() {
133 find_crates(&entry.path(), ws, dst);
134 }
135 }
136 }
137
138 fn read_crate(ws: Option<&Workspace>, manifest: &Path) -> Crate {
139 let mut name = None;
140 let mut version = None;
141 let mut workspace_version = None;
142 let mut publish = true;
143 let mut in_workspace = false;
144 for line in fs::read_to_string(manifest).unwrap().lines() {
145 if line.starts_with("[") {
146 in_workspace = line.starts_with("[workspace");
147 continue;
148 }
149
150 if name.is_none() && line.starts_with("name = \"") {
151 name = Some(
152 line.replace("name = \"", "")
153 .replace("\"", "")
154 .trim()
155 .to_string(),
156 );
157 }
158 if line.starts_with("version = \"") {
159 let dst = if in_workspace {
160 &mut workspace_version
161 } else {
162 &mut version
163 };
164 assert!(dst.is_none());
165 *dst = Some(
166 line.replace("version = \"", "")
167 .replace("\"", "")
168 .trim()
169 .to_string(),
170 );
171 }
172 if let Some(ws) = ws {
173 if version.is_none() && line.starts_with("version.workspace = true") {
174 version = Some(ws.version.clone());
175 }
176 }
177 if line.starts_with("publish = false") {
178 publish = false;
179 }
180 }
181 let name = name.unwrap();
182 let version = if !publish {
183 "0.0.0".to_string()
184 } else {
185 version.unwrap()
186 };
187 Crate {
188 manifest: manifest.to_path_buf(),
189 name,
190 version,
191 workspace_version,
192 publish,
193 }
194 }
195
196 fn bump_version(krate: &Crate, crates: &[Crate], patch: bool) {
197 let contents = fs::read_to_string(&krate.manifest).unwrap();
198 let next_version = |krate: &Crate| -> String {
199 if CRATES_TO_PUBLISH.contains(&&krate.name[..]) {
200 bump(
201 &krate.version,
202 if patch {
203 BumpKind::Patch
204 } else if API_STABLE_CRATES.contains(&&krate.name[..]) {
205 BumpKind::Minor
206 } else {
207 BumpKind::Major
208 },
209 )
210 } else {
211 krate.version.clone()
212 }
213 };
214
215 let mut new_manifest = String::new();
216 let mut is_deps = false;
217 let mut is_workspace = false;
218 for line in contents.lines() {
219 let mut rewritten = false;
220 if !is_deps && line.starts_with("version =") {
221 if CRATES_TO_PUBLISH.contains(&&krate.name[..]) {
222 println!(
223 "bump `{}` {} => {}",
224 krate.name,
225 krate.version,
226 next_version(krate),
227 );
228 let new_line = if is_workspace {
229 let ws_version = krate.workspace_version.as_ref().unwrap();
230 let next_version = bump(
231 ws_version,
232 if patch {
233 BumpKind::Patch
234 } else {
235 BumpKind::Major
236 },
237 );
238 line.replace(ws_version, &next_version)
239 } else {
240 line.replace(&krate.version, &next_version(krate))
241 };
242 new_manifest.push_str(&new_line);
243 rewritten = true;
244 }
245 }
246
247 if line.starts_with("[") {
248 is_deps = line.contains("dependencies");
249 is_workspace = line.contains("workspace");
250 }
251
252 for other in crates {
253 // If `other` isn't a published crate then it's not going to get a
254 // bumped version so we don't need to update anything in the
255 // manifest.
256 if !other.publish {
257 continue;
258 }
259 if !is_deps || !line.starts_with(&format!("{} ", other.name)) {
260 continue;
261 }
262 if !line.contains(&other.version) {
263 if !line.contains("version =") || !krate.publish {
264 continue;
265 }
266 panic!(
267 "{:?} has a dep on {} but doesn't list version {}",
268 krate.manifest, other.name, other.version
269 );
270 }
271 rewritten = true;
272 new_manifest.push_str(&line.replace(&other.version, &next_version(other)));
273 break;
274 }
275 if !rewritten {
276 new_manifest.push_str(line);
277 }
278 new_manifest.push_str("\n");
279 }
280 fs::write(&krate.manifest, new_manifest).unwrap();
281 }
282
283 enum BumpKind {
284 Major,
285 Minor,
286 Patch,
287 }
288
289 /// Performs a major version bump increment on the semver version `version`.
290 ///
291 /// This function will perform a semver-major-version bump on the `version`
292 /// specified. This is used to calculate the next version of a crate in this
293 /// repository since we're currently making major version bumps for all our
294 /// releases. This may end up getting tweaked as we stabilize crates and start
295 /// doing more minor/patch releases, but for now this should do the trick.
296 fn bump(version: &str, bump: BumpKind) -> String {
297 let mut iter = version.split('.').map(|s| s.parse::<u32>().unwrap());
298 let major = iter.next().expect("major version");
299 let minor = iter.next().expect("minor version");
300 let patch = iter.next().expect("patch version");
301
302 match bump {
303 BumpKind::Patch => {
304 format!("{}.{}.{}", major, minor, patch + 1)
305 }
306 BumpKind::Minor => {
307 format!("{}.{}.0", major, minor + 1)
308 }
309 BumpKind::Major if major != 0 => {
310 format!("{}.0.0", major + 1)
311 }
312 BumpKind::Major if minor != 0 => {
313 format!("0.{}.0", minor + 1)
314 }
315 BumpKind::Major => {
316 format!("0.0.{}", patch + 1)
317 }
318 }
319 }
320
321 fn publish(krate: &Crate) -> bool {
322 if !CRATES_TO_PUBLISH.iter().any(|s| *s == krate.name) {
323 return true;
324 }
325
326 // First make sure the crate isn't already published at this version. This
327 // script may be re-run and there's no need to re-attempt previous work.
328 match curl(&format!("https://crates.io/api/v1/crates/{}", krate.name)) {
329 Some(output) => {
330 if output.contains(&format!("\"newest_version\":\"{}\"", krate.version)) {
331 println!(
332 "skip publish {} because {} is latest version",
333 krate.name, krate.version,
334 );
335 return true;
336 }
337 }
338 None => return false,
339 }
340
341 let status = Command::new("cargo")
342 .arg("publish")
343 .current_dir(krate.manifest.parent().unwrap())
344 .arg("--no-verify")
345 .status()
346 .expect("failed to run cargo");
347 if !status.success() {
348 println!("FAIL: failed to publish `{}`: {}", krate.name, status);
349 return false;
350 }
351
352 true
353 }
354
355 fn curl(url: &str) -> Option<String> {
356 let output = cmd_output(
357 Command::new("curl")
358 .arg("--user-agent")
359 .arg("bytecodealliance/wasm-tools auto-publish script")
360 .arg(url),
361 );
362 if !output.status.success() {
363 println!("failed to curl: {}", output.status);
364 println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
365 return None;
366 }
367 Some(String::from_utf8_lossy(&output.stdout).into())
368 }
369
370 // Verify the current tree is publish-able to crates.io. The intention here is
371 // that we'll run `cargo package` on everything which verifies the build as-if
372 // it were published to crates.io. This requires using an incrementally-built
373 // directory registry generated from `cargo vendor` because the versions
374 // referenced from `Cargo.toml` may not exist on crates.io.
375 fn verify(crates: &[Crate]) {
376 drop(fs::remove_dir_all(".cargo"));
377 drop(fs::remove_dir_all("vendor"));
378 let vendor = Command::new("cargo")
379 .arg("vendor")
380 .stderr(Stdio::inherit())
381 .output()
382 .unwrap();
383 assert!(vendor.status.success());
384
385 fs::create_dir_all(".cargo").unwrap();
386 fs::write(".cargo/config.toml", vendor.stdout).unwrap();
387
388 for krate in crates {
389 if !krate.publish {
390 continue;
391 }
392 verify_crates_io(krate);
393 verify_and_vendor(&krate);
394 }
395
396 fn verify_and_vendor(krate: &Crate) {
397 let mut cmd = Command::new("cargo");
398 cmd.arg("package")
399 .arg("--allow-dirty")
400 .arg("--manifest-path")
401 .arg(&krate.manifest)
402 .env("CARGO_TARGET_DIR", "./target");
403 let status = cmd.status().unwrap();
404 assert!(status.success(), "failed to verify {:?}", &krate.manifest);
405 let tar = Command::new("tar")
406 .arg("xf")
407 .arg(format!(
408 "../target/package/{}-{}.crate",
409 krate.name, krate.version
410 ))
411 .current_dir("./vendor")
412 .status()
413 .unwrap();
414 assert!(tar.success());
415 fs::write(
416 format!(
417 "./vendor/{}-{}/.cargo-checksum.json",
418 krate.name, krate.version
419 ),
420 "{\"files\":{}}",
421 )
422 .unwrap();
423 }
424
425 fn verify_crates_io(krate: &Crate) {
426 let name = &krate.name;
427 let Some(owners) = curl(&format!("https://crates.io/api/v1/crates/{name}/owners")) else {
428 panic!(
429 "
430 failed to get owners for {name}
431
432 If this crate does not exist on crates.io yet please ping wasm-tools maintainers
433 to add the crate on crates.io as a small shim. When doing so please remind them
434 that the trusted publishing workflow must be configured as well.
435 ",
436 name = name,
437 );
438 };
439
440 // This is the id of the `wasmtime-publish` user on crates.io
441 if !owners.contains("\"id\":73222,") {
442 panic!(
443 "
444 crate {name} is not owned by wasmtime-publish, please run:
445
446 cargo owner -a wasmtime-publish {name}
447 ",
448 name = name,
449 );
450 }
451
452 if owners.split("\"id\"").count() != 2 {
453 panic!(
454 "
455 crate {name} is not exclusively owned by wasmtime-publish
456
457 Please contact wasm-tools maintainers to ensure that `wasmtime-publish` is the
458 only listed owner of the crate.
459 ",
460 name = name,
461 );
462 }
463 }
464 }
465
466 fn cmd_output(cmd: &mut Command) -> Output {
467 eprintln!("Running: `{:?}`", cmd);
468 match cmd.output() {
469 Ok(o) => o,
470 Err(e) => panic!("Failed to run `{:?}`: {}", cmd, e),
471 }
472 }