Skip to content

Commit

Permalink
refactor: export json (#231)
Browse files Browse the repository at this point in the history
  • Loading branch information
sigoden authored Aug 16, 2023
1 parent 7a02939 commit 8e4efe4
Show file tree
Hide file tree
Showing 6 changed files with 156 additions and 135 deletions.
37 changes: 16 additions & 21 deletions src/command/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,9 @@ use crate::parser::{parse, Event, EventData, EventScope, Position};
use crate::utils::INTERNAL_MODE;
use crate::Result;

use anyhow::{bail, Context};
use anyhow::bail;
use std::cell::RefCell;
use std::collections::HashMap;
use std::result::Result as StdResult;
use std::sync::Arc;

pub fn eval(
Expand All @@ -29,7 +28,7 @@ pub fn eval(

pub fn export(source: &str) -> Result<serde_json::Value> {
let cmd = Command::new(source)?;
cmd.to_json().with_context(|| "Failed to export json")
Ok(cmd.to_json())
}

#[derive(Debug, Default)]
Expand Down Expand Up @@ -87,30 +86,26 @@ impl Command {
Ok(matcher.to_arg_values())
}

pub fn to_json(&self) -> StdResult<serde_json::Value, serde_json::Error> {
let subcommands: StdResult<Vec<serde_json::Value>, _> =
pub fn to_json(&self) -> serde_json::Value {
let subcommands: Vec<serde_json::Value> =
self.subcommands.iter().map(|v| v.to_json()).collect();
let flag_option_params: StdResult<Vec<serde_json::Value>, _> = self
let flag_option_params: Vec<serde_json::Value> = self
.flag_option_params
.iter()
.map(serde_json::to_value)
.map(|v| v.to_json())
.collect();
let positional_params: StdResult<Vec<serde_json::Value>, _> = self
.positional_params
.iter()
.map(serde_json::to_value)
.collect();
let value = serde_json::json!({
let positional_params: Vec<serde_json::Value> =
self.positional_params.iter().map(|v| v.to_json()).collect();
serde_json::json!({
"describe": self.describe,
"name": self.name,
"author": self.author,
"version": self.version,
"options": flag_option_params?,
"positionals": positional_params?,
"options": flag_option_params,
"positionals": positional_params,
"aliases": self.aliases,
"subcommands": subcommands?,
});
Ok(value)
"subcommands": subcommands,
})
}

pub(crate) fn new_from_events(events: &[Event]) -> Result<Self> {
Expand Down Expand Up @@ -451,7 +446,7 @@ impl Command {
pub(crate) fn find_flag_option(&self, name: &str) -> Option<&FlagOptionParam> {
self.flag_option_params
.iter()
.find(|v| v.name == name || v.is_match(name))
.find(|v| v.name() == name || v.is_match(name))
}

pub(crate) fn find_prefixed_option(&self, name: &str) -> Option<(&FlagOptionParam, String)> {
Expand All @@ -467,14 +462,14 @@ impl Command {

pub(crate) fn match_version_short_name(&self) -> bool {
match self.find_flag_option("-V") {
Some(param) => &param.name == "version",
Some(param) => param.name() == "version",
None => true,
}
}

pub(crate) fn match_help_short_name(&self) -> bool {
match self.find_flag_option("-h") {
Some(param) => &param.name == "help",
Some(param) => param.name() == "help",
None => true,
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/command/names_checker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ impl NamesChecker {
param: &PositionalParam,
pos: Position,
) -> Result<()> {
let name = &param.name;
let name = param.name();
if let Some(exist_pos) = self.positionals.get(name) {
bail!(
"{}",
Expand Down
38 changes: 19 additions & 19 deletions src/matcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,14 +113,10 @@ impl<'a, 'b> Matcher<'a, 'b> {
if let Some(param) = cmd.find_flag_option(k) {
add_param_choice_fn(&mut choice_fns, param);
if arg_index == args_len - 1 {
arg_comp = ArgComp::OptionValue(param.name.clone(), 0);
arg_comp = ArgComp::OptionValue(param.name().to_string(), 0);
split_last_arg_at = Some(k.len() + 1);
}
flag_option_args[cmd_level].push((
k,
vec![v],
Some(param.name.as_str()),
));
flag_option_args[cmd_level].push((k, vec![v], Some(param.name())));
} else if let Some((param, prefix)) = cmd.find_prefixed_option(arg) {
add_param_choice_fn(&mut choice_fns, param);
match_prefix_option(
Expand Down Expand Up @@ -343,7 +339,11 @@ impl<'a, 'b> Matcher<'a, 'b> {
comp_subcommands_positional(last_cmd, &values, self.positional_args.len() < 2)
}
ArgComp::OptionValue(name, index) => {
if let Some(param) = last_cmd.flag_option_params.iter().find(|v| &v.name == name) {
if let Some(param) = last_cmd
.flag_option_params
.iter()
.find(|v| v.name() == name)
{
comp_flag_option(param, *index)
} else {
vec![]
Expand Down Expand Up @@ -387,7 +387,7 @@ impl<'a, 'b> Matcher<'a, 'b> {
let values: Vec<&[&str]> = args
.iter()
.filter_map(|(_, value, name)| {
if let Some(true) = name.map(|v| param.name == v) {
if let Some(true) = name.map(|v| param.name() == v) {
Some(value.as_slice())
} else {
None
Expand Down Expand Up @@ -518,7 +518,7 @@ impl<'a, 'b> Matcher<'a, 'b> {
.flag_option_params
.iter()
.filter(|v| v.required())
.map(|v| v.name.as_str())
.map(|v| v.name())
.collect();
for (i, (key, _, name)) in args.iter().enumerate() {
match *name {
Expand All @@ -537,7 +537,7 @@ impl<'a, 'b> Matcher<'a, 'b> {
missing_params.extend(missing_flag_options)
}
for (name, indexes) in flag_option_map {
if let Some(param) = cmd.flag_option_params.iter().find(|v| v.name == name) {
if let Some(param) = cmd.flag_option_params.iter().find(|v| v.name() == name) {
let values_list: Vec<&[&str]> =
indexes.iter().map(|v| args[*v].1.as_slice()).collect();
if !param.multiple() && values_list.len() > 1 {
Expand Down Expand Up @@ -793,7 +793,7 @@ impl<'a, 'b> Matcher<'a, 'b> {
.collect();
let last = self.args.last().map(|v| v.as_str()).unwrap_or_default();
for param in cmd.flag_option_params.iter() {
let mut exist = args.contains(param.name.as_str());
let mut exist = args.contains(param.name());
if !last.is_empty() && param.is_match(last) {
exist = false;
}
Expand Down Expand Up @@ -879,7 +879,7 @@ fn match_combine_shorts<'a, 'b>(
}
}
if let Some(param) = current_cmd.find_flag_option(&name) {
output.push((arg, vec![], Some(param.name.as_str())))
output.push((arg, vec![], Some(param.name())))
} else {
return None;
}
Expand All @@ -902,9 +902,9 @@ fn match_flag_option<'a, 'b>(
*arg_index += value_args.len();
if !value_args.is_empty() {
*arg_comp =
ArgComp::OptionValue(param.name.clone(), value_args.len().saturating_sub(1));
ArgComp::OptionValue(param.name().to_string(), value_args.len().saturating_sub(1));
}
flag_option_args.push((arg, value_args, Some(param.name.as_str())));
flag_option_args.push((arg, value_args, Some(param.name())));
} else {
let values_len = param.values_size();
let args_len = args.len();
Expand All @@ -915,20 +915,20 @@ fn match_flag_option<'a, 'b>(
if *arg_comp != ArgComp::FlagOrOption {
if param.is_option() && value_args.len() <= values_len {
*arg_comp = ArgComp::OptionValue(
param.name.clone(),
param.name().to_string(),
value_args.len().saturating_sub(1),
);
}
} else if let Some(prefix) = param.prefixed() {
if arg.starts_with(&prefix) {
*arg_comp = ArgComp::OptionValue(param.name.clone(), 0);
*arg_comp = ArgComp::OptionValue(param.name().to_string(), 0);
*split_last_arg_at = Some(prefix.len());
}
} else if param.is_flag() && !(arg.len() > 2 && param.is_match(arg)) {
*arg_comp = ArgComp::FlagOrOptionCombine(arg.to_string());
}
}
flag_option_args.push((arg, value_args, Some(param.name.as_str())));
flag_option_args.push((arg, value_args, Some(param.name())));
}
}

Expand All @@ -945,10 +945,10 @@ fn match_prefix_option<'a, 'b>(
let args_len = args.len();
let arg = &args[*arg_index];
if *arg_index == args_len - 1 {
*arg_comp = ArgComp::OptionValue(param.name.clone(), 0);
*arg_comp = ArgComp::OptionValue(param.name().to_string(), 0);
*split_last_arg_at = Some(prefix_len);
}
flag_option_args.push((arg, vec![&arg[prefix_len..]], Some(param.name.as_str())));
flag_option_args.push((arg, vec![&arg[prefix_len..]], Some(param.name())));
}

fn match_command<'a, 'b>(
Expand Down
Loading

0 comments on commit 8e4efe4

Please sign in to comment.