GithubHelp home page GithubHelp logo

cargo-readme's Introduction

Crates.io Workflow Status

cargo-readme

Generate README.md from doc comments.

Cargo subcommand that extract documentation from your crate's doc comments that you can use to populate your README.md.

Attribution

This library was authored by Livio Ribeiro (@livioribeiro) and originally located at https://github.com/livioribeiro/cargo-readme, which now redirects here (as of August 2023). Thank you, Livio, for this lib!

Installation

cargo install cargo-readme

Motivation

As you write documentation, you often have to show examples of how to use your software. But how do you make sure your examples are all working properly? That we didn't forget to update them after a breaking change and left our (possibly new) users with errors they will have to figure out by themselves?

With cargo-readme, you just write the rustdoc, run the tests, and then run:

cargo readme > README.md

And that's it! Your README.md is populated with the contents of the doc comments from your lib.rs (or main.rs).

Usage

Let's take the following rust doc:

//! This is my awesome crate
//!
//! Here goes some other description of what it is and what is does
//!
//! # Examples
//! ```
//! fn sum2(n1: i32, n2: i32) -> i32 {
//!   n1 + n2
//! }
//! # assert_eq!(4, sum2(2, 2));
//! ```

Running cargo readme will output the following:

[![Build Status](__badge_image__)](__badge_url__)

# my_crate

This is my awesome crate

Here goes some other description of what it is and what is does

## Examples
```rust
fn sum2(n1: i32, n2: i32) -> i32 {
  n1 + n2
}
```

License: MY_LICENSE

Let's see what's happened:

  • a badge was created from the one defined in the [badges] section of Cargo.toml
  • the crate name ("my-crate") was added
  • "# Examples" heading became "## Examples"
  • code block became "```rust"
  • hidden line # assert_eq!(4, sum2(2, 2)); was removed

cargo-readme also supports multiline doc comments /*! */ (but you cannot mix styles):

/*!
This is my awesome crate

Here goes some other description of what it is and what is does

```
fn sum2(n1: i32, n2: i32) -> i32 {
  n1 + n2
}
```
*/

If you have additional information that does not fit in doc comments, you can use a template. Just create a file called README.tpl in the same directory as Cargo.toml with the following content:

{{badges}}

# {{crate}}

{{readme}}

Current version: {{version}}

Some additional info here

License: {{license}}

The output will look like this

[![Build Status](__badge_image__)](__badge_url__)

# my_crate

Current version: 3.0.0

This is my awesome crate

Here goes some other description of what it is and what is does

## Examples
```rust
fn sum2(n1: i32, n2: i32) -> i32 {
  n1 + n2
}
```

Some additional info here

License: MY_LICENSE

By default, README.tpl will be used as the template, but you can override it using the --template to choose a different template or --no-template to disable it.

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

cargo-readme's People

Contributors

antifuchs avatar emberian avatar jeanmertz avatar livioribeiro avatar mendelt avatar mexus avatar msrd0 avatar otavio avatar psyomn avatar scattenlaeufer avatar webern avatar xoac avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

cargo-readme's Issues

Relicense under dual MIT/Apache-2.0

This issue was automatically generated. Feel free to close without ceremony if
you do not agree with re-licensing or if it is not possible for other reasons.
Respond to @cmr with any questions or concerns, or pop over to
#rust-offtopic on IRC to discuss.

You're receiving this because someone (perhaps the project maintainer)
published a crates.io package with the license as "MIT" xor "Apache-2.0" and
the repository field pointing here.

TL;DR the Rust ecosystem is largely Apache-2.0. Being available under that
license is good for interoperation. The MIT license as an add-on can be nice
for GPLv2 projects to use your code.

Why?

The MIT license requires reproducing countless copies of the same copyright
header with different names in the copyright field, for every MIT library in
use. The Apache license does not have this drawback. However, this is not the
primary motivation for me creating these issues. The Apache license also has
protections from patent trolls and an explicit contribution licensing clause.
However, the Apache license is incompatible with GPLv2. This is why Rust is
dual-licensed as MIT/Apache (the "primary" license being Apache, MIT only for
GPLv2 compat), and doing so would be wise for this project. This also makes
this crate suitable for inclusion and unrestricted sharing in the Rust
standard distribution and other projects using dual MIT/Apache, such as my
personal ulterior motive, the Robigalia project.

