├── .github └── workflows │ └── rust.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── lib.rs ├── rustfmt.toml └── tests └── self-doc.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | RUSTFLAGS: -D warnings 12 | RUST_BACKTRACE: 1 13 | 14 | jobs: 15 | test: 16 | runs-on: ubuntu-latest 17 | strategy: 18 | matrix: 19 | rust: 20 | - stable 21 | - 1.54.0 22 | - nightly 23 | 24 | steps: 25 | - uses: actions/checkout@v4 26 | - uses: dtolnay/rust-toolchain@master 27 | with: 28 | toolchain: ${{ matrix.rust }} 29 | - name: Run tests 30 | run: cargo test --verbose --all-features 31 | - name: Run docs 32 | run: cargo doc --verbose 33 | format: 34 | runs-on: ubuntu-latest 35 | steps: 36 | - uses: actions/checkout@v4 37 | - uses: dtolnay/rust-toolchain@stable 38 | - name: Run rustfmt 39 | run: cargo fmt --all -- --check 40 | 41 | 42 | crater: 43 | runs-on: ubuntu-latest 44 | steps: 45 | - uses: actions/checkout@v4 46 | - uses: dtolnay/rust-toolchain@master 47 | with: 48 | toolchain: nightly 49 | - name: setup patch 50 | run: | 51 | echo "" >> ~/.cargo/config.toml 52 | echo [patch.crates-io] >> ~/.cargo/config.toml 53 | echo document-features = { path = \"$GITHUB_WORKSPACE\" } >> ~/.cargo/config.toml 54 | - name: create project and generate docs 55 | run: | 56 | cd ~ 57 | cargo new crater 58 | cd crater 59 | cargo add quick-xml -F document-features 60 | cargo add serde_with -F guide 61 | cargo add serial_test -F docsrs 62 | cargo add wgpu-core 63 | cargo add wgpu 64 | cargo add gix -F document-features 65 | cargo add kstring -F document-features 66 | cargo add ratatui -F document-features 67 | cargo add re_types 68 | cargo add slint -F document-features 69 | cargo add egui-winit -F document-features 70 | cargo add ehttp 71 | cargo add snapbox -F document-features 72 | cargo add fast-image-resize 73 | cargo add rhai -F document-features 74 | cargo add embassy-executor 75 | cargo add embassy-time 76 | 77 | cargo doc 78 | grep -r ">No documented features in Cargo.toml<" target/doc || exit 0 79 | false 80 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | Cargo.lock 2 | /target 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 0.2.11 - 2024-02-16 4 | 5 | * Collect defaults recursively (#19) 6 | 7 | ## 0.2.10 - 2024-07-12 8 | 9 | * Revert parsing of multi-lines string while parsing features 10 | (Keep parsing of multi-lines string when detecting if we need to use Cargo.toml.orig) 11 | 12 | ## 0.2.9 - 2024-07-11 13 | 14 | * Fix parsing of multi-lines string (#25) 15 | * Fix `out_of_scope_macro_calls` compatibility warning 16 | * Fix documentation having too many `#` (#22) 17 | 18 | ## 0.2.8 - 2023-12-29 19 | 20 | * Remove `\n` between features (#17) 21 | * Don't throw an error when there is no features in Cargo.toml (#20) 22 | 23 | ## 0.2.7 - 2022-12-21 24 | 25 | * Fix parsing of Cargo.toml with multi-line array of array (#16) 26 | 27 | ## 0.2.6 - 2022-09-24 28 | 29 | * Fix parsing of escaped string literal in the macro arguments 30 | 31 | ## 0.2.5 - 2022-09-17 32 | 33 | * Allow customization of the output with the `feature_label=` parameter 34 | 35 | ## 0.2.4 - 2022-09-14 36 | 37 | * Fix dependencies or features written with quotes 38 | 39 | ## 0.2.3 - 2022-08-15 40 | 41 | * Fix parsing of table with `#` within strings (#10) 42 | 43 | ## 0.2.2 - 2022-07-25 44 | 45 | * Fix parsing of dependencies or feature spanning multiple lines (#9) 46 | 47 | ## 0.2.1 - 2022-02-12 48 | 49 | * Fix indentation of multi-lines feature comments (#5) 50 | 51 | ## 0.2.0 - 2022-02-11 52 | 53 | * Added ability to document optional features. (This is a breaking change in the 54 | sense that previously ignored comments may now result in errors) 55 | 56 | ## 0.1.0 - 2022-02-01 57 | 58 | Initial release 59 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | # Copyright © SixtyFPS GmbH 2 | # SPDX-License-Identifier: MIT OR Apache-2.0 3 | 4 | [package] 5 | name = "document-features" 6 | version = "0.2.11" 7 | authors = ["Slint Developers "] 8 | edition = "2018" 9 | license = "MIT OR Apache-2.0" 10 | repository = "https://github.com/slint-ui/document-features" 11 | homepage = "https://slint.rs" 12 | description = "Extract documentation for the feature flags from comments in Cargo.toml" 13 | categories = ["development-tools"] 14 | keywords = ["documentation", "features", "rustdoc", "macro"] 15 | 16 | [lib] 17 | proc-macro = true 18 | path = "lib.rs" 19 | 20 | [features] 21 | default = [] 22 | 23 | ## Internal feature used only for the tests, don't enable 24 | self-test = [] 25 | 26 | [dependencies] 27 | litrs = { version = "0.4.1", default-features = false } 28 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 10 | 11 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 12 | 13 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 14 | 15 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 16 | 17 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 18 | 19 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 20 | 21 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 22 | 23 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 24 | 25 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 26 | 27 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 28 | 29 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 30 | 31 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 32 | 33 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 34 | 35 | (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and 36 | 37 | (b) You must cause any modified files to carry prominent notices stating that You changed the files; and 38 | 39 | (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 40 | 41 | (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 42 | 43 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 44 | 45 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 46 | 47 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 48 | 49 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 50 | 51 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 52 | 53 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 54 | 55 | END OF TERMS AND CONDITIONS 56 | 57 | APPENDIX: How to apply the Apache License to your work. 58 | 59 | To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. 60 | 61 | Copyright [yyyy] [name of copyright owner] 62 | 63 | Licensed under the Apache License, Version 2.0 (the "License"); 64 | you may not use this file except in compliance with the License. 65 | You may obtain a copy of the License at 66 | 67 | http://www.apache.org/licenses/LICENSE-2.0 68 | 69 | Unless required by applicable law or agreed to in writing, software 70 | distributed under the License is distributed on an "AS IS" BASIS, 71 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 72 | See the License for the specific language governing permissions and 73 | limitations under the License. 74 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2020 Olivier Goffart 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Document your crate's feature flags 2 | 3 | [![Crates.io](https://img.shields.io/crates/v/document-features)](https://crates.io/crates/document-features) 4 | [![Documentation](https://docs.rs/document-features/badge.svg)](https://docs.rs/document-features/) 5 | 6 | This crate provides a macro that extracts documentation comments from Cargo.toml 7 | 8 | To use this crate, add `#![doc = document_features::document_features!()]` in your crate documentation. 9 | The `document_features!()` macro reads your `Cargo.toml` file, extracts feature comments and generates 10 | a markdown string for your documentation. 11 | 12 | Use `## ` and `#! ` comments in your Cargo.toml to document features, for example: 13 | 14 | ```toml 15 | [dependencies] 16 | document-features = "0.2" 17 | ## ... 18 | 19 | [features] 20 | ## The foo feature enables the `foo` functions 21 | foo = [] 22 | ## The bar feature enables the [`bar`] module 23 | bar = [] 24 | 25 | #! ### Experimental features 26 | #! The following features are experimental 27 | 28 | ## Activate the fusion reactor 29 | fusion = [] 30 | ``` 31 | 32 | These comments keep the feature definition and documentation next to each other, and they are then 33 | rendered into your crate documentation. 34 | 35 | Check out the [documentation](https://docs.rs/document-features/) for more details. 36 | 37 | ## Contributions 38 | 39 | Contributions are welcome. We accept pull requests and bug reports. 40 | 41 | ## License 42 | 43 | MIT OR Apache-2.0 44 | -------------------------------------------------------------------------------- /lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright © SixtyFPS GmbH 2 | // SPDX-License-Identifier: MIT OR Apache-2.0 3 | 4 | /*! 5 | Document your crate's feature flags. 6 | 7 | This crates provides a macro that extracts "documentation" comments from Cargo.toml 8 | 9 | To use this crate, add `#![doc = document_features::document_features!()]` in your crate documentation. 10 | The `document_features!()` macro reads your `Cargo.toml` file, extracts feature comments and generates 11 | a markdown string for your documentation. 12 | 13 | Basic example: 14 | 15 | ```rust 16 | //! Normal crate documentation goes here. 17 | //! 18 | //! ## Feature flags 19 | #![doc = document_features::document_features!()] 20 | 21 | // rest of the crate goes here. 22 | ``` 23 | 24 | ## Documentation format: 25 | 26 | The documentation of your crate features goes into `Cargo.toml`, where they are defined. 27 | 28 | The `document_features!()` macro analyzes the contents of `Cargo.toml`. 29 | Similar to Rust's documentation comments `///` and `//!`, the macro understands 30 | comments that start with `## ` and `#! `. Note the required trailing space. 31 | Lines starting with `###` will not be understood as doc comment. 32 | 33 | `## ` comments are meant to be *above* the feature they document. 34 | There can be several `## ` comments, but they must always be followed by a 35 | feature name or an optional dependency. 36 | There should not be `#! ` comments between the comment and the feature they document. 37 | 38 | `#! ` comments are not associated with a particular feature, and will be printed 39 | in where they occur. Use them to group features, for example. 40 | 41 | ## Examples: 42 | 43 | */ 44 | #![doc = self_test!(/** 45 | [package] 46 | name = "..." 47 | # ... 48 | 49 | [features] 50 | default = ["foo"] 51 | #! This comments goes on top 52 | 53 | ## The foo feature enables the `foo` functions 54 | foo = [] 55 | 56 | ## The bar feature enables the bar module 57 | bar = [] 58 | 59 | #! ### Experimental features 60 | #! The following features are experimental 61 | 62 | ## Enable the fusion reactor 63 | ## 64 | ## ⚠️ Can lead to explosions 65 | fusion = [] 66 | 67 | [dependencies] 68 | document-features = "0.2" 69 | 70 | #! ### Optional dependencies 71 | 72 | ## Enable this feature to implement the trait for the types from the genial crate 73 | genial = { version = "0.2", optional = true } 74 | 75 | ## This awesome dependency is specified in its own table 76 | [dependencies.awesome] 77 | version = "1.3.5" 78 | optional = true 79 | */ 80 | => 81 | /** 82 | This comments goes on top 83 | * **`foo`** *(enabled by default)* — The foo feature enables the `foo` functions 84 | * **`bar`** — The bar feature enables the bar module 85 | 86 | #### Experimental features 87 | The following features are experimental 88 | * **`fusion`** — Enable the fusion reactor 89 | 90 | ⚠️ Can lead to explosions 91 | 92 | #### Optional dependencies 93 | * **`genial`** — Enable this feature to implement the trait for the types from the genial crate 94 | * **`awesome`** — This awesome dependency is specified in its own table 95 | */ 96 | )] 97 | /*! 98 | 99 | ## Customization 100 | 101 | You can customize the formatting of the features in the generated documentation by setting 102 | the key **`feature_label=`** to a given format string. This format string must be either 103 | a [string literal](https://doc.rust-lang.org/reference/tokens.html#string-literals) or 104 | a [raw string literal](https://doc.rust-lang.org/reference/tokens.html#raw-string-literals). 105 | Every occurrence of `{feature}` inside the format string will be substituted with the name of the feature. 106 | 107 | For instance, to emulate the HTML formatting used by `rustdoc` one can use the following: 108 | 109 | ```rust 110 | #![doc = document_features::document_features!(feature_label = r#"{feature}"#)] 111 | ``` 112 | 113 | The default formatting is equivalent to: 114 | 115 | ```rust 116 | #![doc = document_features::document_features!(feature_label = "**`{feature}`**")] 117 | ``` 118 | 119 | ## Compatibility 120 | 121 | The minimum Rust version required to use this crate is Rust 1.54 because of the 122 | feature to have macro in doc comments. You can make this crate optional and use 123 | `#[cfg_attr()]` statements to enable it only when building the documentation: 124 | You need to have two levels of `cfg_attr` because Rust < 1.54 doesn't parse the attribute 125 | otherwise. 126 | 127 | ```rust,ignore 128 | #![cfg_attr( 129 | feature = "document-features", 130 | cfg_attr(doc, doc = ::document_features::document_features!()) 131 | )] 132 | ``` 133 | 134 | In your Cargo.toml, enable this feature while generating the documentation on docs.rs: 135 | 136 | ```toml 137 | [dependencies] 138 | document-features = { version = "0.2", optional = true } 139 | 140 | [package.metadata.docs.rs] 141 | features = ["document-features"] 142 | ## Alternative: enable all features so they are all documented 143 | ## all-features = true 144 | ``` 145 | */ 146 | 147 | #[cfg(not(feature = "default"))] 148 | compile_error!( 149 | "The feature `default` must be enabled to ensure \ 150 | forward compatibility with future version of this crate" 151 | ); 152 | 153 | extern crate proc_macro; 154 | 155 | use proc_macro::{TokenStream, TokenTree}; 156 | use std::borrow::Cow; 157 | use std::collections::{HashMap, HashSet}; 158 | use std::convert::TryFrom; 159 | use std::fmt::Write; 160 | use std::path::Path; 161 | use std::str::FromStr; 162 | 163 | fn error(e: &str) -> TokenStream { 164 | TokenStream::from_str(&format!("::core::compile_error!{{\"{}\"}}", e.escape_default())).unwrap() 165 | } 166 | 167 | fn compile_error(msg: &str, tt: Option) -> TokenStream { 168 | let span = tt.as_ref().map_or_else(proc_macro::Span::call_site, TokenTree::span); 169 | use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing}; 170 | use std::iter::FromIterator; 171 | TokenStream::from_iter(vec![ 172 | TokenTree::Ident(Ident::new("compile_error", span)), 173 | TokenTree::Punct({ 174 | let mut punct = Punct::new('!', Spacing::Alone); 175 | punct.set_span(span); 176 | punct 177 | }), 178 | TokenTree::Group({ 179 | let mut group = Group::new(Delimiter::Brace, { 180 | TokenStream::from_iter([TokenTree::Literal({ 181 | let mut string = Literal::string(msg); 182 | string.set_span(span); 183 | string 184 | })]) 185 | }); 186 | group.set_span(span); 187 | group 188 | }), 189 | ]) 190 | } 191 | 192 | #[derive(Default)] 193 | struct Args { 194 | feature_label: Option, 195 | } 196 | 197 | fn parse_args(input: TokenStream) -> Result { 198 | let mut token_trees = input.into_iter().fuse(); 199 | 200 | // parse the key, ensuring that it is the identifier `feature_label` 201 | match token_trees.next() { 202 | None => return Ok(Args::default()), 203 | Some(TokenTree::Ident(ident)) if ident.to_string() == "feature_label" => (), 204 | tt => return Err(compile_error("expected `feature_label`", tt)), 205 | } 206 | 207 | // parse a single equal sign `=` 208 | match token_trees.next() { 209 | Some(TokenTree::Punct(p)) if p.as_char() == '=' => (), 210 | tt => return Err(compile_error("expected `=`", tt)), 211 | } 212 | 213 | // parse the value, ensuring that it is a string literal containing the substring `"{feature}"` 214 | let feature_label; 215 | if let Some(tt) = token_trees.next() { 216 | match litrs::StringLit::::try_from(&tt) { 217 | Ok(string_lit) if string_lit.value().contains("{feature}") => { 218 | feature_label = string_lit.value().to_string() 219 | } 220 | _ => { 221 | return Err(compile_error( 222 | "expected a string literal containing the substring \"{feature}\"", 223 | Some(tt), 224 | )) 225 | } 226 | } 227 | } else { 228 | return Err(compile_error( 229 | "expected a string literal containing the substring \"{feature}\"", 230 | None, 231 | )); 232 | } 233 | 234 | // ensure there is nothing left after the format string 235 | if let tt @ Some(_) = token_trees.next() { 236 | return Err(compile_error("unexpected token after the format string", tt)); 237 | } 238 | 239 | Ok(Args { feature_label: Some(feature_label) }) 240 | } 241 | 242 | /// Produce a literal string containing documentation extracted from Cargo.toml 243 | /// 244 | /// See the [crate] documentation for details 245 | #[proc_macro] 246 | pub fn document_features(tokens: TokenStream) -> TokenStream { 247 | parse_args(tokens) 248 | .and_then(|args| document_features_impl(&args)) 249 | .unwrap_or_else(std::convert::identity) 250 | } 251 | 252 | fn document_features_impl(args: &Args) -> Result { 253 | let path = std::env::var("CARGO_MANIFEST_DIR").unwrap(); 254 | let mut cargo_toml = std::fs::read_to_string(Path::new(&path).join("Cargo.toml")) 255 | .map_err(|e| error(&format!("Can't open Cargo.toml: {:?}", e)))?; 256 | 257 | if !has_doc_comments(&cargo_toml) { 258 | // On crates.io, Cargo.toml is usually "normalized" and stripped of all comments. 259 | // The original Cargo.toml has been renamed Cargo.toml.orig 260 | if let Ok(orig) = std::fs::read_to_string(Path::new(&path).join("Cargo.toml.orig")) { 261 | if has_doc_comments(&orig) { 262 | cargo_toml = orig; 263 | } 264 | } 265 | } 266 | 267 | let result = process_toml(&cargo_toml, args).map_err(|e| error(&e))?; 268 | Ok(std::iter::once(proc_macro::TokenTree::from(proc_macro::Literal::string(&result))).collect()) 269 | } 270 | 271 | /// Check if the Cargo.toml has comments that looks like doc comments. 272 | fn has_doc_comments(cargo_toml: &str) -> bool { 273 | let mut lines = cargo_toml.lines().map(str::trim); 274 | while let Some(line) = lines.next() { 275 | if line.starts_with("## ") || line.starts_with("#! ") { 276 | return true; 277 | } 278 | let before_coment = line.split_once('#').map_or(line, |(before, _)| before); 279 | if line.starts_with("#") { 280 | continue; 281 | } 282 | if let Some((_, mut quote)) = before_coment.split_once("\"\"\"") { 283 | loop { 284 | // skip slashes. 285 | if let Some((_, s)) = quote.split_once('\\') { 286 | quote = s.strip_prefix('\\').or_else(|| s.strip_prefix('"')).unwrap_or(s); 287 | continue; 288 | } 289 | // skip quotes. 290 | if let Some((_, out_quote)) = quote.split_once("\"\"\"") { 291 | let out_quote = out_quote.trim_start_matches('"'); 292 | let out_quote = 293 | out_quote.split_once('#').map_or(out_quote, |(before, _)| before); 294 | if let Some((_, q)) = out_quote.split_once("\"\"\"") { 295 | quote = q; 296 | continue; 297 | } 298 | break; 299 | }; 300 | match lines.next() { 301 | Some(l) => quote = l, 302 | None => return false, 303 | } 304 | } 305 | } 306 | } 307 | false 308 | } 309 | 310 | #[test] 311 | fn test_has_doc_coment() { 312 | assert!(has_doc_comments("foo\nbar\n## comment\nddd")); 313 | assert!(!has_doc_comments("foo\nbar\n#comment\nddd")); 314 | assert!(!has_doc_comments( 315 | r#" 316 | [[package.metadata.release.pre-release-replacements]] 317 | exactly = 1 # not a doc comment 318 | file = "CHANGELOG.md" 319 | replace = """ 320 | 321 | ## [Unreleased] - ReleaseDate 322 | """ 323 | search = "" 324 | array = ["""foo""", """ 325 | bar""", """eee 326 | ## not a comment 327 | """] 328 | "# 329 | )); 330 | assert!(has_doc_comments( 331 | r#" 332 | [[package.metadata.release.pre-release-replacements]] 333 | exactly = 1 # """ 334 | file = "CHANGELOG.md" 335 | replace = """ 336 | 337 | ## [Unreleased] - ReleaseDate 338 | """ 339 | search = "" 340 | array = ["""foo""", """ 341 | bar""", """eee 342 | ## not a comment 343 | """] 344 | ## This is a comment 345 | feature = "45" 346 | "# 347 | )); 348 | 349 | assert!(!has_doc_comments( 350 | r#" 351 | [[package.metadata.release.pre-release-replacements]] 352 | value = """" string \""" 353 | ## within the string 354 | \"""" 355 | another_string = """"" # """ 356 | ## also within""" 357 | "# 358 | )); 359 | 360 | assert!(has_doc_comments( 361 | r#" 362 | [[package.metadata.release.pre-release-replacements]] 363 | value = """" string \""" 364 | ## within the string 365 | \"""" 366 | another_string = """"" # """ 367 | ## also within""" 368 | ## out of the string 369 | foo = bar 370 | "# 371 | )); 372 | } 373 | 374 | fn dependents( 375 | feature_dependencies: &HashMap>, 376 | feature: &str, 377 | collected: &mut HashSet, 378 | ) { 379 | if collected.contains(feature) { 380 | return; 381 | } 382 | collected.insert(feature.to_string()); 383 | if let Some(dependencies) = feature_dependencies.get(feature) { 384 | for dependency in dependencies { 385 | dependents(feature_dependencies, dependency, collected); 386 | } 387 | } 388 | } 389 | 390 | fn parse_feature_deps<'a>( 391 | s: &'a str, 392 | dep: &str, 393 | ) -> Result + 'a, String> { 394 | Ok(s.trim() 395 | .strip_prefix('[') 396 | .and_then(|r| r.strip_suffix(']')) 397 | .ok_or_else(|| format!("Parse error while parsing dependency {}", dep))? 398 | .split(',') 399 | .map(|d| d.trim().trim_matches(|c| c == '"' || c == '\'').trim().to_string()) 400 | .filter(|d: &String| !d.is_empty())) 401 | } 402 | 403 | fn process_toml(cargo_toml: &str, args: &Args) -> Result { 404 | // Get all lines between the "[features]" and the next block 405 | let mut lines = cargo_toml 406 | .lines() 407 | .map(str::trim) 408 | // and skip empty lines and comments that are not docs comments 409 | .filter(|l| { 410 | !l.is_empty() && (!l.starts_with('#') || l.starts_with("##") || l.starts_with("#!")) 411 | }); 412 | let mut top_comment = String::new(); 413 | let mut current_comment = String::new(); 414 | let mut features = vec![]; 415 | let mut default_features = HashSet::new(); 416 | let mut current_table = ""; 417 | let mut dependencies = HashMap::new(); 418 | while let Some(line) = lines.next() { 419 | if let Some(x) = line.strip_prefix("#!") { 420 | if !x.is_empty() && !x.starts_with(' ') { 421 | continue; // it's not a doc comment 422 | } 423 | if !current_comment.is_empty() { 424 | return Err("Cannot mix ## and #! comments between features.".into()); 425 | } 426 | if top_comment.is_empty() && !features.is_empty() { 427 | top_comment = "\n".into(); 428 | } 429 | writeln!(top_comment, "{}", x).unwrap(); 430 | } else if let Some(x) = line.strip_prefix("##") { 431 | if !x.is_empty() && !x.starts_with(' ') { 432 | continue; // it's not a doc comment 433 | } 434 | writeln!(current_comment, " {}", x).unwrap(); 435 | } else if let Some(table) = line.strip_prefix('[') { 436 | current_table = table 437 | .split_once(']') 438 | .map(|(t, _)| t.trim()) 439 | .ok_or_else(|| format!("Parse error while parsing line: {}", line))?; 440 | if !current_comment.is_empty() { 441 | #[allow(clippy::unnecessary_lazy_evaluations)] 442 | let dep = current_table 443 | .rsplit_once('.') 444 | .and_then(|(table, dep)| table.trim().ends_with("dependencies").then(|| dep)) 445 | .ok_or_else(|| format!("Not a feature: `{}`", line))?; 446 | features.push(( 447 | dep.trim(), 448 | std::mem::take(&mut top_comment), 449 | std::mem::take(&mut current_comment), 450 | )); 451 | } 452 | } else if let Some((dep, rest)) = line.split_once('=') { 453 | let dep = dep.trim().trim_matches('"'); 454 | let rest = get_balanced(rest, &mut lines) 455 | .map_err(|e| format!("Parse error while parsing value {}: {}", dep, e))?; 456 | if current_table == "features" { 457 | if dep == "default" { 458 | default_features.extend(parse_feature_deps(&rest, dep)?); 459 | } else { 460 | for d in parse_feature_deps(&rest, dep)? { 461 | dependencies 462 | .entry(dep.to_string()) 463 | .or_insert_with(Vec::new) 464 | .push(d.clone()); 465 | } 466 | } 467 | } 468 | if !current_comment.is_empty() { 469 | if current_table.ends_with("dependencies") { 470 | if !rest 471 | .split_once("optional") 472 | .and_then(|(_, r)| r.trim().strip_prefix('=')) 473 | .map_or(false, |r| r.trim().starts_with("true")) 474 | { 475 | return Err(format!("Dependency {} is not an optional dependency", dep)); 476 | } 477 | } else if current_table != "features" { 478 | return Err(format!( 479 | r#"Comment cannot be associated with a feature: "{}""#, 480 | current_comment.trim() 481 | )); 482 | } 483 | features.push(( 484 | dep, 485 | std::mem::take(&mut top_comment), 486 | std::mem::take(&mut current_comment), 487 | )); 488 | } 489 | } 490 | } 491 | let df = default_features.iter().cloned().collect::>(); 492 | for feature in df { 493 | let mut resolved = HashSet::new(); 494 | dependents(&dependencies, &feature, &mut resolved); 495 | default_features.extend(resolved.into_iter()); 496 | } 497 | if !current_comment.is_empty() { 498 | return Err("Found comment not associated with a feature".into()); 499 | } 500 | if features.is_empty() { 501 | return Ok("*No documented features in Cargo.toml*".into()); 502 | } 503 | let mut result = String::new(); 504 | for (f, top, comment) in features { 505 | let default = if default_features.contains(f) { " *(enabled by default)*" } else { "" }; 506 | let feature_label = args.feature_label.as_deref().unwrap_or("**`{feature}`**"); 507 | let comment = if comment.trim().is_empty() { 508 | String::new() 509 | } else { 510 | format!(" —{}", comment.trim_end()) 511 | }; 512 | 513 | writeln!( 514 | result, 515 | "{}* {}{}{}", 516 | top, 517 | feature_label.replace("{feature}", f), 518 | default, 519 | comment, 520 | ) 521 | .unwrap(); 522 | } 523 | result += &top_comment; 524 | Ok(result) 525 | } 526 | 527 | fn get_balanced<'a>( 528 | first_line: &'a str, 529 | lines: &mut impl Iterator, 530 | ) -> Result, String> { 531 | let mut line = first_line; 532 | let mut result = Cow::from(""); 533 | 534 | let mut in_quote = false; 535 | let mut level = 0; 536 | loop { 537 | let mut last_slash = false; 538 | for (idx, b) in line.as_bytes().iter().enumerate() { 539 | if last_slash { 540 | last_slash = false 541 | } else if in_quote { 542 | match b { 543 | b'\\' => last_slash = true, 544 | b'"' | b'\'' => in_quote = false, 545 | _ => (), 546 | } 547 | } else { 548 | match b { 549 | b'\\' => last_slash = true, 550 | b'"' => in_quote = true, 551 | b'{' | b'[' => level += 1, 552 | b'}' | b']' if level == 0 => return Err("unbalanced source".into()), 553 | b'}' | b']' => level -= 1, 554 | b'#' => { 555 | line = &line[..idx]; 556 | break; 557 | } 558 | _ => (), 559 | } 560 | } 561 | } 562 | if result.len() == 0 { 563 | result = Cow::from(line); 564 | } else { 565 | *result.to_mut() += line; 566 | } 567 | if level == 0 { 568 | return Ok(result); 569 | } 570 | line = if let Some(l) = lines.next() { 571 | l 572 | } else { 573 | return Err("unbalanced source".into()); 574 | }; 575 | } 576 | } 577 | 578 | #[test] 579 | fn test_get_balanced() { 580 | assert_eq!( 581 | get_balanced( 582 | "{", 583 | &mut IntoIterator::into_iter(["a", "{ abc[], #ignore", " def }", "}", "xxx"]) 584 | ), 585 | Ok("{a{ abc[], def }}".into()) 586 | ); 587 | assert_eq!( 588 | get_balanced("{ foo = \"{#\" } #ignore", &mut IntoIterator::into_iter(["xxx"])), 589 | Ok("{ foo = \"{#\" } ".into()) 590 | ); 591 | assert_eq!( 592 | get_balanced("]", &mut IntoIterator::into_iter(["["])), 593 | Err("unbalanced source".into()) 594 | ); 595 | } 596 | 597 | #[cfg(feature = "self-test")] 598 | #[proc_macro] 599 | #[doc(hidden)] 600 | /// Helper macro for the tests. Do not use 601 | pub fn self_test_helper(input: TokenStream) -> TokenStream { 602 | let mut code = String::new(); 603 | for line in (&input).to_string().trim_matches(|c| c == '"' || c == '#').lines() { 604 | // Rustdoc removes the lines that starts with `# ` and removes one `#` from lines that starts with # followed by space. 605 | // We need to re-add the `#` that was removed by rustdoc to get the original. 606 | if line.strip_prefix('#').map_or(false, |x| x.is_empty() || x.starts_with(' ')) { 607 | code += "#"; 608 | } 609 | code += line; 610 | code += "\n"; 611 | } 612 | process_toml(&code, &Args::default()).map_or_else( 613 | |e| error(&e), 614 | |r| std::iter::once(proc_macro::TokenTree::from(proc_macro::Literal::string(&r))).collect(), 615 | ) 616 | } 617 | 618 | #[cfg(feature = "self-test")] 619 | macro_rules! self_test { 620 | (#[doc = $toml:literal] => #[doc = $md:literal]) => { 621 | concat!( 622 | "\n`````rust\n\ 623 | fn normalize_md(md : &str) -> String { 624 | md.lines().skip_while(|l| l.is_empty()).map(|l| l.trim()) 625 | .collect::>().join(\"\\n\") 626 | } 627 | assert_eq!(normalize_md(document_features::self_test_helper!(", 628 | stringify!($toml), 629 | ")), normalize_md(", 630 | stringify!($md), 631 | "));\n`````\n\n" 632 | ) 633 | }; 634 | } 635 | 636 | #[cfg(not(feature = "self-test"))] 637 | macro_rules! self_test { 638 | (#[doc = $toml:literal] => #[doc = $md:literal]) => { 639 | concat!( 640 | "This contents in Cargo.toml:\n`````toml", 641 | $toml, 642 | "\n`````\n Generates the following:\n\ 643 |
Preview
\n\n", 644 | $md, 645 | "\n
\n\n \n", 646 | ) 647 | }; 648 | } 649 | 650 | use self_test; 651 | 652 | // The following struct is inserted only during generation of the documentation in order to exploit doc-tests. 653 | // These doc-tests are used to check that invalid arguments to the `document_features!` macro cause a compile time error. 654 | // For a more principled way of testing compilation error, maybe investigate . 655 | // 656 | /// ```rust 657 | /// #![doc = document_features::document_features!()] 658 | /// #![doc = document_features::document_features!(feature_label = "**`{feature}`**")] 659 | /// #![doc = document_features::document_features!(feature_label = r"**`{feature}`**")] 660 | /// #![doc = document_features::document_features!(feature_label = r#"**`{feature}`**"#)] 661 | /// #![doc = document_features::document_features!(feature_label = "{feature}")] 662 | /// #![doc = document_features::document_features!(feature_label = r#"{feature}"#)] 663 | /// ``` 664 | /// ```compile_fail 665 | /// #![doc = document_features::document_features!(feature_label > "{feature}")] 666 | /// ``` 667 | /// ```compile_fail 668 | /// #![doc = document_features::document_features!(label = "{feature}")] 669 | /// ``` 670 | /// ```compile_fail 671 | /// #![doc = document_features::document_features!(feature_label = "{feat}")] 672 | /// ``` 673 | /// ```compile_fail 674 | /// #![doc = document_features::document_features!(feature_label = 3.14)] 675 | /// ``` 676 | /// ```compile_fail 677 | /// #![doc = document_features::document_features!(feature_label = )] 678 | /// ``` 679 | /// ```compile_fail 680 | /// #![doc = document_features::document_features!(feature_label = "**`{feature}`**" extra)] 681 | /// ``` 682 | #[cfg(doc)] 683 | struct FeatureLabelCompilationTest; 684 | 685 | #[cfg(test)] 686 | mod tests { 687 | use super::{process_toml, Args}; 688 | 689 | #[track_caller] 690 | fn test_error(toml: &str, expected: &str) { 691 | let err = process_toml(toml, &Args::default()).unwrap_err(); 692 | assert!(err.contains(expected), "{:?} does not contain {:?}", err, expected) 693 | } 694 | 695 | #[test] 696 | fn only_get_balanced_in_correct_table() { 697 | process_toml( 698 | r#" 699 | 700 | [package.metadata.release] 701 | pre-release-replacements = [ 702 | {test=\"\#\# \"}, 703 | ] 704 | [abcd] 705 | [features]#xyz 706 | #! abc 707 | # 708 | ### 709 | #! def 710 | #! 711 | ## 123 712 | ## 456 713 | feat1 = ["plop"] 714 | #! ghi 715 | no_doc = [] 716 | ## 717 | feat2 = ["momo"] 718 | #! klm 719 | default = ["feat1", "something_else"] 720 | #! end 721 | "#, 722 | &Args::default(), 723 | ) 724 | .unwrap(); 725 | } 726 | 727 | #[test] 728 | fn no_features() { 729 | let r = process_toml( 730 | r#" 731 | [features] 732 | [dependencies] 733 | foo = 4; 734 | "#, 735 | &Args::default(), 736 | ) 737 | .unwrap(); 738 | assert_eq!(r, "*No documented features in Cargo.toml*"); 739 | } 740 | 741 | #[test] 742 | fn no_features2() { 743 | let r = process_toml( 744 | r#" 745 | [packages] 746 | [dependencies] 747 | "#, 748 | &Args::default(), 749 | ) 750 | .unwrap(); 751 | assert_eq!(r, "*No documented features in Cargo.toml*"); 752 | } 753 | 754 | #[test] 755 | fn parse_error3() { 756 | test_error( 757 | r#" 758 | [features] 759 | ff = [] 760 | [abcd 761 | efgh 762 | [dependencies] 763 | "#, 764 | "Parse error while parsing line: [abcd", 765 | ); 766 | } 767 | 768 | #[test] 769 | fn parse_error4() { 770 | test_error( 771 | r#" 772 | [features] 773 | ## dd 774 | ## ff 775 | #! ee 776 | ## ff 777 | "#, 778 | "Cannot mix", 779 | ); 780 | } 781 | 782 | #[test] 783 | fn parse_error5() { 784 | test_error( 785 | r#" 786 | [features] 787 | ## dd 788 | "#, 789 | "not associated with a feature", 790 | ); 791 | } 792 | 793 | #[test] 794 | fn parse_error6() { 795 | test_error( 796 | r#" 797 | [features] 798 | # ff 799 | foo = [] 800 | default = [ 801 | #ffff 802 | # ff 803 | "#, 804 | "Parse error while parsing value default", 805 | ); 806 | } 807 | 808 | #[test] 809 | fn parse_error7() { 810 | test_error( 811 | r#" 812 | [features] 813 | # f 814 | foo = [ x = { ] 815 | bar = [] 816 | "#, 817 | "Parse error while parsing value foo", 818 | ); 819 | } 820 | 821 | #[test] 822 | fn not_a_feature1() { 823 | test_error( 824 | r#" 825 | ## hallo 826 | [features] 827 | "#, 828 | "Not a feature: `[features]`", 829 | ); 830 | } 831 | 832 | #[test] 833 | fn not_a_feature2() { 834 | test_error( 835 | r#" 836 | [package] 837 | ## hallo 838 | foo = [] 839 | "#, 840 | "Comment cannot be associated with a feature: \"hallo\"", 841 | ); 842 | } 843 | 844 | #[test] 845 | fn non_optional_dep1() { 846 | test_error( 847 | r#" 848 | [dev-dependencies] 849 | ## Not optional 850 | foo = { version = "1.2", optional = false } 851 | "#, 852 | "Dependency foo is not an optional dependency", 853 | ); 854 | } 855 | 856 | #[test] 857 | fn non_optional_dep2() { 858 | test_error( 859 | r#" 860 | [dev-dependencies] 861 | ## Not optional 862 | foo = { version = "1.2" } 863 | "#, 864 | "Dependency foo is not an optional dependency", 865 | ); 866 | } 867 | 868 | #[test] 869 | fn basic() { 870 | let toml = r#" 871 | [abcd] 872 | [features]#xyz 873 | #! abc 874 | # 875 | ### 876 | #! def 877 | #! 878 | ## 123 879 | ## 456 880 | feat1 = ["plop"] 881 | #! ghi 882 | no_doc = [] 883 | ## 884 | feat2 = ["momo"] 885 | #! klm 886 | default = ["feat1", "something_else"] 887 | #! end 888 | "#; 889 | let parsed = process_toml(toml, &Args::default()).unwrap(); 890 | assert_eq!( 891 | parsed, 892 | " abc\n def\n\n* **`feat1`** *(enabled by default)* — 123\n 456\n\n ghi\n* **`feat2`**\n\n klm\n end\n" 893 | ); 894 | let parsed = process_toml( 895 | toml, 896 | &Args { 897 | feature_label: Some( 898 | "{feature}".into(), 899 | ), 900 | }, 901 | ) 902 | .unwrap(); 903 | assert_eq!( 904 | parsed, 905 | " abc\n def\n\n* feat1 *(enabled by default)* — 123\n 456\n\n ghi\n* feat2\n\n klm\n end\n" 906 | ); 907 | } 908 | 909 | #[test] 910 | fn dependencies() { 911 | let toml = r#" 912 | #! top 913 | [dev-dependencies] #yo 914 | ## dep1 915 | dep1 = { version="1.2", optional=true} 916 | #! yo 917 | dep2 = "1.3" 918 | ## dep3 919 | [target.'cfg(unix)'.build-dependencies.dep3] 920 | version = "42" 921 | optional = true 922 | "#; 923 | let parsed = process_toml(toml, &Args::default()).unwrap(); 924 | assert_eq!(parsed, " top\n* **`dep1`** — dep1\n\n yo\n* **`dep3`** — dep3\n"); 925 | let parsed = process_toml( 926 | toml, 927 | &Args { 928 | feature_label: Some( 929 | "{feature}".into(), 930 | ), 931 | }, 932 | ) 933 | .unwrap(); 934 | assert_eq!(parsed, " top\n* dep1 — dep1\n\n yo\n* dep3 — dep3\n"); 935 | } 936 | 937 | #[test] 938 | fn multi_lines() { 939 | let toml = r#" 940 | [package.metadata.foo] 941 | ixyz = [ 942 | ["array"], 943 | [ 944 | "of", 945 | "arrays" 946 | ] 947 | ] 948 | [dev-dependencies] 949 | ## dep1 950 | dep1 = { 951 | version="1.2-}", 952 | optional=true 953 | } 954 | [features] 955 | default = [ 956 | "goo", 957 | "\"]", 958 | "bar", 959 | ] 960 | ## foo 961 | foo = [ 962 | "bar" 963 | ] 964 | ## bar 965 | bar = [ 966 | 967 | ] 968 | "#; 969 | let parsed = process_toml(toml, &Args::default()).unwrap(); 970 | assert_eq!( 971 | parsed, 972 | "* **`dep1`** — dep1\n* **`foo`** — foo\n* **`bar`** *(enabled by default)* — bar\n" 973 | ); 974 | let parsed = process_toml( 975 | toml, 976 | &Args { 977 | feature_label: Some( 978 | "{feature}".into(), 979 | ), 980 | }, 981 | ) 982 | .unwrap(); 983 | assert_eq!( 984 | parsed, 985 | "* dep1 — dep1\n* foo — foo\n* bar *(enabled by default)* — bar\n" 986 | ); 987 | } 988 | 989 | #[test] 990 | fn dots_in_feature() { 991 | let toml = r#" 992 | [features] 993 | ## This is a test 994 | "teßt." = [] 995 | default = ["teßt."] 996 | [dependencies] 997 | ## A dep 998 | "dep" = { version = "123", optional = true } 999 | "#; 1000 | let parsed = process_toml(toml, &Args::default()).unwrap(); 1001 | assert_eq!( 1002 | parsed, 1003 | "* **`teßt.`** *(enabled by default)* — This is a test\n* **`dep`** — A dep\n" 1004 | ); 1005 | let parsed = process_toml( 1006 | toml, 1007 | &Args { 1008 | feature_label: Some( 1009 | "{feature}".into(), 1010 | ), 1011 | }, 1012 | ) 1013 | .unwrap(); 1014 | assert_eq!( 1015 | parsed, 1016 | "* teßt. *(enabled by default)* — This is a test\n* dep — A dep\n" 1017 | ); 1018 | } 1019 | 1020 | #[test] 1021 | fn recursive_default() { 1022 | let toml = r#" 1023 | [features] 1024 | default=["qqq"] 1025 | 1026 | ## Qqq 1027 | qqq=["www"] 1028 | 1029 | ## Www 1030 | www=[] 1031 | "#; 1032 | let parsed = process_toml(toml, &Args::default()).unwrap(); 1033 | assert_eq!(parsed, "* **`qqq`** *(enabled by default)* — Qqq\n* **`www`** *(enabled by default)* — Www\n"); 1034 | } 1035 | } 1036 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | use_small_heuristics = "Max" 2 | -------------------------------------------------------------------------------- /tests/self-doc.rs: -------------------------------------------------------------------------------- 1 | #[test] 2 | fn ensure_it_compiles() { 3 | document_features::document_features!(); 4 | document_features::document_features!(feature_label = "**`{feature}`**"); 5 | document_features::document_features!(feature_label = r"**`{feature}`**"); 6 | document_features::document_features!(feature_label = r#"**`{feature}`**"#); 7 | document_features::document_features!( 8 | feature_label = "{feature}" 9 | ); 10 | document_features::document_features!( 11 | feature_label = r#"{feature}"# 12 | ); 13 | document_features::document_features!( 14 | feature_label = r##"{feature}"## 15 | ); 16 | } 17 | 18 | #[test] 19 | fn self_doc() { 20 | let actual = document_features::document_features!(); 21 | let expected = "* **`self-test`** — Internal feature used only for the tests, don't enable\n"; 22 | assert_eq!(actual, expected); 23 | } 24 | 25 | #[test] 26 | fn self_doc_with_custom_label() { 27 | let actual = document_features::document_features!( 28 | feature_label = r#"{feature}"# 29 | ); 30 | let expected = 31 | "* self-test — Internal feature used only for the tests, don't enable\n"; 32 | assert_eq!(actual, expected); 33 | let actual2 = document_features::document_features!( 34 | feature_label = "{feature}" 35 | ); 36 | assert_eq!(actual2, expected); 37 | } 38 | --------------------------------------------------------------------------------