rust/xtask/src/codegen/gen_feature_docs.rs

89 lines
2.5 KiB
Rust
Raw Normal View History

2020-05-30 18:54:54 -05:00
//! Generates `assists.md` documentation.
use std::{fmt, fs, path::PathBuf};
use crate::{
codegen::{self, extract_comment_blocks_with_empty_lines, Mode},
project_root, rust_files, Result,
};
pub fn generate_feature_docs(mode: Mode) -> Result<()> {
let features = Feature::collect()?;
let contents = features.into_iter().map(|it| it.to_string()).collect::<Vec<_>>().join("\n\n");
2020-05-31 05:12:41 -05:00
let contents = contents.trim().to_string() + "\n";
2020-05-30 18:54:54 -05:00
let dst = project_root().join("docs/user/generated_features.adoc");
codegen::update(&dst, &contents, mode)?;
Ok(())
}
#[derive(Debug)]
struct Feature {
id: String,
path: PathBuf,
doc: String,
}
impl Feature {
fn collect() -> Result<Vec<Feature>> {
let mut res = Vec::new();
for path in rust_files(&project_root()) {
collect_file(&mut res, path)?;
}
res.sort_by(|lhs, rhs| lhs.id.cmp(&rhs.id));
return Ok(res);
fn collect_file(acc: &mut Vec<Feature>, path: PathBuf) -> Result<()> {
let text = fs::read_to_string(&path)?;
let comment_blocks = extract_comment_blocks_with_empty_lines("Feature", &text);
for block in comment_blocks {
let id = block.id;
2020-05-31 02:45:41 -05:00
assert!(is_valid_feature_name(&id), "invalid feature name: {:?}", id);
2020-05-30 18:54:54 -05:00
let doc = block.contents.join("\n");
acc.push(Feature { id, path: path.clone(), doc })
}
Ok(())
}
}
}
2020-05-31 02:45:41 -05:00
fn is_valid_feature_name(feature: &str) -> bool {
'word: for word in feature.split_whitespace() {
for &short in ["to", "and"].iter() {
2020-05-31 02:45:41 -05:00
if word == short {
continue 'word;
}
}
for &short in ["To", "And"].iter() {
2020-05-31 02:45:41 -05:00
if word == short {
return false;
}
}
if !word.starts_with(char::is_uppercase) {
return false;
}
}
true
}
2020-05-30 18:54:54 -05:00
impl fmt::Display for Feature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "=== {}", self.id)?;
2020-05-31 05:49:06 -05:00
let path = self.path.strip_prefix(&project_root()).unwrap().display().to_string();
let path = path.replace('\\', "/");
2020-05-30 18:54:54 -05:00
let name = self.path.file_name().unwrap();
//FIXME: generate line number as well
writeln!(
f,
"**Source:** https://github.com/rust-analyzer/rust-analyzer/blob/master/{}[{}]",
2020-05-31 05:49:06 -05:00
path,
2020-05-30 18:54:54 -05:00
name.to_str().unwrap(),
)?;
2020-05-31 05:12:41 -05:00
writeln!(f, "{}", self.doc)?;
2020-05-30 18:54:54 -05:00
Ok(())
}
}