puerto 0.31.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.
//! `puerto` alone, in a terminal inside a project (Fase 35): the contexts of `puerto.toml`, the
//! map of their references, a form per generator and the manual — those two read from the CLI's own
//! definition (`forms`). It only reads `puerto.toml`; a form runs the CLI itself as a child process,
//! so nothing a generator does, or says about itself, is written twice.
pub mod forms;
pub mod map;
pub mod view;

use crate::puerto_toml::PuertoConfig;
use forms::{Form, Generator};
use map::ProjectMap;
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use std::path::Path;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tab {
    Contexts,
    Relations,
    Generate,
    Manual,
}

/// What a key asks of the loop.
#[derive(Debug, PartialEq)]
pub enum Action {
    None,
    Quit,
    /// Run `puerto <args>` in the project, outside the TUI.
    Run(Vec<String>),
}

pub struct App {
    pub config: PuertoConfig,
    pub map: ProjectMap,
    pub tab: Tab,
    /// The selected entity, shared by the contexts and the relations.
    pub entity: usize,
    pub generators: Vec<Generator>,
    pub generator: usize,
    pub form: Option<Form>,
    pub manual: Vec<forms::Page>,
    pub page: usize,
    /// How far down the page the manual is.
    pub scroll: u16,
    /// The last command's result, or what a form is missing.
    pub status: String,
}

impl App {
    pub fn new(config: PuertoConfig) -> Self {
        Self {
            map: ProjectMap::new(&config),
            generators: forms::generators(&config),
            config,
            tab: Tab::Contexts,
            entity: 0,
            generator: 0,
            form: None,
            manual: forms::manual(),
            page: 0,
            scroll: 0,
            status: String::new(),
        }
    }

    pub fn entity_names(&self) -> Vec<String> {
        self.config.entity.iter().map(|e| e.name.clone()).collect()
    }

    pub fn handle(&mut self, key: KeyEvent) -> Action {
        if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {
            return Action::Quit;
        }
        if self.form.is_some() {
            return self.handle_form(key);
        }
        match key.code {
            KeyCode::Char('q') | KeyCode::Esc => return Action::Quit,
            KeyCode::Char('1') => self.tab = Tab::Contexts,
            KeyCode::Char('2') => self.tab = Tab::Relations,
            KeyCode::Char('3') => self.tab = Tab::Generate,
            KeyCode::Char('4') => self.tab = Tab::Manual,
            KeyCode::Tab => {
                self.tab = match self.tab {
                    Tab::Contexts => Tab::Relations,
                    Tab::Relations => Tab::Generate,
                    Tab::Generate => Tab::Manual,
                    Tab::Manual => Tab::Contexts,
                }
            }
            KeyCode::Up | KeyCode::Char('k') => self.step(false),
            KeyCode::Down | KeyCode::Char('j') => self.step(true),
            KeyCode::PageDown if self.tab == Tab::Manual => {
                self.scroll = self.scroll.saturating_add(10)
            }
            KeyCode::PageUp if self.tab == Tab::Manual => {
                self.scroll = self.scroll.saturating_sub(10)
            }
            KeyCode::Enter if self.tab == Tab::Generate => self.open_form(),
            _ => {}
        }
        Action::None
    }

    fn open_form(&mut self) {
        let Some(generator) = self.generators.get(self.generator) else {
            return;
        };
        let mut form = Form::new(generator.clone());
        // The entity selected in the contexts, unless the command makes a new one.
        let selected = self.config.entity.get(self.entity).map(|e| e.name.clone());
        if let (Some(name), false) = (
            selected,
            forms::CREATE_AN_ENTITY.contains(&generator.name.as_str()),
        ) {
            for (at, input) in generator.inputs.iter().enumerate() {
                if input.suggestions == forms::Suggestions::Entities {
                    form.set_text(at, &name);
                }
            }
        }
        self.form = Some(form);
        self.status.clear();
    }

    fn step(&mut self, down: bool) {
        let (selected, count) = match self.tab {
            Tab::Generate => (&mut self.generator, self.generators.len()),
            Tab::Manual => {
                self.scroll = 0;
                (&mut self.page, self.manual.len())
            }
            _ => (&mut self.entity, self.config.entity.len()),
        };
        if count > 0 {
            *selected = if down {
                (*selected + 1) % count
            } else {
                (*selected + count - 1) % count
            };
        }
    }

    fn handle_form(&mut self, key: KeyEvent) -> Action {
        let entities = self.entity_names();
        let Some(form) = self.form.as_mut() else {
            return Action::None;
        };
        let inputs = form.generator.inputs.len();
        let at = form.focus;
        let switch = form.kind(at) == Some(&forms::Kind::Switch);
        match key.code {
            KeyCode::Esc => self.form = None,
            KeyCode::Up if inputs > 0 => form.focus = (at + inputs - 1) % inputs,
            KeyCode::Down | KeyCode::Tab if inputs > 0 => form.focus = (at + 1) % inputs,
            KeyCode::Left => form.suggest(at, &entities, true),
            KeyCode::Right => form.suggest(at, &entities, false),
            KeyCode::Char(' ') if switch => form.toggle(at),
            KeyCode::Char(c) if !switch => form.values[at].push(c),
            KeyCode::Backspace if !switch => {
                form.values[at].pop();
            }
            KeyCode::Enter => match form.args() {
                Ok(args) => return Action::Run(args),
                Err(missing) => self.status = missing,
            },
            _ => {}
        }
        Action::None
    }

    /// After a command: `puerto.toml` again (it may have new entities), the selections kept in
    /// range and the form closed.
    fn reload(&mut self, base: &Path, status: String) {
        if let Ok(config) = crate::puerto_toml::read(base) {
            let (tab, entity, generator, page) = (self.tab, self.entity, self.generator, self.page);
            *self = Self::new(config);
            self.tab = tab;
            self.entity = entity.min(self.config.entity.len().saturating_sub(1));
            self.generator = generator.min(self.generators.len().saturating_sub(1));
            self.page = page;
        }
        self.form = None;
        self.status = status;
    }
}

pub fn run(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let mut app = App::new(crate::puerto_toml::read(base)?);
    let mut terminal = ratatui::init();
    let result = (|| -> Result<(), Box<dyn std::error::Error>> {
        loop {
            terminal.draw(|frame| view::render(frame, &app))?;
            let Event::Key(key) = event::read()? else {
                continue;
            };
            if key.kind != KeyEventKind::Press {
                continue;
            }
            match app.handle(key) {
                Action::None => {}
                Action::Quit => return Ok(()),
                Action::Run(args) => {
                    ratatui::restore();
                    let status = run_command(base, &args);
                    terminal = ratatui::init();
                    app.reload(base, status);
                }
            }
        }
    })();
    ratatui::restore();
    result
}

/// `puerto <args>` in `base` with the terminal to itself (its output and its questions, as
/// always), then back on Enter. The status line it leaves.
fn run_command(base: &Path, args: &[String]) -> String {
    let line = forms::command_line(args);
    println!("$ {line}\n");
    let status = std::env::current_exe().and_then(|exe| {
        std::process::Command::new(exe)
            .args(args)
            .current_dir(base)
            .status()
    });
    println!("\nIntro para volver a puerto");
    let _ = std::io::stdin().read_line(&mut String::new());
    match status {
        Ok(status) if status.success() => format!("✓ {line}"),
        Ok(status) => format!(
            "✗ {line} (salió con {})",
            status.code().map_or("una señal".into(), |c| c.to_string())
        ),
        Err(e) => format!("✗ no se pudo ejecutar puerto: {e}"),
    }
}