Skip to main content

cargo_readme/readme/
mod.rs

1use std::io::{BufRead, BufReader, Read};
2use std::path::Path;
3
4mod extract;
5mod process;
6mod template;
7
8use crate::config;
9
10/// Toggles controlling how the README is generated.
11///
12/// Bundling these flags keeps `generate_readme` free of a long run of same-typed `bool`
13/// arguments, which are easy to transpose at the call site.
14#[derive(Debug, Clone, Copy)]
15pub struct ReadmeOptions {
16    /// Prepend the crate name as a title. Ignored when using a template.
17    pub add_title: bool,
18    /// Prepend the badges defined in `Cargo.toml`. Ignored when using a template.
19    pub add_badges: bool,
20    /// Append the license defined in `Cargo.toml`. Ignored when using a template.
21    pub add_license: bool,
22    /// Add an extra level to headings so the crate name can be the top heading.
23    pub indent_headings: bool,
24    /// Extract docs from comments rather than processing the input file as-is.
25    pub extract_from_comment: bool,
26}
27
28impl Default for ReadmeOptions {
29    fn default() -> Self {
30        ReadmeOptions {
31            add_title: true,
32            add_badges: true,
33            add_license: true,
34            indent_headings: true,
35            extract_from_comment: true,
36        }
37    }
38}
39
40/// Generates readme data from `source` file
41///
42/// Optionally, a template can be used to render the output
43pub fn generate_readme<T: Read>(
44    project_root: &Path,
45    source: &mut T,
46    template: Option<&mut T>,
47    options: ReadmeOptions,
48) -> Result<String, String> {
49    let lines = if options.extract_from_comment {
50        extract::extract_docs(source).map_err(|e| format!("{}", e))?
51    } else {
52        BufReader::new(source)
53            .lines()
54            .collect::<Result<Vec<_>, _>>()
55            .map_err(|e| format!("{}", e))?
56    };
57
58    let readme = process::process_docs(lines, options.indent_headings).join("\n");
59
60    // get template from file
61    let template = if let Some(template) = template {
62        Some(get_template_string(template)?)
63    } else {
64        None
65    };
66
67    // get manifest from Cargo.toml
68    let cargo = config::get_manifest(project_root)?;
69
70    template::render(template, readme, &cargo, options)
71}
72
73/// Load a template String from a file
74fn get_template_string<T: Read>(template: &mut T) -> Result<String, String> {
75    let mut template_string = String::new();
76    if let Err(e) = template.read_to_string(&mut template_string) {
77        return Err(format!("Error: {}", e));
78    }
79
80    Ok(template_string)
81}