cargo_readme/readme/
mod.rs1use std::io::{BufRead, BufReader, Read};
2use std::path::Path;
3
4mod extract;
5mod process;
6mod template;
7
8use crate::config;
9
10#[derive(Debug, Clone, Copy)]
15pub struct ReadmeOptions {
16 pub add_title: bool,
18 pub add_badges: bool,
20 pub add_license: bool,
22 pub indent_headings: bool,
24 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
40pub 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 let template = if let Some(template) = template {
62 Some(get_template_string(template)?)
63 } else {
64 None
65 };
66
67 let cargo = config::get_manifest(project_root)?;
69
70 template::render(template, readme, &cargo, options)
71}
72
73fn 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}