Skip to main content

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(version: &str) -> 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!("{bin} {version}")));
152    }
153    // if matches!(first.as_str(), "--version" | "-V") {
154    //     return Ok(ParseResult::Version(format!(
155    //         "{bin} {}",
156    //         env!("CARGO_PKG_VERSION")
157    //     )));
158    // }
159
160    if first.starts_with('-') {
161        return Err(format!("unexpected argument '{first}'\n\n{}", usage(&bin)));
162    }
163
164    let type_name = first;
165    let mut filter = None;
166    let mut interactive = false;
167    let mut show_doc = false;
168    let mut goto_def = None;
169    let mut open_def = false;
170    let mut open_doc = false;
171    let mut deps = None;
172    let mut snippet = false;
173    let mut json = false;
174
175    while let Some(arg) = args.next() {
176        match arg.as_str() {
177            "-i" | "--interactive" => interactive = true,
178            "-d" | "--doc" => show_doc = true,
179            "--gd" => {
180                let method = args
181                    .next()
182                    .ok_or_else(|| "--gd requires a method name".to_string())?;
183                goto_def = Some(method);
184            }
185            "--open" | "-o" => open_def = true,
186            "--open-doc" => open_doc = true,
187            "--deps" => {
188                let dep_str = args.next().ok_or_else(|| {
189                    "--deps requires a dependency string (e.g., 'serde_json = \"1.0\"')".to_string()
190                })?;
191                deps = Some(dep_str);
192            }
193            "--snippet" => snippet = true,
194            "--json" => json = true,
195            _ if arg.starts_with('-') => {
196                return Err(format!("unexpected flag '{arg}'"));
197            }
198            _ => {
199                if filter.is_none() {
200                    filter = Some(arg);
201                } else {
202                    return Err(format!("unexpected argument '{arg}'"));
203                }
204            }
205        }
206    }
207
208    if interactive {
209        filter = None;
210    }
211
212    if open_def && goto_def.is_none() {
213        return Err("--open requires --gd <method>".to_string());
214    }
215
216    if open_doc && goto_def.is_none() {
217        return Err("--open-doc requires --gd <method>".to_string());
218    }
219
220    if open_def && open_doc {
221        return Err("choose only one of --open or --open-doc".to_string());
222    }
223
224    Ok(ParseResult::Opts(Opts {
225        bin,
226        type_name,
227        filter,
228        interactive,
229        show_doc,
230        goto_def,
231        open_def,
232        open_doc,
233        deps,
234        snippet,
235        json,
236    }))
237}