Some ask, "Does this really apply to binary redistributions? Does MIT really
require reproducing the whole thing?" I'm not a lawyer, and I can't give legal
advice, but some Google Android apps include open source attributions using
this interpretation. Others also agree with
it
.
But, again, the copyright notice redistribution is not the primary motivation
for the dual-licensing. It's stronger protections to licensees and better
interoperation with the wider Rust ecosystem.

How?

To do this, get explicit approval from each contributor of copyrightable work
(as not all contributions qualify for copyright, due to not being a "creative
work", e.g. a typo fix) and then add the following to your README:

## License

Licensed under either of

 * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
 * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)

at your option.

### Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any
additional terms or conditions.

and in your license headers, if you have them, use the following boilerplate
(based on that used in Rust):

// Copyright 2016 cargo-readme developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

It's commonly asked whether license headers are required. I'm not comfortable
making an official recommendation either way, but the Apache license
recommends it in their appendix on how to use the license.

Be sure to add the relevant LICENSE-{MIT,APACHE} files. You can copy these
from the Rust repo for a plain-text
version.

And don't forget to update the license metadata in your Cargo.toml to:

license = "MIT/Apache-2.0"

I'll be going through projects which agree to be relicensed and have approval
by the necessary contributors and doing this changes, so feel free to leave
the heavy lifting to me!

Contributor checkoff

To agree to relicensing, comment with :

I license past and future contributions under the dual MIT/Apache-2.0 license, allowing licensees to chose either at their option.

Or, if you're a contributor, you can check the box in this repo next to your
name. My scripts will pick this exact phrase up and check your checkbox, but
I'll come through and manually review this issue later as well.

Feature request: attach binaries to github releases

First off: thanks for a lovely tool; I use it for a ton of my crates :)

I also include #[test]s to make sure that the readme is up-to-date, and run them in CI, for when folks send me PRs.

I install cargo readme via cargo install cargo-readme in CI. This makes my builds a bit slower than I'd like, since building cargo readme is not super fast. It would be super awesome if I could instead curl the binary from a github release.

We do a similar thing with appveyor and travis for the wasm-pack project, and it might be helpful to look at if/when adding the config for this repo.

https://github.com/rustwasm/wasm-pack/blob/6d376483d7431b3f2db4de82a52b1cbdca872fea/.appveyor.yml#L21-L44

https://github.com/rustwasm/wasm-pack/blob/2c2627d3202335f886f4b66d9b5356449cac1ac3/.travis.yml#L78-L95

Whitespace trimming breaks line break functionality

Whitespace trimming seems to break line breaks in markdown as it is defined as two space at the end of a line.

Input (double space is there)

//! Line 1  
//! Line 2  
//! Line 3  

Expected output (double space is there)

markdown:

Line 1  
Line 2  
Line 3  

html:

Line 1
<br>
Line 2
<br>
Line 3

Actual output (double space is gone)

markdown:

Line 1
Line 2
Line 3

html:

Line 1 Line 2 Line 3

Thank You! ๐ŸŽ‰

I have needed this for a while. It is an annoyance present in my every rust project large or small that I have to sync the lib.rs and the README.md usually resulting in a lower quality of documentaiton for them both! Thank you for this project!

Anyway, this is not an actionable issue, so I'll close this myself immediately. ๐Ÿ˜‰

Thanks again!

Code blocks metadata translated incorrectly

If I annotate the crate docs with, for example, "no_run" to make the doctest not run:

//! ```rust,no_run
//! // My code
//! ```

It is translated, incorrectly, into:

```rust
// My code
```rust

That last "rust" should not be there :)

Include feature gated docs

Some of my docs are behind feature flags, e.g.

//!  In general, you can use the library like this
//! ```rust
//! use my_lib::foo;
//! assert!(foo())
//! ```
#![cfg_attr(
    feature = "serde",
    doc = r##"
