-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcmd_generate.rs
208 lines (172 loc) · 6.38 KB
/
cmd_generate.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
use std::{fs, io::Write};
use anyhow::{Context, Result};
use clap::{Command, CommandFactory, Parser};
/// Generate various documentation files for the `zoo` command line.
#[derive(Parser, Debug, Clone)]
#[clap(verbatim_doc_comment)]
pub struct CmdGenerate {
#[clap(subcommand)]
subcmd: SubCommand,
}
#[derive(Parser, Debug, Clone)]
enum SubCommand {
Markdown(CmdGenerateMarkdown),
}
#[async_trait::async_trait(?Send)]
impl crate::cmd::Command for CmdGenerate {
async fn run(&self, ctx: &mut crate::context::Context) -> Result<()> {
match &self.subcmd {
SubCommand::Markdown(cmd) => cmd.run(ctx).await,
}
}
}
/// Generate markdown documentation.
#[derive(Parser, Debug, Clone)]
#[clap(verbatim_doc_comment)]
pub struct CmdGenerateMarkdown {
/// Path directory where you want to output the generated files.
#[clap(short = 'D', long, default_value = "")]
pub dir: String,
}
#[async_trait::async_trait(?Send)]
impl crate::cmd::Command for CmdGenerateMarkdown {
async fn run(&self, ctx: &mut crate::context::Context) -> Result<()> {
let mut app: Command = crate::Opts::command();
app.build();
// Make sure the output directory exists.
if !self.dir.is_empty() {
fs::create_dir_all(&self.dir).with_context(|| format!("failed to create directory {}", self.dir))?;
}
self.generate(ctx, &app, "")?;
Ok(())
}
}
impl CmdGenerateMarkdown {
fn generate(&self, ctx: &mut crate::context::Context, app: &Command, parent: &str) -> Result<()> {
let name = app.get_name();
if name == "help" {
// Skip the help command.
return Ok(());
}
let mut p = parent.to_string();
if !p.is_empty() {
p = format!("{}_{}", p, name);
} else {
p = name.to_string();
}
let filename = format!("{p}.md");
let title = p.replace('_', " ");
writeln!(ctx.io.out, "Generating markdown for `{title}` -> {filename}")?;
// Generate the markdown.
let m = crate::docs_markdown::app_to_markdown(app, &title)?;
// Add our header information.
let markdown = format!(
r#"---
title: "{}"
excerpt: "{}"
layout: manual
---
{}"#,
title,
app.get_about().unwrap_or_default(),
m
);
if self.dir.is_empty() {
// TODO: glamorize markdown to the shell.
writeln!(ctx.io.out, "{markdown}")?;
} else {
let p = std::path::Path::new(&self.dir).join(filename);
let mut file = std::fs::File::create(p)?;
file.write_all(markdown.as_bytes())?;
}
// Iterate over all the subcommands and generate the documentation.
for subcmd in app.get_subcommands() {
self.generate(ctx, subcmd, &p)?;
}
Ok(())
}
}
#[cfg(test)]
fn test_app() -> clap::Command {
// Define our app.
clap::Command::new("git")
.about("A fictional versioning CLI")
.subcommand_required(true)
.allow_external_subcommands(true)
.subcommand(
Command::new("clone")
.about("Clones repos")
.arg(clap::arg!(<REMOTE> "The remote to clone"))
.arg_required_else_help(true),
)
.subcommand(
clap::Command::new("push")
.about("pushes things")
.arg(clap::arg!(<REMOTE> "The remote to target"))
.arg_required_else_help(true),
)
.subcommand(
clap::Command::new("add")
.about("adds things")
.arg_required_else_help(true)
.arg(clap::arg!(<PATH> ... "Stuff to add"))
.subcommand(
clap::Command::new("new")
.about("subcommand for adding new stuff")
.long_about("See url: <https://example.com> and <https://example.com/thing|thing>.")
// Add an enum arg.
.arg(
clap::Arg::new("type")
.help("The type of thing to add.")
.long("type")
.value_parser(["file", "dir"])
.default_value("file")
.required(true),
)
.subcommand(clap::Command::new("foo").about("sub subcommand")),
),
)
}
#[cfg(test)]
mod test {
use pretty_assertions::assert_eq;
use crate::cmd::Command;
#[tokio::test(flavor = "multi_thread")]
async fn test_generate_markdown() {
let mut config = crate::config::new_blank_config().unwrap();
let mut c = crate::config_from_env::EnvConfig::inherit_env(&mut config);
let (io, stdout_path, stderr_path) = crate::iostreams::IoStreams::test();
let mut ctx = crate::context::Context {
config: &mut c,
io,
debug: false,
};
let cmd = crate::cmd_generate::CmdGenerateMarkdown { dir: "".to_string() };
cmd.run(&mut ctx).await.unwrap();
let stdout = std::fs::read_to_string(stdout_path).unwrap();
let stderr = std::fs::read_to_string(stderr_path).unwrap();
assert!(stdout.contains("<dt><code>-H/--host</code></dt>"), "");
assert!(stdout.contains("### About"), "");
assert_eq!(stderr, "");
// Ensure we don't generate the help command.
assert!(!stdout.contains("help.md"));
}
#[test]
fn test_generate_markdown_sub_subcommands() {
let mut config = crate::config::new_blank_config().unwrap();
let mut c = crate::config_from_env::EnvConfig::inherit_env(&mut config);
let (io, stdout_path, stderr_path) = crate::iostreams::IoStreams::test();
let mut ctx = crate::context::Context {
config: &mut c,
io,
debug: false,
};
let cmd = crate::cmd_generate::CmdGenerateMarkdown { dir: "".to_string() };
let app = crate::cmd_generate::test_app();
cmd.generate(&mut ctx, &app, "").unwrap();
let stdout = std::fs::read_to_string(stdout_path).unwrap();
let stderr = std::fs::read_to_string(stderr_path).unwrap();
expectorate::assert_contents("tests/markdown_sub_commands.txt", &stdout);
assert_eq!(stderr, "");
}
}