puerto 0.32.0

Puerto: la CLI de un framework full-stack DDD en Rust. Genera proyectos con Clean Architecture, la inyección de dependencias cableada sola y soporte de SQLx, sin cablear nada a mano. Antes, puerto-framework.
//! The generator forms, read from the CLI's own definition (`Cli::command()`): every argument of a
//! command is an input, with the text its `--help` gives it. A form only builds arguments; the TUI
//! runs the CLI itself with them, so no generator is duplicated, and neither is its documentation.
use crate::puerto_toml::PuertoConfig;
use clap::{Arg, Command, CommandFactory};

#[derive(Debug, Clone, PartialEq)]
pub enum Kind {
    /// `<NOMBRE>`: in order, before the options.
    Positional,
    /// `--flag <VALUE>`
    Option,
    /// `--flag`, ticked or not.
    Switch,
    /// The fields after `--`, as on the command line.
    Fields,
    /// Anything else, as on the command line (quotes allowed): a repeated option.
    Extra,
}

/// What `←`/`→` cycles through in a text input.
#[derive(Debug, Clone, PartialEq)]
pub enum Suggestions {
    None,
    /// The entities of `puerto.toml`.
    Entities,
    /// The values the option accepts (`--ide zed|vscode`).
    Values(Vec<String>),
}

#[derive(Debug, Clone)]
pub struct Input {
    /// As `--help` shows it: `<NOMBRE>`, `--publico`, `-- <CAMPOS>...`.
    pub label: String,
    pub kind: Kind,
    /// What it does: the long help of the argument.
    pub help: String,
    pub required: bool,
    pub suggestions: Suggestions,
}

#[derive(Debug, Clone)]
pub struct Generator {
    pub name: String,
    /// The command before the inputs: `["generar", "scaffold"]`.
    pub command: Vec<String>,
    pub about: String,
    pub inputs: Vec<Input>,
}

/// The `generar` commands that only make sense with a project feature.
fn makes_sense(name: &str, config: &PuertoConfig) -> bool {
    match name {
        "evento" | "consumidor" => config.project.has_events(),
        "migracion" => config.project.db,
        "web" | "web-bloque" => config.project.web,
        _ => true,
    }
}

/// The commands that make a new entity: their name starts empty, not on the selected one.
pub const CREATE_AN_ENTITY: [&str; 2] = ["scaffold", "dominio"];

/// Every `generar` command that makes sense in the project `config` describes, then `validar` and
/// `listar`.
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,
    })
}

/// A generator's form being filled in: one value per input (`ticked` in a switch), and the one
/// with the cursor.
#[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;
        }
    }

    /// The next of its suggestions (the previous one with `back`), wrapping.
    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();
    }

    /// The arguments of its command, or what is missing.
    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)
    }
}

/// `text` split into words as a shell would: on whitespace, with `'…'` and `"…"` keeping theirs.
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)
}

/// `args` as a command line to show: `puerto generar scaffold Producto -- nombre:String`.
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(" ")
}

/// One page of the manual: a command of `puerto`, as the path of its subcommands.
#[derive(Debug)]
pub struct Page {
    /// `puerto generar scaffold`
    pub command: String,
    path: Vec<String>,
}

impl Page {
    /// Its long help (what `--help` prints) in Spanish, wrapped by clap at `width` columns.
    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())
    }
}

/// Every command of `puerto`, `puerto` itself first.
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
}