## integration with `serde`

if you've enabled the optional `serde` feature, you can use the lib in fancy new ways!

\```rust
use my_lib::foo_method_that_requires_serde;

assert!(foo_method_that_requires_serde());
\```
"##
)]

However these aren't recognized as doc comments by cargo-readme.

rustdoc uses cfg/feature gated comments to produce UI like this, which I think is nice:
image

But perhaps less subjectively, doctests that require a feature will fail if that feature isn't enabled.

A brief dive into cargo-readme shows that this might be non-trivial. It looks like currently cargo-readme has implemented it's own parsing for comment extraction. I have no idea if it's possible, but maybe cargo-readme could actually use librustdoc to extract and parse comments?

Or, if you're feeling really evil you could generate the docs with rustdoc and parse the html back into markdown ๐Ÿ˜ˆ

last line is empty

using cargo readme > README.md with a README.tpl the last line of the generated readme contains an empty line.

Weird encoding issue on Windows

The โ€” (EM DASH) symbol in my doc comment got converted to gibberish from my current code page (cp1251). This might mean that the tool reads files in cp1251 but outputs them as UTF-8.

Support `compile_fail` option in an example section

The argument is described in https://doc.rust-lang.org/rustdoc/documentation-tests.html#attributes

This snipped is not recognized as rust code.

//! ```rust,compile_fail
//! use tabled::Tabled;
//!
//! #[derive(Tabled)]
//! struct SomeType {
//! field1: SomeOtherType,
//! }
//! 
//! struct SomeOtherType;
//! ```

The correct behavior should be the same as no_run, ignore, should_panic options has

use tabled::Tabled;

#[derive(Tabled)]
struct SomeType {
field1: SomeOtherType,
}

struct SomeOtherType;

For crates with binaries, allow writing of --help docs to README

Possibly best supported in the template file, something like

# {{crate}}

{{readme}}

## Binaries

### `my_bin_name`

{{bin:my_bin_name --help}}

### `my_other_bin`

{{bin:my_other_bin -h}}

which would produce something like

# my_crate

Some information I've totally written in my crate docs.

## Binaries

### `my_bin_name`

```
usage: my_bin_name [-h] arg [arg ...]

positional arguments:
  arg

options:
  -h, --help            show this help message and exit
```

### `my_other_bin`

```
usage: my_other_bin [-h] arg [arg ...]

positional arguments:
  arg

options:
  -h, --help            show this help message and exit
```

This would allow somewhat-arbitrary code execution which isn't ideal but this is a really useful feature to have when it comes to self-documentation. My current solution is a python script which pipes text into a labelled code block: https://pypi.org/project/pipe2codeblock/

Feature request: output binaries' `--help` into template

Keeping a binary crate's usage information up to date with the crate itself is really helpful. I made a very hacky python tool for piping text into markdown code blocks for this purpose, so my README would look like

# My package

## Usage

```_mybinary
```

Then do cargo run -- --help | pipe2codeblock --tgt _mybinary README.md to dump the help text into that labelled code block, and git diff --exit-code in CI to make sure every commit has it up to date.

I'd love to replace that with a template with cargo-readme: do you think that would be helpful?

Missing git tag 3.3.0

The 3.2.0 tag is also missing - now the 3.3.0 is missing as well.

We cannot even package the update in nixpkgs, because we don't know which commit the release was made from.

I would advise you yank the release on crates.io, because nobody is able to reproduce it, and create a new release 3.4.0 with a tag in this repository. Feel free to ping me then for updating the nixpkgs package.

build.rs example

I like to auto-generate the README with a build.rs build script so I don't forget to update it manually.

The snippet I use:

extern crate cargo_readme;

use std::{fs, path};
use std::io::Write;

fn main() {
    // Generate README.md with cargo_readme.

    let mut f = fs::File::open("src/lib.rs").unwrap();
    let content = cargo_readme::generate_readme(
        &path::PathBuf::from("./"),
        &mut f,
        None,
        false,
        false,
        false,
    ).unwrap();

    let mut f = fs::File::create("README.md").unwrap();
    f.write_all(content.as_bytes()).unwrap();
}

