rust_meth_lib/ui/args.rs
1use std::fmt::Write;
2
3/// Configuration options for specifying execution behavior, queries, and presentation modes.
4///
5/// `Opts` acts as the primary configuration object driving the analyzer and UI routing layers.
6#[allow(clippy::struct_excessive_bools)]
7pub struct Opts {
8 /// The name of the binary or application executable (used primarily for help headers).
9 pub bin: String,
10
11 /// The fully qualified or exact string representation of the type path to analyze
12 /// (e.g., `std::collections::HashMap`).
13 pub type_name: String,
14
15 /// An optional text pattern used to match and filter down target method names.
16 pub filter: Option<String>,
17
18 /// When `true`, instructs the tool to drop into an interactive terminal-based
19 /// selection mode rather than outputting text sequentially.
20 pub interactive: bool,
21
22 /// When `true`, prints inline documentation summaries directly alongside matching methods
23 /// in the default terminal layout.
24 pub show_doc: bool,
25
26 /// An optional exact method name targeting "go-to-definition" mechanics.
27 /// If populated, it short-circuits standard filtering and visualization paths.
28 pub goto_def: Option<String>,
29
30 /// When `true` alongside `goto_def`, attempts to launch the host system's native
31 /// editor to display the source code line definition.
32 pub open_def: bool,
33
34 /// When `true` alongside `goto_def`, builds a local documentation URL and triggers
35 /// the system's default web browser to view it.
36 pub open_doc: bool,
37
38 /// Optional paths or metadata defining external dependencies where `rust-analyzer`
39 /// should crawl looking for structural definitions.
40 pub deps: Option<String>,
41
42 /// When `true`, extracts and prints raw signature implementations or sample usage snippets.
43 pub snippet: bool,
44
45 /// When `true`, formats the matched results into a pretty-printed JSON payload
46 /// and prints it to standard output.
47 pub json: bool,
48}
49
50/// The result of parsing command-line arguments.
51///
52/// Expresses either a successfully built application context or an intentional early exit request
53/// such as information printouts.
54pub enum ParseResult {
55 /// Standard execution branch carrying a fully initialized configuration payload.
56 Opts(Opts),
57
58 /// Represents an explicit request for utility instructions. Contains the formatted
59 /// string payload destined for standard error output before exiting the process.
60 Help(String),
61
62 /// Represents an explicit request for application generation identifiers. Contains
63 /// the version string destined for standard output before exiting the process.
64 Version(String),
65}
66/// Builds the CLI help text.
67#[must_use]
68pub fn usage(bin: &str) -> String {
69 let mut s = String::new();
70 let _ = writeln!(
71 s,
72 "Usage: {bin} <type> [filter] [-i] [--doc] [--gd <method>] [--open] [--open-doc]\n"
73 );
74 s.push_str("\nExamples:\n");
75 let _ = writeln!(s, " {bin} u8\n");
76 let _ = writeln!(s, " {bin} String\n");
77 let _ = writeln!(s, " {bin} \"Vec<i32>\"\n");
78 let _ = writeln!(s, " {bin} \"HashMap<String,u32>\"\n");
79 let _ = writeln!(s, " {bin} u8 wrapping # fuzzy filter\n");
80 let _ = writeln!(
81 s,
82 " {bin} u8 -i # interactive picker\n"
83 );
84 let _ = writeln!(
85 s,
86 " {bin} u8 --doc # show doc comments inline\n"
87 );
88 let _ = writeln!(s, " {bin} u8 checked --doc # filter + docs\n");
89 let _ = writeln!(
90 s,
91 " {bin} String --gd len # print definition location\n"
92 );
93 let _ = writeln!(
94 s,
95 " {bin} u8 --gd checked_add # go to definition\n"
96 );
97 let _ = writeln!(s, " {bin} u8 --gd checked_add --open # open in $EDITOR\n");
98 let _ = writeln!(
99 s,
100 " {bin} u8 --gd checked_add --open-doc # open in browser\n"
101 );
102 s.push_str("\n3rd party crates:\n");
103 let _ = writeln!(
104 s,
105 " {bin} 'serde_json::Value' --deps 'serde_json = \"1.0\"'\n"
106 );
107 let _ = writeln!(
108 s,
109 " {bin} 'tokio::net::TcpStream' --deps 'tokio = {{ version = \"1.0\", features = [\"net\"] }}'\n"
110 );
111 s
112}
113
114/// Parses the environment command-line arguments into a structured [`ParseResult`].
115///
116/// This function manually iterates over [`std::env::args`], resolving the executable's
117/// binary name dynamically. It enforces positional priorities (e.g., `<type_name>` must precede
118/// optional `<filter>`) and validates incompatible flag pairings.
119///
120/// # Layout Rules & Semantics
121///
122/// * **Early Returns:** Global meta-flags like `-h`/`--help` or `-V`/`--version` instantly
123/// intercept evaluation and return a pre-baked variant.
124/// * **Muting Overrides:** If `--interactive` is enabled, any trailing text filter argument
125/// is explicitly dropped (`filter = None`).
126///
127/// # Errors
128///
129/// Returns an `Err(String)` containing utility descriptions if:
130/// * An unexpected flag or a third/subsequent unflagged positional argument is supplied.
131/// * Sub-commands demanding parameter arguments (like `--gd` or `--deps`) run out of argument tokens.
132/// * Mutually exclusive or poorly anchored flag arrangements are passed (e.g., using `--open` or
133/// `--open-doc` without also specifying a targeting `--gd` method, or invoking both simultaneously).
134pub fn parse_args() -> Result<ParseResult, String> {
135 let bin = std::env::current_exe()
136 .ok()
137 .and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
138 .unwrap_or_else(|| "rust-meth".to_string());
139
140 let mut args = std::env::args().skip(1);
141
142 let Some(first) = args.next() else {
143 return Ok(ParseResult::Help(usage(&bin)));
144 };
145
146 if matches!(first.as_str(), "--help" | "-h") {
147 return Ok(ParseResult::Help(usage(&bin)));
148 }
149
150 if matches!(first.as_str(), "--version" | "-V") {
151 return Ok(ParseResult::Version(format!(
152 "{bin} {}",
153 env!("CARGO_PKG_VERSION")
154 )));
155 }
156
157 if first.starts_with('-') {
158 return Err(format!("unexpected argument '{first}'\n\n{}", usage(&bin)));
159 }
160
161 let type_name = first;
162 let mut filter = None;
163 let mut interactive = false;
164 let mut show_doc = false;
165 let mut goto_def = None;
166 let mut open_def = false;
167 let mut open_doc = false;
168 let mut deps = None;
169 let mut snippet = false;
170 let mut json = false;
171
172 while let Some(arg) = args.next() {
173 match arg.as_str() {
174 "-i" | "--interactive" => interactive = true,
175 "-d" | "--doc" => show_doc = true,
176 "--gd" => {
177 let method = args
178 .next()
179 .ok_or_else(|| "--gd requires a method name".to_string())?;
180 goto_def = Some(method);
181 }
182 "--open" | "-o" => open_def = true,
183 "--open-doc" => open_doc = true,
184 "--deps" => {
185 let dep_str = args.next().ok_or_else(|| {
186 "--deps requires a dependency string (e.g., 'serde_json = \"1.0\"')".to_string()
187 })?;
188 deps = Some(dep_str);
189 }
190 "--snippet" => snippet = true,
191 "--json" => json = true,
192 _ if arg.starts_with('-') => {
193 return Err(format!("unexpected flag '{arg}'"));
194 }
195 _ => {
196 if filter.is_none() {
197 filter = Some(arg);
198 } else {
199 return Err(format!("unexpected argument '{arg}'"));
200 }
201 }
202 }
203 }
204
205 if interactive {
206 filter = None;
207 }
208
209 if open_def && goto_def.is_none() {
210 return Err("--open requires --gd <method>".to_string());
211 }
212
213 if open_doc && goto_def.is_none() {
214 return Err("--open-doc requires --gd <method>".to_string());
215 }
216
217 if open_def && open_doc {
218 return Err("choose only one of --open or --open-doc".to_string());
219 }
220
221 Ok(ParseResult::Opts(Opts {
222 bin,
223 type_name,
224 filter,
225 interactive,
226 show_doc,
227 goto_def,
228 open_def,
229 open_doc,
230 deps,
231 snippet,
232 json,
233 }))
234}