bevy/tools/build-templated-pages/src/examples.rs
Zachary Harrold d70595b667
Add core and alloc over std Lints (#15281)
# Objective

- Fixes #6370
- Closes #6581

## Solution

- Added the following lints to the workspace:
  - `std_instead_of_core`
  - `std_instead_of_alloc`
  - `alloc_instead_of_core`
- Used `cargo +nightly fmt` with [item level use
formatting](https://rust-lang.github.io/rustfmt/?version=v1.6.0&search=#Item%5C%3A)
to split all `use` statements into single items.
- Used `cargo clippy --workspace --all-targets --all-features --fix
--allow-dirty` to _attempt_ to resolve the new linting issues, and
intervened where the lint was unable to resolve the issue automatically
(usually due to needing an `extern crate alloc;` statement in a crate
root).
- Manually removed certain uses of `std` where negative feature gating
prevented `--all-features` from finding the offending uses.
- Used `cargo +nightly fmt` with [crate level use
formatting](https://rust-lang.github.io/rustfmt/?version=v1.6.0&search=#Crate%5C%3A)
to re-merge all `use` statements matching Bevy's previous styling.
- Manually fixed cases where the `fmt` tool could not re-merge `use`
statements due to conditional compilation attributes.

## Testing

- Ran CI locally

## Migration Guide

The MSRV is now 1.81. Please update to this version or higher.

## Notes

- This is a _massive_ change to try and push through, which is why I've
outlined the semi-automatic steps I used to create this PR, in case this
fails and someone else tries again in the future.
- Making this change has no impact on user code, but does mean Bevy
contributors will be warned to use `core` and `alloc` instead of `std`
where possible.
- This lint is a critical first step towards investigating `no_std`
options for Bevy.

---------

Co-authored-by: François Mockers <francois.mockers@vleue.com>
2024-09-27 00:59:59 +00:00

146 lines
4.4 KiB
Rust

use core::cmp::Ordering;
use std::fs::File;
use hashbrown::HashMap;
use serde::Serialize;
use tera::{Context, Tera};
use toml_edit::{DocumentMut, Item};
use crate::Command;
#[derive(Debug, Serialize, PartialEq, Eq)]
struct Category {
description: Option<String>,
examples: Vec<Example>,
}
#[derive(Debug, Serialize, PartialEq, Eq)]
struct Example {
technical_name: String,
path: String,
name: String,
description: String,
category: String,
wasm: bool,
}
impl Ord for Example {
fn cmp(&self, other: &Self) -> Ordering {
match self.category.cmp(&other.category) {
Ordering::Equal => self.name.cmp(&other.name),
ordering => ordering,
}
}
}
impl PartialOrd for Example {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
fn parse_examples(panic_on_missing: bool) -> Vec<Example> {
let manifest_file = std::fs::read_to_string("Cargo.toml").unwrap();
let manifest = manifest_file.parse::<DocumentMut>().unwrap();
let metadatas = manifest
.get("package")
.unwrap()
.get("metadata")
.as_ref()
.unwrap()["example"]
.clone();
manifest["example"]
.as_array_of_tables()
.unwrap()
.iter()
.flat_map(|val| {
let technical_name = val.get("name").unwrap().as_str().unwrap().to_string();
if panic_on_missing && metadatas.get(&technical_name).is_none() {
panic!("Missing metadata for example {technical_name}");
}
if panic_on_missing && val.get("doc-scrape-examples").is_none() {
panic!("Example {technical_name} is missing doc-scrape-examples");
}
if metadatas
.get(&technical_name)
.and_then(|metadata| metadata.get("hidden"))
.and_then(Item::as_bool)
.and_then(|hidden| hidden.then_some(()))
.is_some()
{
return None;
}
metadatas.get(&technical_name).map(|metadata| Example {
technical_name,
path: val["path"].as_str().unwrap().to_string(),
name: metadata["name"].as_str().unwrap().to_string(),
description: metadata["description"].as_str().unwrap().to_string(),
category: metadata["category"].as_str().unwrap().to_string(),
wasm: metadata["wasm"].as_bool().unwrap(),
})
})
.collect()
}
fn parse_categories() -> HashMap<Box<str>, String> {
let manifest_file = std::fs::read_to_string("Cargo.toml").unwrap();
let manifest = manifest_file.parse::<DocumentMut>().unwrap();
manifest
.get("package")
.unwrap()
.get("metadata")
.as_ref()
.unwrap()["example_category"]
.clone()
.as_array_of_tables()
.unwrap()
.iter()
.map(|v| {
(
v.get("name").unwrap().as_str().unwrap().into(),
v.get("description").unwrap().as_str().unwrap().to_string(),
)
})
.collect()
}
pub(crate) fn check(what_to_run: Command) {
let examples = parse_examples(what_to_run.contains(Command::CHECK_MISSING));
if what_to_run.contains(Command::UPDATE) {
let categories = parse_categories();
let examples_by_category: HashMap<Box<str>, Category> = examples
.into_iter()
.fold(HashMap::<Box<str>, Vec<Example>>::new(), |mut v, ex| {
v.entry_ref(ex.category.as_str()).or_default().push(ex);
v
})
.into_iter()
.map(|(key, mut examples)| {
examples.sort();
let description = categories.get(&key).cloned();
(
key,
Category {
description,
examples,
},
)
})
.collect();
let mut context = Context::new();
context.insert("all_examples", &examples_by_category);
Tera::new("docs-template/*.md.tpl")
.expect("error parsing template")
.render_to(
"EXAMPLE_README.md.tpl",
&context,
File::create("examples/README.md").expect("error creating file"),
)
.expect("error rendering template");
}
}