It would be nice to have this snippet in the docs somewhere so you can just copy/paste.

What do you thing, @livioribeiro ?

Relative file paths are resolved from the wrong path

First off, thanks for the great tool! It's, at the very least, a great holdover until the external_doc feature stabilizes.

I'm working on a project that's a Cargo workspace, so the root of my repository contains my README.md and only a virtual manifest.

If I run cargo-readme in my project root, I get an error hinting that there's no [package] section in my Cargo.toml:

$ cargo readme -o README.md
Error: missing field `package`

I noticed that the -r flag lets me set the project root, which I started using to tell cargo-readme which crate to actually use, so I tried:

$ cargo readme -r snax -o README.md

This writes to snax/README.md instead of ./README.md like I expected! In other words, it behaves differently than:

$ cargo readme -r snax > README.md

Is this intentional?

$ cargo readme --version
cargo-readme v3.1.2

# comments don't get stripped from example code if the ``` is annotated

This example from the readme correctly strips the assert_eq line from the resulting markdown:

//! ```
//! fn sum2(n1: i32, n2: i32) -> i32 {
//!   n1 + n2
//! }
//! # assert_eq!(4, sum2(2, 2));
//! ```

But if I annotate the backticks with a language name, like this, the assert_eq line becomes visible in the result:

//! ```rust
//! fn sum2(n1: i32, n2: i32) -> i32 {
//!   n1 + n2
//! }
//! # assert_eq!(4, sum2(2, 2));
//! ```

Empty readme on latest version with README.tpl

The generated readme is empty. The {{readme}} does not seem to work anymore.

cargo install cargo-readme
cargo readme

with a README.tpl of:

