Skip to content

Commit

Permalink
Feat: ignore items documentation with the # rhai-autodocs:ignore pr…
Browse files Browse the repository at this point in the history
…eprocessor (#13)

* docs: update readme example

* feat: add # rhai-autodocs:ignore preprocessor

* ci: simplify scripts

* fix: clippy lints

* fix: clippy lints

* docs: remove main in readme
  • Loading branch information
ltabis authored Apr 18, 2024
1 parent 7d4997b commit b9ab5ba
Show file tree
Hide file tree
Showing 6 changed files with 80 additions and 63 deletions.
4 changes: 1 addition & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ jobs:
name: test-stable
steps:
- uses: actions/checkout@v3
- uses: dtolnay/rust-toolchain@master
with:
toolchain: stable
- uses: dtolnay/rust-toolchain@stable
- run: cargo test

clippy:
Expand Down
54 changes: 26 additions & 28 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,17 @@ Published with [Docusaurus](https://docusaurus.io/).

## How to use

First, create a plugin module or any kind of Rhai API that supports documentation on functions and types.

```rust
use rhai::exported_module;
use rhai::plugin::*;

// 1. Create a plugin module or any kind of Rhai API that supports documentation on functions and types.

/// My own module.
#[export_module]
mod my_module {
use rhai::plugin::*;

/// A function that prints to stdout.
///
/// # Args
Expand Down Expand Up @@ -55,34 +58,29 @@ mod my_module {
a + b
}
}
```

Then, generate the docs with autodocs. This library can be imported as a build dependency into your build script.
A typical documentation generation workflow would look like this:
// 2. Generate the docs with autodocs. This library can be imported as a build dependency into your build script.
// A typical documentation generation workflow would look like this:

```rust
// -- build.rs
fn main() {
// Specify an environment variable that points to the directory
// where the documentation will be generated.
if let Ok(docs_path) = std::env::var("DOCS_DIR") {
let mut engine = rhai::Engine::new();

// We register the module defined in the previous code block for this example,
// but you could register other functions and types ...
engine.register_static_module("my_module", exported_module!(my_module).into());

let docs = rhai_autodocs::options()
.include_standard_packages(false)
.generate(&engine)
.expect("failed to generate documentation");

// Write the documentation in a file, or output to stdout, etc.
for (name, docs) in generate_for_docusaurus(&docs).unwrap() {
println("docs for module {name}");
println("{docs}");
}
}
// Specify an environment variable that points to the directory
// where the documentation will be generated.
let docs_path = std::env::var("DOCS_DIR").unwrap_or("target/docs".to_string());

let mut engine = rhai::Engine::new();

// We register the module defined in the previous code block for this example,
// but you could register other functions and types ...
engine.register_static_module("my_module", exported_module!(my_module).into());

let docs = rhai_autodocs::options()
.include_standard_packages(false)
.generate(&engine)
.expect("failed to generate documentation");

// Write the documentation in a file, or output to stdout, etc.
for (name, docs) in rhai_autodocs::generate_for_docusaurus(&docs).unwrap() {
println!("docs for module {name}");
println!("{docs}");
}
```

Expand Down
78 changes: 46 additions & 32 deletions src/doc_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{
function::FunctionMetadata,
module::{
error::AutodocsError,
options::{Options, RHAI_ITEM_INDEX_PATTERN},
options::{Options, RHAI_IGNORE_PATTERN, RHAI_ITEM_INDEX_PATTERN},
},
ItemsOrder,
};
Expand Down Expand Up @@ -119,7 +119,7 @@ impl DocItem {
name: &str,
namespace: &str,
options: &Options,
) -> Result<Self, AutodocsError> {
) -> Result<Option<Self>, AutodocsError> {
// Takes the first valid comments found for a function group.
let root = metadata
.iter()
Expand All @@ -128,22 +128,26 @@ impl DocItem {
match root {
// Anonymous functions are ignored.
Some(root) if !name.starts_with("anon$") => {
let index = if matches!(options.items_order, ItemsOrder::ByIndex) {
if matches!(options.items_order, ItemsOrder::ByIndex) {
Self::find_index(
name,
namespace,
root.doc_comments.as_ref().unwrap_or(&vec![]),
)?
} else {
0
};

Ok(Self::Function {
root_metadata: root.clone(),
metadata: metadata.to_vec(),
name: name.to_string(),
index,
})
Some(0)
}
.map_or_else(
|| Ok(None),
|index| {
Ok(Some(Self::Function {
root_metadata: root.clone(),
metadata: metadata.to_vec(),
name: name.to_string(),
index,
}))
},
)
}
_ => Err(AutodocsError::Metadata(format!(
"No documentation found for function item {namespace}/{name}"
Expand All @@ -155,18 +159,20 @@ impl DocItem {
metadata: CustomTypesMetadata,
namespace: &str,
options: &Options,
) -> Result<Self, AutodocsError> {
let index = if matches!(options.items_order, ItemsOrder::ByIndex) {
) -> Result<Option<Self>, AutodocsError> {
if matches!(options.items_order, ItemsOrder::ByIndex) {
Self::find_index(
&metadata.display_name,
namespace,
metadata.doc_comments.as_ref().unwrap_or(&vec![]),
)?
} else {
0
};

Ok(Self::CustomType { metadata, index })
Some(0)
}
.map_or_else(
|| Ok(None),
|index| Ok(Some(Self::CustomType { metadata, index })),
)
}

pub fn index(&self) -> usize {
Expand All @@ -187,20 +193,26 @@ impl DocItem {
name: &str,
namespace: &str,
doc_comments: &[String],
) -> Result<usize, AutodocsError> {
if let Some((_, index)) = doc_comments
.iter()
.find_map(|line| line.rsplit_once(RHAI_ITEM_INDEX_PATTERN))
{
index.parse::<usize>().map_err(|err| {
AutodocsError::PreProcessing(format!("failed to parsed order metadata: {err}"))
})
} else {
Err(AutodocsError::PreProcessing(format!(
"missing order metadata in item {}/{}",
namespace, name
)))
) -> Result<Option<usize>, AutodocsError> {
for line in doc_comments {
if let Some((_, index)) = line.rsplit_once(RHAI_ITEM_INDEX_PATTERN) {
return index
.parse::<usize>()
.map_err(|err| {
AutodocsError::PreProcessing(format!(
"failed to parsed order metadata: {err}"
))
})
.map(Some);
} else if line.contains(RHAI_IGNORE_PATTERN) {
return Ok(None);
}
}

Err(AutodocsError::PreProcessing(format!(
"missing order metadata in item {}/{}",
namespace, name
)))
}

/// Format the function doc comments to make them
Expand All @@ -218,7 +230,9 @@ impl DocItem {
dc.into_iter()
.map(|s| {
s.lines()
.filter(|l| !l.contains(RHAI_ITEM_INDEX_PATTERN))
.filter(|l| {
!l.contains(RHAI_ITEM_INDEX_PATTERN) && !l.contains(RHAI_IGNORE_PATTERN)
})
.collect::<Vec<_>>()
.join("\n")
})
Expand Down
3 changes: 3 additions & 0 deletions src/glossary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ fn generate_module_glossary_inner(
vec![]
});

// Remove ignored documentation.
let items = items.into_iter().flatten().collect::<Vec<DocItem>>();

let items = options.items_order.order_items(items);

let signatures = {
Expand Down
3 changes: 3 additions & 0 deletions src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ fn generate_module_documentation_inner(
}
}

// Remove ignored documentation.
let items = items.into_iter().flatten().collect::<Vec<DocItem>>();

md.items = options.items_order.order_items(items);

// Generate documentation for each submodule. (if any)
Expand Down
1 change: 1 addition & 0 deletions src/module/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::{
use super::{error::AutodocsError, generate_module_documentation};

pub const RHAI_ITEM_INDEX_PATTERN: &str = "# rhai-autodocs:index:";
pub const RHAI_IGNORE_PATTERN: &str = "# rhai-autodocs:ignore";

/// Types of markdown processor where the documentation generated will be hosted.
#[derive(Default)]
Expand Down

0 comments on commit b9ab5ba

Please sign in to comment.