Files
cotizador/internal/cli/cli.go
T

1132 lines
28 KiB
Go

package cli
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
)
const Version = "1.0.0"
// Exit codes matching cli/cotizador.mjs.
const (
ExitOK = 0
ExitError = 1
ExitUso = 2
ExitAuth = 3
ExitNoEncontrado = 4
ExitValidacion = 5
ExitConflicto = 6
ExitRed = 7
)
var descripcionCodigos = map[string]string{
"0": "ok",
"1": "error del servidor o inesperado",
"2": "uso incorrecto (flag faltante o invalida, comando desconocido)",
"3": "sin sesion o sin permiso (ejecuta `cotizador login`)",
"4": "no encontrado",
"5": "validacion rechazada por el servidor (ver `detalles`)",
"6": "conflicto (duplicado)",
"7": "no se pudo conectar con el servidor",
}
// ---------------------------------------------------------------------------
// Dominio (espejo de src/lib/calculators.ts y cli/cotizador.mjs)
// ---------------------------------------------------------------------------
var (
nivelesServicio = []string{"Emprendedor", "PYME", "Empresario", "Corporativo"}
estadosCotizacion = []string{"borrador", "enviada", "aprobada", "rechazada"}
esquemasPago = []string{"Pago Unico", "Mensual", "Pago Unico/Mensual", "Por hora (postpago)"}
monedasValidas = []string{"MXN", "USD"}
planesBucefaloCRM = []string{"basico", "estandar", "premium", "empresarial"}
tarifaHoraDefault = 700.0
ivaRate = 0.16
)
func dominioInfo() map[string]any {
return map[string]any{
"fases": map[string]string{
"0": "Auditoria / Acompanamiento",
"1": "Setup e Infraestructura",
"2": "Publicidad y Manejo",
"3": "Contenido y SEO",
},
"tiposPago": map[string]string{
"unico": "pago unico",
"mensual": "pago recurrente mensual",
},
"nivelesServicio": nivelesServicio,
"estadosCotizacion": estadosCotizacion,
"esquemasPago": esquemasPago,
"monedas": monedasValidas,
"planesBucefaloCRM": planesBucefaloCRM,
"iva": ivaRate,
"tarifaHoraDefault": tarifaHoraDefault,
}
}
// ---------------------------------------------------------------------------
// Errors & dry-run signal
// ---------------------------------------------------------------------------
type cliError struct {
Mensaje string
Codigo int
Status int
Detalles any
Sugerencia string
}
func (e *cliError) Error() string { return e.Mensaje }
func errorUso(mensaje string, sugerencia ...string) *cliError {
sug := ""
if len(sugerencia) > 0 {
sug = sugerencia[0]
}
return &cliError{
Mensaje: mensaje,
Codigo: ExitUso,
Sugerencia: sug,
}
}
type dryRunSignal struct {
Metodo string `json:"metodo"`
URL string `json:"url"`
Cuerpo any `json:"cuerpo"`
}
func (d *dryRunSignal) Error() string { return "dry-run" }
// ---------------------------------------------------------------------------
// Flag specifications & argument parsing
// ---------------------------------------------------------------------------
type flagSpec struct {
Flag string
Tipo string // texto | entero | numero | booleano | lista | fecha | json
Valores []any
Repetible bool
Descripcion string
}
type argSpec struct {
Nombre string `json:"nombre"`
Descripcion string `json:"descripcion"`
}
type cmdContext struct {
Pos []string
Flags *parsedFlags
Cliente *apiClient
Stdin io.Reader
Stdout io.Writer
}
type commandSpec struct {
Comando string
Alias []string
Descripcion string
Argumentos []argSpec
Flags []flagSpec
Ejemplos []string
Endpoint string
HasEndpoint bool
SinServidor bool
Run func(ctx *cmdContext) (any, bool, error)
}
var flagsGlobales = []flagSpec{
{Flag: "url", Tipo: "texto", Descripcion: "URL base de la plataforma (default: $COTIZADOR_URL o http://localhost:3000)"},
{Flag: "campos", Tipo: "lista", Descripcion: "Devuelve solo estos campos, separados por coma (ej. id,nombre,precioBase). Ahorra tokens."},
{Flag: "formato", Tipo: "texto", Valores: []any{"json", "tabla"}, Descripcion: "json (default) o tabla legible"},
{Flag: "compacto", Tipo: "booleano", Descripcion: "JSON en una sola linea"},
{Flag: "dry-run", Tipo: "booleano", Descripcion: "En comandos de escritura: muestra la peticion que se enviaria y no la envia"},
{Flag: "ayuda", Tipo: "booleano", Descripcion: "Ayuda del comando (tambien -h, --help)"},
{Flag: "version", Tipo: "booleano", Descripcion: "Version del CLI"},
}
type parsedFlags struct {
present map[string]bool
values map[string]string
bools map[string]bool
lists map[string][]string
}
func newParsedFlags() *parsedFlags {
return &parsedFlags{
present: make(map[string]bool),
values: make(map[string]string),
bools: make(map[string]bool),
lists: make(map[string][]string),
}
}
func (f *parsedFlags) Has(key string) bool { return f.present[key] }
func (f *parsedFlags) Str(key string) string { return f.values[key] }
func (f *parsedFlags) Bool(key string) bool { return f.bools[key] }
func (f *parsedFlags) List(key string) []string { return f.lists[key] }
func aCamel(s string) string {
var b strings.Builder
upperNext := false
for _, r := range s {
if r == '-' {
upperNext = true
continue
}
if upperNext && r >= 'a' && r <= 'z' {
b.WriteRune(unicode.ToUpper(r))
upperNext = false
continue
}
if upperNext {
b.WriteRune('-')
upperNext = false
}
b.WriteRune(r)
}
if upperNext {
b.WriteRune('-')
}
return b.String()
}
func aKebab(s string) string {
var b strings.Builder
for _, r := range s {
if unicode.IsUpper(r) {
b.WriteRune('-')
b.WriteRune(unicode.ToLower(r))
} else {
b.WriteRune(r)
}
}
return b.String()
}
func parsearArgs(argv []string, especFlags []flagSpec) ([]string, *parsedFlags, error) {
booleanas := make(map[string]bool)
repetibles := make(map[string]bool)
conocidas := make(map[string]bool)
for _, f := range especFlags {
conocidas[f.Flag] = true
if f.Tipo == "booleano" {
booleanas[f.Flag] = true
}
if f.Repetible {
repetibles[f.Flag] = true
}
}
var posicionales []string
flags := newParsedFlags()
for i := 0; i < len(argv); i++ {
a := argv[i]
if a == "--" {
posicionales = append(posicionales, argv[i+1:]...)
break
}
if a == "-h" {
flags.present["ayuda"] = true
flags.bools["ayuda"] = true
continue
}
if !strings.HasPrefix(a, "--") {
posicionales = append(posicionales, a)
continue
}
nombre := a[2:]
var valor string
hasValor := false
if eq := strings.IndexByte(nombre, '='); eq >= 0 {
valor = nombre[eq+1:]
nombre = nombre[:eq]
hasValor = true
}
if nombre == "help" {
nombre = "ayuda"
}
if strings.HasPrefix(nombre, "no-") && booleanas[nombre[3:]] {
clave := aCamel(nombre[3:])
flags.present[clave] = true
flags.bools[clave] = false
continue
}
if booleanas[nombre] {
clave := aCamel(nombre)
flags.present[clave] = true
if !hasValor {
flags.bools[clave] = true
} else {
low := strings.ToLower(valor)
flags.bools[clave] = low != "false" && low != "0" && low != "no"
}
continue
}
// Unknown flag without value: record it so per-command validation reports unknown flag clearly
if !conocidas[nombre] && !hasValor {
clave := aCamel(nombre)
flags.present[clave] = true
if i+1 < len(argv) && !strings.HasPrefix(argv[i+1], "--") {
flags.values[clave] = argv[i+1]
i++
}
continue
}
if !hasValor {
if i+1 >= len(argv) || (strings.HasPrefix(argv[i+1], "--") && argv[i+1] != "--") {
return nil, nil, errorUso(fmt.Sprintf("La flag --%s necesita un valor", nombre))
}
valor = argv[i+1]
i++
}
clave := aCamel(nombre)
flags.present[clave] = true
if repetibles[nombre] {
flags.lists[clave] = append(flags.lists[clave], valor)
} else {
flags.values[clave] = valor
}
}
return posicionales, flags, nil
}
// ---------------------------------------------------------------------------
// Value conversion helpers
// ---------------------------------------------------------------------------
var (
fechaISORe = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`)
colorHexRe = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
cleanNumRe = regexp.MustCompile(`[$,\s]`)
servicioRefRe = regexp.MustCompile(`^(.*?)\s*=\s*([\d.,$\s]+)$`)
filenameRe = regexp.MustCompile(`(?i)filename\*?=(?:UTF-8'')?"?([^";]+)"?`)
cookieSessRe = regexp.MustCompile(`cotizador-session=([^;]+)`)
)
func parseNumero(valor, flag string) (float64, error) {
limpio := cleanNumRe.ReplaceAllString(valor, "")
if limpio == "" {
return 0, errorUso(fmt.Sprintf(`--%s debe ser un numero (recibi "%s")`, flag, valor))
}
n, err := strconv.ParseFloat(limpio, 64)
if err != nil || math.IsNaN(n) || math.IsInf(n, 0) {
return 0, errorUso(fmt.Sprintf(`--%s debe ser un numero (recibi "%s")`, flag, valor))
}
return n, nil
}
func parseEntero(valor, flag string) (int, error) {
n, err := parseNumero(valor, flag)
if err != nil {
return 0, err
}
if math.Trunc(n) != n {
return 0, errorUso(fmt.Sprintf(`--%s debe ser un entero (recibi "%s")`, flag, valor))
}
return int(n), nil
}
func unoDe(valor string, opciones []string, flag string) (string, error) {
for _, op := range opciones {
if op == valor {
return valor, nil
}
}
return "", errorUso(fmt.Sprintf(`--%s debe ser uno de: %s (recibi "%s")`, flag, strings.Join(opciones, ", "), valor))
}
func textoOpcional(valor string) (string, bool) {
low := strings.ToLower(valor)
if low == "" || low == "null" || low == "ninguno" || low == "ninguna" {
return "", true
}
return valor, false
}
func validarFechaISO(valor, flag string) (string, error) {
if !fechaISORe.MatchString(valor) {
return "", errorUso(fmt.Sprintf(`--%s debe tener formato YYYY-MM-DD (recibi "%s")`, flag, valor))
}
return valor, nil
}
func leerStdin(r io.Reader) (string, error) {
if r == nil {
return "", nil
}
b, err := io.ReadAll(r)
if err != nil {
return "", err
}
return string(b), nil
}
func leerDatos(valor string, hasValor bool, stdin io.Reader) (map[string]any, error) {
if !hasValor {
return map[string]any{}, nil
}
texto := valor
if valor == "-" {
var err error
texto, err = leerStdin(stdin)
if err != nil {
return nil, errorUso("No pude leer stdin")
}
} else if strings.HasPrefix(valor, "@") {
p := valor[1:]
b, err := os.ReadFile(p)
if err != nil {
return nil, errorUso(fmt.Sprintf("No pude leer el archivo %s", p))
}
texto = string(b)
}
var raw any
if err := json.Unmarshal([]byte(texto), &raw); err != nil {
return nil, errorUso("--datos debe ser un objeto JSON valido (en linea, @archivo.json o - para stdin)")
}
obj, ok := raw.(map[string]any)
if !ok || obj == nil {
return nil, errorUso("--datos debe ser un objeto JSON valido (en linea, @archivo.json o - para stdin)")
}
return obj, nil
}
// ---------------------------------------------------------------------------
// Sessions & HTTP client
// ---------------------------------------------------------------------------
type sessionEntry struct {
Token string `json:"token"`
Usuario any `json:"usuario"`
Iniciada string `json:"iniciada"`
}
func sessionPaths() (dir string, file string, legacyFile string) {
home, _ := os.UserHomeDir()
envHome := os.Getenv("COTIZADOR_HOME")
if envHome != "" {
dir = envHome
} else {
dir = filepath.Join(home, ".cotizador-uj")
}
file = filepath.Join(dir, "sesiones.json")
if envHome == "" && home != "" {
legacyFile = filepath.Join(home, ".cotizador-e3", "sesiones.json")
}
return dir, file, legacyFile
}
func leerSesiones() map[string]sessionEntry {
_, file, legacy := sessionPaths()
if b, err := os.ReadFile(file); err == nil {
var s map[string]sessionEntry
if json.Unmarshal(b, &s) == nil && s != nil {
return s
}
}
if legacy != "" {
if b, err := os.ReadFile(legacy); err == nil {
var s map[string]sessionEntry
if json.Unmarshal(b, &s) == nil && s != nil {
return s
}
}
}
return map[string]sessionEntry{}
}
func guardarSesiones(sesiones map[string]sessionEntry) error {
dir, file, _ := sessionPaths()
if err := os.MkdirAll(dir, 0o700); err != nil {
return err
}
b, err := json.MarshalIndent(sesiones, "", " ")
if err != nil {
return err
}
return os.WriteFile(file, b, 0o600)
}
func resolverURLBase(flags *parsedFlags) (string, error) {
raw := flags.Str("url")
if raw == "" {
raw = os.Getenv("COTIZADOR_URL")
}
if raw == "" {
raw = "http://localhost:3000"
}
raw = strings.TrimRight(raw, "/")
u, err := url.Parse(raw)
if err != nil || u.Scheme == "" || u.Host == "" {
return "", errorUso(fmt.Sprintf("URL invalida: %s", raw))
}
return raw, nil
}
func codigoPorStatus(status int) int {
switch status {
case 400, 422:
return ExitValidacion
case 401, 403:
return ExitAuth
case 404:
return ExitNoEncontrado
case 409:
return ExitConflicto
default:
return ExitError
}
}
func extraerToken(res *http.Response) string {
for _, c := range res.Cookies() {
if c.Name == "cotizador-session" && c.Value != "" {
return c.Value
}
}
for _, raw := range res.Header.Values("Set-Cookie") {
if m := cookieSessRe.FindStringSubmatch(raw); len(m) == 2 && m[1] != "" {
return m[1]
}
}
return ""
}
type apiClient struct {
base string
dryRun bool
tokenEnMemoria string
httpClient *http.Client
}
func crearCliente(flags *parsedFlags) (*apiClient, error) {
base, err := resolverURLBase(flags)
if err != nil {
return nil, err
}
return &apiClient{
base: base,
dryRun: flags.Bool("dryRun"),
tokenEnMemoria: os.Getenv("COTIZADOR_TOKEN"),
httpClient: &http.Client{
Timeout: 60 * time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
},
}, nil
}
func (c *apiClient) token() string {
if c.tokenEnMemoria != "" {
return c.tokenEnMemoria
}
sesiones := leerSesiones()
if s, ok := sesiones[c.base]; ok && s.Token != "" {
c.tokenEnMemoria = s.Token
return s.Token
}
return ""
}
func (c *apiClient) errorRed(err error) *cliError {
return &cliError{
Mensaje: fmt.Sprintf("No se pudo conectar con %s: %v", c.base, err),
Codigo: ExitRed,
Sugerencia: "Revisa que el servidor este arriba o pasa la URL correcta con --url o COTIZADOR_URL",
}
}
func (c *apiClient) login(email, password string) (any, error) {
payload, _ := json.Marshal(map[string]string{
"email": email,
"password": password,
})
req, err := http.NewRequest(http.MethodPost, c.base+"/api/auth/login", bytes.NewReader(payload))
if err != nil {
return nil, c.errorRed(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
res, err := c.httpClient.Do(req)
if err != nil {
return nil, c.errorRed(err)
}
defer res.Body.Close()
bodyBytes, _ := io.ReadAll(res.Body)
var cuerpo map[string]any
_ = json.Unmarshal(bodyBytes, &cuerpo)
if res.StatusCode < 200 || res.StatusCode >= 300 {
msg := fmt.Sprintf("Login fallido (HTTP %d)", res.StatusCode)
if s, ok := cuerpo["error"].(string); ok && s != "" {
msg = s
}
return nil, &cliError{Mensaje: msg, Codigo: ExitAuth, Status: res.StatusCode}
}
nuevo := extraerToken(res)
if nuevo == "" {
return nil, &cliError{Mensaje: "El servidor no devolvio la cookie de sesion", Codigo: ExitAuth}
}
if u, ok := cuerpo["user"].(map[string]any); ok {
if role, _ := u["role"].(string); role == "cliente" {
return nil, &cliError{
Mensaje: "Esa cuenta es de rol cliente; el CLI necesita una cuenta de staff (admin o asesor)",
Codigo: ExitAuth,
}
}
}
sesiones := leerSesiones()
sesiones[c.base] = sessionEntry{
Token: nuevo,
Usuario: cuerpo["user"],
Iniciada: time.Now().UTC().Format(time.RFC3339),
}
if err := guardarSesiones(sesiones); err != nil {
return nil, &cliError{Mensaje: fmt.Sprintf("No pude guardar la sesion: %v", err), Codigo: ExitError}
}
c.tokenEnMemoria = nuevo
return cuerpo["user"], nil
}
func (c *apiClient) cerrarSesion() (bool, error) {
sesiones := leerSesiones()
_, habia := sesiones[c.base]
delete(sesiones, c.base)
if err := guardarSesiones(sesiones); err != nil {
return false, err
}
c.tokenEnMemoria = ""
return habia, nil
}
type apiOpts struct {
Cuerpo any
HasCuerpo bool
Binario bool
Escritura *bool
}
type binaryResponse struct {
Buffer []byte
NombreArchivo string
Tipo string
}
func (c *apiClient) api(metodo, ruta string, opts ...apiOpts) (any, error) {
var opt apiOpts
if len(opts) > 0 {
opt = opts[0]
}
fullURL := c.base + ruta
esEscritura := metodo != http.MethodGet
if opt.Escritura != nil {
esEscritura = *opt.Escritura
}
if c.dryRun && esEscritura {
var cuerpo any
if opt.HasCuerpo {
cuerpo = opt.Cuerpo
}
return nil, &dryRunSignal{
Metodo: metodo,
URL: fullURL,
Cuerpo: cuerpo,
}
}
reintentado := false
for {
var bodyReader io.Reader
if opt.HasCuerpo {
b, err := json.Marshal(opt.Cuerpo)
if err != nil {
return nil, &cliError{Mensaje: fmt.Sprintf("Error serializando cuerpo JSON: %v", err), Codigo: ExitError}
}
bodyReader = bytes.NewReader(b)
}
req, err := http.NewRequest(metodo, fullURL, bodyReader)
if err != nil {
return nil, c.errorRed(err)
}
if opt.Binario {
req.Header.Set("Accept", "*/*")
} else {
req.Header.Set("Accept", "application/json")
}
if opt.HasCuerpo {
req.Header.Set("Content-Type", "application/json")
}
if t := c.token(); t != "" {
req.Header.Set("Cookie", "cotizador-session="+t)
}
res, err := c.httpClient.Do(req)
if err != nil {
return nil, c.errorRed(err)
}
bodyBytes, readErr := io.ReadAll(res.Body)
res.Body.Close()
if readErr != nil {
return nil, c.errorRed(readErr)
}
// Auto-reauth on 401 when COTIZADOR_EMAIL and COTIZADOR_PASSWORD are set.
if res.StatusCode == http.StatusUnauthorized && !reintentado &&
os.Getenv("COTIZADOR_EMAIL") != "" && os.Getenv("COTIZADOR_PASSWORD") != "" {
reintentado = true
c.tokenEnMemoria = ""
if _, err := c.login(os.Getenv("COTIZADOR_EMAIL"), os.Getenv("COTIZADOR_PASSWORD")); err != nil {
return nil, err
}
continue
}
if res.StatusCode >= 300 && res.StatusCode < 400 {
return nil, &cliError{
Mensaje: fmt.Sprintf("El servidor redirigio a %s (¿sesion invalida?)", res.Header.Get("Location")),
Codigo: ExitAuth,
Status: res.StatusCode,
Sugerencia: "Ejecuta: cotizador login --email <correo> --password <contrasena>",
}
}
if res.StatusCode < 200 || res.StatusCode >= 300 {
var errBody map[string]any
_ = json.Unmarshal(bodyBytes, &errBody)
msg := fmt.Sprintf("HTTP %d", res.StatusCode)
if s, ok := errBody["error"].(string); ok && s != "" {
msg = s
}
var sug string
if res.StatusCode == http.StatusUnauthorized {
sug = "Ejecuta: cotizador login --email <correo> --password <contrasena> (o define COTIZADOR_EMAIL y COTIZADOR_PASSWORD)"
} else if res.StatusCode == http.StatusForbidden {
sug = "La cuenta no tiene permiso para esta accion (el CLI necesita rol admin o asesor)"
}
return nil, &cliError{
Mensaje: msg,
Codigo: codigoPorStatus(res.StatusCode),
Status: res.StatusCode,
Detalles: errBody["detalles"],
Sugerencia: sug,
}
}
if opt.Binario {
disp := res.Header.Get("Content-Disposition")
nombre := ""
if m := filenameRe.FindStringSubmatch(disp); len(m) == 2 {
if decoded, err := url.PathUnescape(m[1]); err == nil {
nombre = decoded
} else {
nombre = m[1]
}
}
return &binaryResponse{
Buffer: bodyBytes,
NombreArchivo: nombre,
Tipo: res.Header.Get("Content-Type"),
}, nil
}
trimmed := bytes.TrimSpace(bodyBytes)
if len(trimmed) == 0 {
return nil, nil
}
var out any
if err := json.Unmarshal(trimmed, &out); err != nil {
return nil, &cliError{Mensaje: fmt.Sprintf("Respuesta JSON invalida del servidor: %v", err), Codigo: ExitError}
}
return out, nil
}
}
// ---------------------------------------------------------------------------
// Output formatting (--campos, --formato tabla, --compacto)
// ---------------------------------------------------------------------------
func normalizeAny(v any) any {
b, err := json.Marshal(v)
if err != nil {
return v
}
var out any
if err := json.Unmarshal(b, &out); err != nil {
return v
}
return out
}
func getDotPath(obj map[string]any, path string) (any, bool) {
parts := strings.Split(path, ".")
var cur any = obj
for _, k := range parts {
m, ok := cur.(map[string]any)
if !ok || m == nil {
return nil, false
}
val, exists := m[k]
if !exists {
return nil, false
}
cur = val
}
return cur, true
}
func elegirCampos(datos any, campos string) (any, []string) {
if strings.TrimSpace(campos) == "" {
return datos, nil
}
var lista []string
for _, c := range strings.Split(campos, ",") {
c = strings.TrimSpace(c)
if c != "" {
lista = append(lista, c)
}
}
if len(lista) == 0 {
return datos, nil
}
norm := normalizeAny(datos)
pick := func(v any) any {
m, ok := v.(map[string]any)
if !ok || m == nil {
return v
}
res := make(map[string]any, len(lista))
for _, c := range lista {
if val, exists := getDotPath(m, c); exists {
res[c] = val
}
}
return res
}
if arr, ok := norm.([]any); ok {
out := make([]any, len(arr))
for i, item := range arr {
out[i] = pick(item)
}
return out, lista
}
return pick(norm), lista
}
func celdaTabla(v any) string {
if v == nil {
return ""
}
var s string
switch x := v.(type) {
case []any:
parts := make([]string, len(x))
for i, item := range x {
parts[i] = fmt.Sprint(item)
}
s = strings.Join(parts, "; ")
case float64:
if math.Trunc(x) == x {
s = strconv.FormatInt(int64(x), 10)
} else {
s = strconv.FormatFloat(x, 'f', -1, 64)
}
default:
s = fmt.Sprint(x)
}
runes := []rune(s)
if len(runes) > 60 {
return string(runes[:57]) + "..."
}
return s
}
func aTabla(datos any, orderedCols []string) string {
norm := normalizeAny(datos)
var filas []map[string]any
switch x := norm.(type) {
case []any:
if len(x) == 0 {
return "(sin resultados)"
}
for _, item := range x {
if m, ok := item.(map[string]any); ok {
filas = append(filas, m)
} else {
filas = append(filas, map[string]any{"valor": item})
}
}
case map[string]any:
filas = []map[string]any{x}
default:
if norm == nil {
return "(sin resultados)"
}
filas = []map[string]any{{"valor": norm}}
}
var colCandidates []string
if len(orderedCols) > 0 {
colCandidates = orderedCols
} else {
seen := make(map[string]bool)
for _, f := range filas {
for k := range f {
if !seen[k] {
seen[k] = true
colCandidates = append(colCandidates, k)
}
}
}
sort.Strings(colCandidates)
}
var columnas []string
for _, c := range colCandidates {
ok := true
for _, f := range filas {
if v, exists := f[c]; exists && v != nil {
if _, isMap := v.(map[string]any); isMap {
ok = false
break
}
}
}
if ok {
columnas = append(columnas, c)
}
}
anchos := make([]int, len(columnas))
for i, c := range columnas {
anchos[i] = len([]rune(c))
for _, f := range filas {
l := len([]rune(celdaTabla(f[c])))
if l > anchos[i] {
anchos[i] = l
}
}
}
padRight := func(s string, width int) string {
r := len([]rune(s))
if r >= width {
return s
}
return s + strings.Repeat(" ", width-r)
}
linea := func(vals []string) string {
padded := make([]string, len(vals))
for i, v := range vals {
padded[i] = padRight(v, anchos[i])
}
return strings.Join(padded, " ")
}
var lines []string
lines = append(lines, linea(columnas))
dashes := make([]string, len(anchos))
for i, a := range anchos {
dashes[i] = strings.Repeat("-", a)
}
lines = append(lines, linea(dashes))
for _, f := range filas {
vals := make([]string, len(columnas))
for i, c := range columnas {
vals[i] = celdaTabla(f[c])
}
lines = append(lines, linea(vals))
}
return strings.Join(lines, "\n")
}
func imprimir(w io.Writer, datos any, flags *parsedFlags) {
filtrado, orderedCols := elegirCampos(datos, flags.Str("campos"))
if flags.Str("formato") == "tabla" {
_, _ = fmt.Fprintln(w, aTabla(filtrado, orderedCols))
return
}
var b []byte
if flags.Bool("compacto") {
b, _ = json.Marshal(filtrado)
} else {
b, _ = json.MarshalIndent(filtrado, "", " ")
}
_, _ = fmt.Fprintln(w, string(b))
}
func imprimirError(w io.Writer, err *cliError) {
salida := map[string]any{
"ok": false,
"error": err.Mensaje,
"codigo": err.Codigo,
}
if err.Status != 0 {
salida["status"] = err.Status
}
if err.Detalles != nil {
salida["detalles"] = err.Detalles
}
if err.Sugerencia != "" {
salida["sugerencia"] = err.Sugerencia
}
b, _ := json.MarshalIndent(salida, "", " ")
_, _ = fmt.Fprintln(w, string(b))
}
// ---------------------------------------------------------------------------
// Entry points
// ---------------------------------------------------------------------------
// Run executes the cotizador CLI with the given arguments and returns its exit code.
func Run(args []string) int {
return runWithIO(args, os.Stdin, os.Stdout, os.Stderr)
}
func runWithIO(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
err := execute(args, stdin, stdout)
if err == nil {
return ExitOK
}
var dr *dryRunSignal
if errors.As(err, &dr) {
b, _ := json.MarshalIndent(map[string]any{
"dryRun": true,
"metodo": dr.Metodo,
"url": dr.URL,
"cuerpo": dr.Cuerpo,
}, "", " ")
_, _ = fmt.Fprintln(stdout, string(b))
return ExitOK
}
var ce *cliError
if errors.As(err, &ce) {
imprimirError(stderr, ce)
return ce.Codigo
}
imprimirError(stderr, &cliError{Mensaje: err.Error(), Codigo: ExitError})
return ExitError
}
func execute(args []string, stdin io.Reader, stdout io.Writer) error {
cmds := allCommands()
todasLasFlags := make([]flagSpec, 0, len(flagsGlobales)+64)
todasLasFlags = append(todasLasFlags, flagsGlobales...)
for _, c := range cmds {
todasLasFlags = append(todasLasFlags, c.Flags...)
}
posicionales, flags, err := parsearArgs(args, todasLasFlags)
if err != nil {
return err
}
if flags.Bool("version") {
imprimir(stdout, map[string]any{"version": Version}, flags)
return nil
}
if len(posicionales) == 0 {
_, _ = io.WriteString(stdout, ayudaGeneral(cmds))
return nil
}
cmd, consumidas := buscarComando(cmds, posicionales)
if cmd == nil {
return fallarComando(cmds, posicionales)
}
pos := posicionales[consumidas:]
if flags.Bool("ayuda") {
_, _ = io.WriteString(stdout, ayudaComando(cmd))
return nil
}
if flags.Has("formato") {
f := flags.Str("formato")
if f != "json" && f != "tabla" {
return errorUso("--formato debe ser json o tabla")
}
}
// Reject unknown flags for this command instead of silently ignoring them.
validas := make(map[string]bool, len(flagsGlobales)+len(cmd.Flags))
for _, f := range flagsGlobales {
validas[aCamel(f.Flag)] = true
}
for _, f := range cmd.Flags {
validas[aCamel(f.Flag)] = true
}
var desconocidas []string
for k := range flags.present {
if !validas[k] {
desconocidas = append(desconocidas, "--"+aKebab(k))
}
}
if len(desconocidas) > 0 {
sort.Strings(desconocidas)
validFlagsList := make([]string, len(cmd.Flags))
for i, f := range cmd.Flags {
validFlagsList[i] = "--" + f.Flag
}
validStr := strings.Join(validFlagsList, ", ")
if validStr == "" {
validStr = "(ninguna)"
}
return errorUso(
fmt.Sprintf(`Flag no valida para "%s": %s`, cmd.Comando, strings.Join(desconocidas, ", ")),
fmt.Sprintf("Flags validas: %s. Ver: cotizador ayuda %s", validStr, cmd.Comando),
)
}
var cliente *apiClient
if !cmd.SinServidor {
cliente, err = crearCliente(flags)
if err != nil {
return err
}
}
res, hasOutput, err := cmd.Run(&cmdContext{
Pos: pos,
Flags: flags,
Cliente: cliente,
Stdin: stdin,
Stdout: stdout,
})
if err != nil {
return err
}
if hasOutput {
imprimir(stdout, res, flags)
}
return nil
}