[![Build Status](https://travis-ci.org/fschutt/printpdf.svg?branch=master)](https://travis-ci.org/fschutt/printpdf)

{{readme}}

The generated file only contains the badge, not the actual readme content. Can you reproduce this?

rustc 1.23.0-nightly (8b22e70b2 2017-10-31)
binary: rustc
commit-hash: 8b22e70b2de5152db3b0c53cfa16eb96b0b9e40e
commit-date: 2017-10-31
host: x86_64-unknown-linux-gnu
release: 1.23.0-nightly
LLVM version: 4.0

Generate rustdoc from README?

My project uses #![doc = include_str!("../README.md")] to generate the rustdoc for the crate from its README. However, I noticed a user forked it just to remove this line, ostensibly since they're using a Rust version < 1.54.

Does this crate support this opposite direction for the doc generation? For example, outputting rustdoc comments to stdout, or automatically replacing src/lib.rs rustdoc with the result.

I suppose I can also just convert the markdown to rustdoc manually, but I'm curious about a tool for this. Thanks!

Wishlist: delimit docs-only section

When a crate's documentation contains a point from where on it is not practical to include in the README any more, it would be convenient to add a magic marker (say, <!-- END OF README PART -->) into the text and cut it there.

For example, in https://gitlab.com/etonomy/riot-sys, the main part is about building and integration which is all good, but where it cuts to what is in the main crate vs. what is in pub modules, this belongs into the docs but not the README.

Feature Request: --locked flag for use in CI

Many cargo subcommands implement a --locked flag intended to be used in CI to verify that e.g. the content of the Cargo.lock file matches that of the Cargo.toml file. Since cargo readme updates the readme based on the contents of lib.rs, it would be nice if I could have my CI do something like

cargo readme -o README.md --locked

and have cargo readme verify that the output it would generate is identical to the present readme, without updating the file but rather fail with a non-zero exit code if the output differs.

Empty bedges shouldn't generate Error

Is there a reason for README.tpl that contains:

{{badges}}

generate error:

Error: `{{badges}}` was found in template but no badges were provided

It's ok to have no badges in my opinion and this shouldn't be error. At least warning.

Support template arguments in rustdoc

This can be done with the template file, but would it make sense for the rustdoc to also support template arguments? I currently have a rustdoc where the non-template output has been perfect, but I'd like to populate the version in the install instructions without creating a separate template file

I can understand if this is infeasible because the rustdoc is used elsewhere (crates.io?) where the template arguments wouldn't be parsed, so I guess this is more of a question than a request

Feature request: Option to add crates.io badge

The automatic badge from cargo.toml has been very helpful to me so far, not having to do tedious search, copy, and paste is amazing.
However there are one badge that many project use but aren't included in Cargo.toml's [badges], a crates.io badge.

Crates.io

Option to add crates.io badge would be very helpful for many project and doesn't seem difficult to add since project's name are in Cargo.toml.

Missing git tag 3.2.0

Hello!

Any chance you could push a tag 3.2.0 on cf66017. I believe cargo-readme has been pushed to crates.io but it's missing the git tag.

That makes it easier to package :)

Thank you!

Cargo.toml parsing expects path key when [lib] section is found.

Thank you for making cargo readme available. While using it I found a small issue

I tried running cargo readme on a crate with proc macro's in it. It had this section in its cargo.toml

[lib]
proc-macro = true

This causes cargo readme to fail with the error "Error: missing field path for key lib"
First of all this error could be made clearer, where was this field missing? what file?
But when the path key is not found it should just use the default src/lib.rs
For now I can get around this by adding

path = "src/lib.rs"

to Cargo.toml

Strip hidden lines from code blocks

I just publish a library with a bunch of code examples in the crate-level docs. These docs use a really neat feature of the Rust documentation code blocks, namely that # can be used to hide lines from the output example code. To quote the book:

You can add lines that start with #, and they will be hidden from the output, but will be used when compiling your code. You can use this to your advantage. In this case, documentation comments need to apply to some kind of function, so if I want to show you just a documentation comment, I need to add a little function definition below it. At the same time, it's only there to satisfy the compiler, so hiding it makes the example more clear. You can use this technique to explain longer examples in detail, while still preserving the testability of your documentation.

Unfortunately, cargo-readme doesn't support this at the moment, leading to some added noise in the extracted code segments: https://github.com/jonhoo/fantoccini#examples. It's not too bad for that particular library since I'm not hiding too many lines, but it can quickly distract from the main points of the example, so it'd be really neat if cargo-readme could also support hiding these lines!

Q: Dealing with submodules

Is there any way it can export documentation of submodule?

I would like my README.md to also include documentation of non-root module of my library.

Leading sharp in generated readme's example code

In the example code here there is a leading sharp in the first line that shouldn't be there. In the generated rustdoc it's not present.

Wrong Behaviour

The sharp followed by an empty line is included. Screenshot from the generated README:

image

Expected Behaviour

The sharp, along with the rest of the line, should not be included. Screenshot from the rustdoc:

image

Setup

Issue happens on both ArchLinux and AlpineLinux, Rust/Cargo 1.38.0, Cargo-Readme 3.1.2

Workspace usage error

When I try to use cargo readme in a workspace directory I get this error:

Error: missing field path for key lib at line 23 column 1

I have a workspace with many crates in it, and I'd like to generate individual README.mds for each one. I've tried both:

  • cargo readme -r subcrate > subcrate/README.md
  • (cd subcrate ; cargo readme > README.md)

With the same error message.

This is the workspace: https://github.com/emilk/egui/

An empty readme on v3.1.1

After updating to the v3 branch cargo-readme stopped working. The {{readme}} section is being replaced with nothing.

Here is the test crate. I'm using .tpl.

Support `document-features`

document-features is a crate that, like cargo-readme, tries to minimize copypasta for developers.

In this case, comments in the [features] section of a crate's Cargo.toml get used to populate a section in the docs; via a Rust macro. This is of ignored by cargo-readme as it would require to run on a source file after macro expansion.

Better handling of relative links

tsunami has a crate-local link (for a builder struct) in its top-level docs. While this works fine in generated documentation, that link is wrong when used in README.md. It'd be great if relative links could be removed in the generated readme, or if they could be made absolute relative to, say, docs.rs!

coveralls badge `branch` in URL query param

The coveralls badge has the branch URL query parameters set to the fixed string branch, instead of the user provided value for the branch attribute.

This is fixed in #68.

Current behavior:

For a badge configured like so:

$ tail -n1 Cargo.toml
coveralls = { repository = "owayss/huffman-encoding",  branch = "main" }

It configures the badge as:

$ cargo readme |grep coveralls
[![Coverage Status](https://coveralls.io/repos/github/owayss/huffman-encoding/badge.svg?branch=branch)](https://coveralls.io/github/owayss/huffman-encoding?branch=main)

Expected behavior

The branch URL query parameter should have the value provided for the branch attribute, that is, branch=main instead of branch=branch:

[![Coverage Status](https://coveralls.io/repos/github/owayss/huffman-encoding/badge.svg?branch=main)](https://coveralls.io/github/owayss/huffman-encoding?branch=main)

parse the whole file

Hi,

I noticed that only the header is parsed, so in other words, if I put rust code between two ///! blocks, the second block gets ignored.

Would it be possible to parse the whole thing? That way something like this would work:

///! description of what this does in general

fn main_function_that_does_something() {
    ///! # functionality
    ///! at the moment the following is supported
    do_something();
}

///! maybe even some closing remarks

that way the documentation lives right next to the code and I won't forget to update it as well ;)

Document supported badges

Right now the only way to discover which badges are supported in Cargo.toml is to carefully read the source.

The current list seems to be: "appveyor", "circle-ci", "gitlab", "travis-ci", "github",
"codecov", "coveralls", "is-it-maintained-issue-resolution",
"is-it-maintained-open-issues", "maintenance"

We could put these into the README. Better might be to support cargo readme --list-badges.

Either way, documentation on what each badge wants as text would also be helpful.

Let me know what you want to do and I'm happy to put together a PR.

Code fences have "rust" added to closing fence

The following doc comment:

//!
//! This crate frequently uses a trait bound like the following where subprocess
//! commands are required:
//!
//! ```none,actually-rust-but-see-https://github.com/rust-lang/rust/issues/63193
//! T where
//!     T: IntoIterator,
//!     T::Item: Into<OsString>
//! ```
//!
//! You can understand this as:
//! - `T` is anything that can turn into an iterator
//! - the iterator type is anything that can turn into an `OsString`
//!

Gets turned into:

This crate frequently uses a trait bound like the following where subprocess
commands are required:

```none,actually-rust-but-see-https://github.com/rust-lang/rust/issues/63193
T where
    T: IntoIterator,
    T::Item: Into<OsString>
```rust

You can understand this as:
- `T` is anything that can turn into an iterator
- the iterator type is anything that can turn into an `OsString`

The trailing ```rust should not be there. cargo doc seems to do the right thing, by comparison.

Using cargo-readme v3.2.0 on Rust 1.59.0 + Ubuntu 21.10.

Support for intra-doc links

Intra-doc links allow documentation authors to link to items by their path relative to the current module. It would be nice to resolve intra-doc links in the same way that rustdoc does, and make them point to the documentation at docs.rs or wherever else the API documentation is hosted.

Crash on `badges.is-it-maintained`

Information

cargo-readme version:
cargo-readme v3.1.2

rust version:
rustc 1.38.0-nightly (83e4eed16 2019-07-14)

Prior Art

No related issues found.

Issue

When I run cargo-readme against both the main crate and the subcrate in my project cargo-readme panics complaining:

thread 'main' panicked at 'no entry found for key', src/libcore/option.rs:1036:5
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.

If I remove badges.is-it-maintained-open-issues and badges.is-it-maintained-issue-resolution from the Cargo.toml it correctly outputs the readme file. This would suggest that these keys are things cargo-readme needs to be aware of.

Backtrace

thread 'main' panicked at 'no entry found for key', src/libcore/option.rs:1036:5
stack backtrace:
   0: std::sys::unix::backtrace::tracing::imp::unwind_backtrace
             at src/libstd/sys/unix/backtrace/tracing/gcc_s.rs:39
   1: std::sys_common::backtrace::_print
             at src/libstd/sys_common/backtrace.rs:71
   2: std::panicking::default_hook::{{closure}}
             at src/libstd/sys_common/backtrace.rs:59
             at src/libstd/panicking.rs:197
   3: std::panicking::default_hook
             at src/libstd/panicking.rs:211
   4: std::panicking::rust_panic_with_hook
             at src/libstd/panicking.rs:474
   5: std::panicking::continue_panic_fmt
             at src/libstd/panicking.rs:381
   6: rust_begin_unwind
             at src/libstd/panicking.rs:308
   7: core::panicking::panic_fmt
             at src/libcore/panicking.rs:85
   8: core::option::expect_failed
             at src/libcore/option.rs:1036
   9: cargo_readme::config::badges::is_it_maintained_issue_resolution
  10: <core::iter::adapters::FilterMap<I,F> as core::iter::traits::iterator::Iterator>::next
  11: <alloc::vec::Vec<T> as alloc::vec::SpecExtend<T,I>>::from_iter
  12: cargo_readme::config::manifest::get_manifest
  13: cargo_readme::helper::get_source
  14: cargo_readme::main
  15: std::rt::lang_start::{{closure}}
  16: std::panicking::try::do_call
             at src/libstd/rt.rs:49
             at src/libstd/panicking.rs:293
  17: __rust_maybe_catch_panic
             at src/libpanic_unwind/lib.rs:85
  18: std::rt::lang_start_internal
             at src/libstd/panicking.rs:272
             at src/libstd/panic.rs:394
             at src/libstd/rt.rs:48
  19: main
  20: __libc_start_main
  21: _start

stops parsing after first //! block

I've noticed the following limitations, which I'd like to report:

  • the content after the first //! block is missing
  • #![doc = include_str(...)] is not included

It looks like the parser only considers the first block of lines starting with //! and stops at the first line that doesn't start with //!.

Minimal Reproducible Example

This is src/lib.rs:

//! start of document
//!
//! # Examples
//!
//! ```rust,no_run
#![doc = include_str!("../examples/hello.rs")]
//! ```
//!
//! end of document

pub fn hello() {
    println!("hello");
}

This is examples/hello.rs:

fn main() {
    hello::hello();
}

The stuff after the first //! block is missing, i.e. neither the hello.rs example code, nor the end of document bit:

$ cargo readme --version
cargo-readme v3.2.0

$ cargo readme --no-title
start of document

## Examples

```rust

Add crate name as title

In order to add the # crate-name I have to use a template but in most cases I'd be happy to just use a flag like cargo readme --add-name-as-title.
And the same thing could be used for sections like the license. E.g. cargo readme --add-license-section would take the license property from the Cargo.toml and add a section like

## License
This project is licensed under the {{license}} license.

Just some ideas you might take for a next release :)

Obtain source file from Cargo.toml.

Currently if no input is given you check for "src/lib.rs" or "src/main.rs", it would be quite good if you "Cargo.toml" instead.

First you could check for a library table like

[lib]
path = "..."

then check the firs binary in the bin list

[[bin]]
path = "..."

then finally fall back to checking "src". Or maybe a better idea would be to check "src" first then fall back to "Cargo.toml", since most projects will stick to using "src".

Having said that I'm not sure the extra complexity would be worth it considering cargo readme --input=... isn't that diificult to call, it would be nice though.

Option to pull in struct/etc comments for documentation?

In binaries, I often use a configuration struct (via StructOpt) and all fields, data types for the configuration are properly commented on the structure(s) themselves. It would be great if cargo readme would pull documentation from more than just the file header. Thoughts?

Example:

//! Some file documentation

/// The configuration for the binary.
///
/// foo
#[derive(StructOpt, Debug)]
pub struct Config {
  /// Some port value.
  ///
  /// bar
  #[structopt(long, env = "PORT", default_value = "5051")]
  port: u16,
}

Might render to something like:

# Some file documentation

## The configuration for the binary.
foo

### Some port value
bar

Think this would be too difficult to "get right"? The only workaround I can think of is to copy the idiomatic documentation on the struct into the module header.. which seems, wrong. Thoughts?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.