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
use crate::error::*;
use crate::Parameter;
use yansi::Paint;
#[derive(Debug)]
pub struct HelpEntry {
pub command: String,
pub parameters: Vec<(String, bool)>,
pub summary: Option<String>,
}
impl HelpEntry {
pub(crate) fn new(
command_name: &str,
parameters: &[Parameter],
summary: &Option<String>,
) -> Self {
Self {
command: command_name.to_string(),
parameters: parameters
.iter()
.map(|pd| (pd.name.clone(), pd.required))
.collect(),
summary: summary.clone(),
}
}
}
pub struct HelpContext {
pub app_name: String,
pub app_version: String,
pub app_purpose: String,
pub help_entries: Vec<HelpEntry>,
}
impl HelpContext {
pub(crate) fn new(
app_name: &str,
app_version: &str,
app_purpose: &str,
help_entries: Vec<HelpEntry>,
) -> Self {
Self {
app_name: app_name.into(),
app_version: app_version.into(),
app_purpose: app_purpose.into(),
help_entries,
}
}
}
pub trait HelpViewer {
fn help_general(&self, context: &HelpContext) -> Result<()>;
fn help_command(&self, entry: &HelpEntry) -> Result<()>;
}
pub struct DefaultHelpViewer;
impl DefaultHelpViewer {
pub fn new() -> Self {
Self
}
}
impl HelpViewer for DefaultHelpViewer {
fn help_general(&self, context: &HelpContext) -> Result<()> {
self.print_help_header(context);
for entry in &context.help_entries {
print!("{}", entry.command);
if entry.summary.is_some() {
print!(" - {}", entry.summary.clone().unwrap());
}
println!();
}
Ok(())
}
fn help_command(&self, entry: &HelpEntry) -> Result<()> {
if entry.summary.is_some() {
println!("{}: {}", entry.command, entry.summary.clone().unwrap());
} else {
println!("{}:", entry.command);
}
println!("Usage:");
print!("\t{}", entry.command);
for param in entry.parameters.clone() {
if param.1 {
print!(" {}", param.0);
} else {
print!(" [{}]", param.0);
}
}
Ok(())
}
}
impl DefaultHelpViewer {
fn print_help_header(&self, context: &HelpContext) {
let header = format!(
"{} {}: {}",
context.app_name, context.app_version, context.app_purpose
);
let underline = Paint::new(
std::iter::repeat(" ")
.take(header.len())
.collect::<String>(),
)
.strikethrough();
println!("{}", header);
println!("{}", underline);
}
}