rushls_common/config/
reference.rs1use std::fmt::Write as _;
10
11use conf::{Conf, introspection::ProgramOptionMeta};
12
13pub struct Reference<'a> {
15 pub preamble: &'a str,
18 pub toml_path: &'a dyn Fn(&str) -> Option<String>,
21 pub credential_file_flags: &'a [&'a str],
27 pub tables: &'a [(&'a str, &'a [TableKey<'a>])],
30}
31
32pub struct TableKey<'a> {
34 pub suffix: &'a str,
36 pub default: &'a str,
38 pub description: &'a str,
39}
40
41pub fn reference_markdown<T: Conf>(reference: &Reference<'_>) -> String {
45 let cell = |text: String| text.replace('|', "\\|");
46 let code =
47 |value: Option<String>| value.map_or_else(|| "—".to_owned(), |value| format!("`{value}`"));
48 let mut output = reference.preamble.to_owned();
49 let mut section = None;
50 for option in T::program_options() {
51 let Some(path) = (reference.toml_path)(&option.id().to_string()) else {
52 continue;
53 };
54 let table_keys = reference
55 .tables
56 .iter()
57 .find(|(table, _)| *table == path)
58 .map(|(_, keys)| *keys);
59 let top = match path.split_once('.') {
60 Some((top, _)) => top.to_owned(),
61 None if table_keys.is_some() => path.clone(),
63 None => "(top level)".to_owned(),
64 };
65 if section.as_ref() != Some(&top) {
66 write!(
67 output,
68 "\n## {}\n\n| Setting | Default | Environment | CLI | Description |\n|---|---|---|---|---|\n",
69 if top == "(top level)" {
70 top.clone()
71 } else {
72 format!("[{top}]")
73 }
74 )
75 .expect("writing to a String cannot fail");
76 section = Some(top);
77 }
78 let description = option
79 .description()
80 .map(ToString::to_string)
81 .unwrap_or_default();
82 let summary = description
83 .split("\n\n")
84 .next()
85 .unwrap_or_default()
86 .split_whitespace()
87 .collect::<Vec<_>>()
88 .join(" ");
89 let flag = option
90 .long_form()
91 .map(|value| format!("--{value}"))
92 .or_else(|| {
93 let sibling = format!("{path}_file");
94 reference
95 .credential_file_flags
96 .contains(&sibling.as_str())
97 .then(|| format!("--{} <PATH>", path.replace(['.', '_'], "-")))
98 });
99 writeln!(
100 output,
101 "| `{path}` | {} | {} | {} | {} |",
102 cell(code(option.default_help_str().map(ToString::to_string))),
103 cell(code(option.env_form().map(ToString::to_string))),
104 cell(code(flag)),
105 cell(summary),
106 )
107 .expect("writing to a String cannot fail");
108 for key in table_keys.unwrap_or_default() {
109 writeln!(
110 output,
111 "| `{path}{}` | {} | — | — | {} |",
112 key.suffix,
113 cell(if key.default.is_empty() {
114 "—".to_owned()
115 } else {
116 format!("`{}`", key.default)
117 }),
118 cell(key.description.to_owned()),
119 )
120 .expect("writing to a String cannot fail");
121 }
122 }
123 output
124}