use crate::puerto_toml::PuertoConfig;
use clap::{Arg, Command, CommandFactory};
#[derive(Debug, Clone, PartialEq)]
pub enum Kind {
Positional,
Option,
Switch,
Fields,
Extra,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Suggestions {
None,
Entities,
Values(Vec<String>),
}
#[derive(Debug, Clone)]
pub struct Input {
pub label: String,
pub kind: Kind,
pub help: String,
pub required: bool,
pub suggestions: Suggestions,
}
#[derive(Debug, Clone)]
pub struct Generator {
pub name: String,
pub command: Vec<String>,
pub about: String,
pub inputs: Vec<Input>,
}
fn makes_sense(name: &str, config: &PuertoConfig) -> bool {
match name {
"evento" | "consumidor" => config.project.has_events(),
"notificaciones" | "notificacion" => {
config.project.has_auth() && config.project.has_events()
}
"ciclo-cuenta" => config.project.auth.as_deref() == Some("local"),
"migracion" | "tarea-programada" => config.project.db,
"web" | "web-bloque" => config.project.web,
_ => true,
}
}
pub const CREATE_AN_ENTITY: [&str; 2] = ["scaffold", "dominio"];
pub fn generators(config: &PuertoConfig) -> Vec<Generator> {
let cli = crate::Cli::command();
let generate = cli
.find_subcommand("generar")
.into_iter()
.flat_map(Command::get_subcommands)
.filter(|c| makes_sense(c.get_name(), config))
.map(|c| generator(&["generar", c.get_name()], c));
let top = ["validar", "listar"]
.into_iter()
.filter_map(|name| cli.find_subcommand(name).map(|c| generator(&[name], c)));
generate.chain(top).collect()
}
fn text(styled: Option<&clap::builder::StyledStr>) -> String {
styled.map(ToString::to_string).unwrap_or_default()
}
fn generator(command: &[&str], cmd: &Command) -> Generator {
let mut inputs: Vec<Input> = cmd
.get_arguments()
.filter(|arg| !matches!(arg.get_id().as_str(), "help" | "version"))
.filter_map(input)
.collect();
inputs.push(Input {
label: "Más opciones".into(),
kind: Kind::Extra,
help: "Lo que no cabe arriba, como en la línea de comandos (admite comillas): una opción \
que se repite, como un segundo --unico."
.into(),
required: false,
suggestions: Suggestions::None,
});
Generator {
name: cmd.get_name().to_string(),
command: command.iter().map(|s| s.to_string()).collect(),
about: text(cmd.get_long_about().or(cmd.get_about())),
inputs,
}
}
fn input(arg: &Arg) -> Option<Input> {
let value = arg
.get_value_names()
.and_then(|names| names.first())
.map_or_else(|| arg.get_id().as_str().to_uppercase(), |v| v.to_string());
let help = text(arg.get_long_help().or(arg.get_help()));
let (label, kind) = if arg.is_positional() {
if arg.is_last_set() {
(format!("-- <{value}>..."), Kind::Fields)
} else {
(format!("<{value}>"), Kind::Positional)
}
} else {
let long = format!("--{}", arg.get_long()?);
if arg.get_action().takes_values() {
(long, Kind::Option)
} else {
(long, Kind::Switch)
}
};
let values: Vec<String> = arg
.get_possible_values()
.iter()
.map(|v| v.get_name().to_string())
.collect();
let suggestions = if !values.is_empty() {
Suggestions::Values(values)
} else if kind == Kind::Positional
&& (value == "ENTIDAD" || help.starts_with("Nombre de la entidad"))
{
Suggestions::Entities
} else {
Suggestions::None
};
Some(Input {
label,
kind,
help,
required: arg.is_required_set(),
suggestions,
})
}
#[derive(Debug)]
pub struct Form {
pub generator: Generator,
pub values: Vec<String>,
pub ticked: Vec<bool>,
pub focus: usize,
}
impl Form {
pub fn new(generator: Generator) -> Self {
let count = generator.inputs.len();
Self {
generator,
values: vec![String::new(); count],
ticked: vec![false; count],
focus: 0,
}
}
pub fn kind(&self, at: usize) -> Option<&Kind> {
self.generator.inputs.get(at).map(|i| &i.kind)
}
pub fn set_text(&mut self, at: usize, text: &str) {
if let Some(value) = self.values.get_mut(at) {
*value = text.to_string();
}
}
pub fn toggle(&mut self, at: usize) {
if let Some(ticked) = self.ticked.get_mut(at) {
*ticked = !*ticked;
}
}
pub fn suggest(&mut self, at: usize, entities: &[String], back: bool) {
let options = match self.generator.inputs.get(at).map(|i| &i.suggestions) {
Some(Suggestions::Entities) => entities.to_vec(),
Some(Suggestions::Values(values)) => values.clone(),
_ => return,
};
let count = options.len();
if count == 0 {
return;
}
let next = match options.iter().position(|o| *o == self.values[at]) {
Some(i) if back => (i + count - 1) % count,
Some(i) => (i + 1) % count,
None if back => count - 1,
None => 0,
};
self.values[at] = options[next].clone();
}
pub fn args(&self) -> Result<Vec<String>, String> {
let mut args = self.generator.command.clone();
let (mut extra, mut fields) = (Vec::new(), Vec::new());
for (at, input) in self.generator.inputs.iter().enumerate() {
let value = self.values[at].trim();
if value.is_empty() && input.required && input.kind != Kind::Switch {
return Err(format!("falta {}", input.label));
}
match input.kind {
Kind::Positional if !value.is_empty() => args.push(value.to_string()),
Kind::Option if !value.is_empty() => {
args.push(input.label.clone());
args.push(value.to_string());
}
Kind::Switch if self.ticked[at] => args.push(input.label.clone()),
Kind::Fields => fields = value.split_whitespace().map(String::from).collect(),
Kind::Extra => extra = split_words(value)?,
_ => {}
}
}
args.extend(extra);
if !fields.is_empty() {
args.push("--".into());
args.extend(fields);
}
Ok(args)
}
}
pub fn split_words(text: &str) -> Result<Vec<String>, String> {
let mut words = Vec::new();
let mut word = String::new();
let mut in_word = false;
let mut quote = None;
for c in text.chars() {
match quote {
Some(q) if c == q => quote = None,
Some(_) => word.push(c),
None if c == '\'' || c == '"' => {
quote = Some(c);
in_word = true;
}
None if c.is_whitespace() => {
if in_word {
words.push(std::mem::take(&mut word));
in_word = false;
}
}
None => {
word.push(c);
in_word = true;
}
}
}
if quote.is_some() {
return Err("unas comillas sin cerrar en las opciones".into());
}
if in_word {
words.push(word);
}
Ok(words)
}
pub fn command_line(args: &[String]) -> String {
let quoted = args.iter().map(|arg| {
if arg.is_empty() || arg.contains(char::is_whitespace) {
format!("'{arg}'")
} else {
arg.clone()
}
});
std::iter::once("puerto".to_string())
.chain(quoted)
.collect::<Vec<_>>()
.join(" ")
}
#[derive(Debug)]
pub struct Page {
pub command: String,
path: Vec<String>,
}
impl Page {
pub fn help(&self, width: usize) -> String {
let mut cmd = crate::Cli::command().term_width(width);
cmd.build();
let mut page = &mut cmd;
for name in &self.path {
match page.find_subcommand_mut(name) {
Some(sub) => page = sub,
None => return String::new(),
}
}
crate::clap_en_castellano(&page.render_long_help().to_string())
}
}
pub fn manual() -> Vec<Page> {
fn walk(cmd: &Command, path: Vec<String>, pages: &mut Vec<Page>) {
let command = std::iter::once("puerto")
.chain(path.iter().map(String::as_str))
.collect::<Vec<_>>()
.join(" ");
for sub in cmd.get_subcommands().filter(|c| c.get_name() != "help") {
let mut deeper = path.clone();
deeper.push(sub.get_name().to_string());
pages.push(Page {
command: format!("{command} {}", sub.get_name()),
path: deeper.clone(),
});
walk(sub, deeper, pages);
}
}
let mut pages = vec![Page {
command: "puerto".into(),
path: Vec::new(),
}];
walk(&crate::Cli::command(), Vec::new(), &mut pages);
pages
}