Skip to content

fix: stabilization batch 3 — ~60 generator bugs across all commands#59

Merged
sazardev merged 1 commit into
masterfrom
fix/stabilization-batch-3
Jun 14, 2026
Merged

fix: stabilization batch 3 — ~60 generator bugs across all commands#59
sazardev merged 1 commit into
masterfrom
fix/stabilization-batch-3

Conversation

@sazardev

Copy link
Copy Markdown
Owner

Resumen

Pase de estabilización masivo (batch 3). Se auditaron los 24 comandos generando proyectos reales con cada flag y compilando el código generado (go build/go vet), contrastando además contra la documentación del wiki de cada comando. Este PR corrige ~60 bugs detectados de golpe: compile-breakers, no-ops que mentían sobre el éxito, salida incoherente, flags muertos, placeholders/hardcoded y desviaciones de la documentación.

Verificación end-to-end: goca init + 2 features + entity con campos complejos ahora produce un proyecto que compila limpio (go build ./...), con el contenedor DI cableado en cmd/server/main.go, ambos grupos de rutas servidos (/api/v1/...) y ambas entidades registradas en la auto-migración. goca analyze ya no da falsos positivos, config validate detecta configs inválidas, mocks satisfacen las interfaces reales y di --wire genera código procesable por wire.

43 archivos · +2790/−828 · solo cmd/ e internal/testing/.


Bugs corregidos por comando

entity / mocks

  • Nombres snake_case/multi-palabra → PascalCase Go (UserID, LastLogin) manteniendo tags json/gorm en snake_case (antes User_id).
  • Tipos custom de campo generan un stub de tipo en vez de identificadores indefinidos (antes no compilaba).
  • Validación numérica coherente para todos los subtipos int/uint/float; sin constantes ErrInvalid…Range sin usar; sin tag required/checks muertos en slices/punteros.
  • Seeds SQL emiten valores reales para slice/puntero/custom (antes NULL).
  • Los mocks ahora implementan las interfaces reales: nombres/firmas correctos y finders por campo; el test de ejemplo usa la API real + aserciones de interfaz en tiempo de compilación.

usecase

  • goca usecase standalone compila: genera la interface de repository de la que depende y elimina la interface contradictoria en el paquete usecase.
  • --async emite wrappers async reales y compilables (antes tipos indefinidos).
  • Método update genérico usa los campos reales del DTO (antes campos en español inexistentes).
  • --dto-validation ahora llama a input.Validate().
  • Error si la entidad objetivo no existe. Salida solo en inglés.

repository

  • Repo Elasticsearch importa esapi; repo Mongo implementa CRUD completo (antes solo Save).
  • --cache postgres genera los helpers de caché que invoca (go-redis/v9).
  • El cache decorator solo emite finders existentes; soporta --transactions.
  • --database enruta sqlite/sqlserver/postgres-json/elasticsearch/dynamodb a sus generadores reales en el camino field-aware (antes: todo → Postgres).

di / integrate

  • goca integrate emite Go válido para cmd/server/main.go (antes no parseaba: := sin variable, llaves/else mal cerrados), apunta a cmd/server/main.go, y solo integra features con todas las capas (ignora entidades de dominio huérfanas).
  • goca di --wire produce código procesable por wire (provider de *gorm.DB, tipos de retorno consistentes); --cache/--database mongodb solo emiten constructores existentes.

feature (auto-integración estrella — antes era un no-op que imprimía éxito)

  • La auto-migración inserta de verdad &domain.Entity{} en cmd/server/main.go.
  • Las rutas + el contenedor DI se cablean realmente en main.go (idempotente).
  • Múltiples features coexisten: routes.go y el contenedor DI se extienden para la 2ª+ feature en vez de saltarse.

handler / middleware

  • handler + paquete middleware compila junto (mux.MiddlewareFunc).
  • Tipo contextKey compartido movido al middleware.go base (request-id etc. compilan).
  • Servidor gRPC usa el output plano del usecase y los campos reales de la entidad.
  • go mod tidy es best-effort (ya no corrompe go.mod al fallar).
  • --swagger emite las anotaciones @Summary/@Router/@Success documentadas.
  • Nombres de paquete middleware en minúscula permitidos; se valida existencia de entidad; mensajes de éxito veraces (sin falso éxito con directorio vacío).

init

  • Valida valores de --database/--api; persiste --api/--auth en .goca.yaml.
  • docker-compose consciente de la DB (image/port/env/healthcheck/volume), README y defaults de config para postgres/mysql/mongodb/sqlite/sqlserver/dynamodb/es; healthcheck de mongo usa mongosh.
  • Rechaza directorio destino no vacío sin --force; arregla bloques de código markdown; elimina el replace solo-de-test; git init ya no se cuelga por gpg/stdin.

analyze / doctor / config / safety

  • analyze ya no da falsos positivos en el propio layout de goca (encuentra cmd/server/main.go y os.Getenv en pkg/config); --output json emite JSON válido; --fail-on-warn sale con código 2; detecta secretos hardcoded con :=.
  • config validate usa el validador semántico real (antes un stub que aprobaba configs inválidas); config init valida --template/--database.
  • Check de DI de doctor ya no da falso negativo; dry-run nunca falla por archivos existentes.

template / ui / version / test-integration

  • template list lista plantillas; template show/reset implementados.
  • --quiet suprime salida de archivos/tablas; version sigue imprimiendo bajo --quiet; version lee info VCS de los metadatos de build.
  • test-integration: protege contra entidades inexistentes, setup MySQL real (sin t.Skip permanente), setup testcontainers real para --container.

Notas

  • Metodología: la auditoría se ejecutó probando el binario público goca v1.25.7 (idéntico al HEAD del repo), generando proyectos en distintas configuraciones y compilando/ejecutando el resultado, no solo leyendo el código.
  • Infra (fuera de alcance, recomendado para otro PR): el hook pre-commit de lefthook corre go test ./..., que incluye tests E2E en internal/testing/tests que invocan goca initgit add/commit sin aislar el cwd, commiteando contra el .git del repo. Conviene aislar cmd.Dir en initializeGitRepository/los tests o marcarlos como no-paralelos.
  • Quedan diferidos (no compile-breakers): documentación del wiki muy desfasada de la salida real (frameworks, nombres de tipos, firmas), y wiring del motor de plantillas custom en los generadores entity/usecase (sigue siendo código muerto salvo los subcomandos template).

Massive stabilization pass. Every command was audited by generating real
projects with every flag and **compiling the generated code**; this commit
fixes the bugs that broke compilation, lied about success, produced
incoherent output, or contradicted the documentation.

Verified end-to-end: `goca init` + 2 features + tricky-field entity now
produce a project that `go build ./...` compiles cleanly, with the DI
container wired into cmd/server/main.go, both feature route groups served,
and both entities registered for auto-migration.

## entity / mocks
- Convert snake_case/multi-word field names to Go PascalCase (UserID,
  LastLogin) while keeping snake_case json/gorm tags (was: User_id).
- Generate stub types for custom field types instead of emitting undefined
  identifiers.
- Numeric validation now covers all int/uint/float subtypes coherently;
  no more unused ErrInvalid…Range constants; no required tag / dead checks
  on slice/pointer fields.
- SQL seeds emit real values for slice/pointer/custom fields (was NULL).
- Mocks now implement the REAL interfaces: correct method names/signatures
  and per-field finders; example test uses the real API + compile-time
  interface assertions.

## usecase
- Standalone `goca usecase` compiles: generates the repository interface it
  depends on and drops the contradictory usecase-package interface.
- `--async` emits real, compilable async wrappers (was undefined types).
- Generic update method uses real DTO fields (was Spanish undefined fields).
- `--dto-validation` actually calls input.Validate().
- Errors when the target entity doesn't exist. English-only output.

## repository
- Elasticsearch repo imports esapi; Mongo repo implements full CRUD.
- Postgres `--cache` generates the cache helper methods it calls (go-redis/v9).
- Cache decorator only emits finders that exist; supports `--transactions`.
- `--database` routes sqlite/sqlserver/postgres-json/elasticsearch/dynamodb
  to their real generators in the field-aware path (was: all → Postgres).

## di / integrate
- `goca integrate` emits VALID Go for cmd/server/main.go (was unparseable:
  missing LHS, brace/else mismatches), targets cmd/server/main.go, and only
  integrates features that have all layers (skips orphan domain entities).
- `goca di --wire` produces wire-processable code (gorm DB provider, matching
  return types); `--cache`/`--database mongodb` only emit constructors that
  exist.

## feature (flagship auto-integration — was a no-op that printed success)
- Auto-migration actually inserts &domain.Entity{} into cmd/server/main.go.
- Routes + DI container are really wired into main.go (idempotent).
- Multiple features coexist: routes.go and the DI container are extended for
  the 2nd+ feature instead of being skipped.

## handler / middleware
- handler+middleware-package output compiles (mux.MiddlewareFunc wrap).
- Shared contextKey type moved to base middleware.go (request-id et al. build).
- gRPC server uses the flat usecase output and real entity fields.
- `go mod tidy` is best-effort (no longer corrupts go.mod on failure).
- `--swagger` emits the documented @Summary/@Router/@success annotations.
- Lowercase middleware package names allowed; entity-existence is validated;
  success messages are truthful (no empty-dir false success).

## init
- Validate --database/--api values; persist --api/--auth in .goca.yaml.
- DB-aware docker-compose (image/port/env/healthcheck/volume), README, and
  config defaults for postgres/mysql/mongodb/sqlite/sqlserver/dynamodb/es;
  mongo healthcheck uses mongosh.
- Refuse non-empty target dir without --force; fix fenced code blocks; drop
  the test-only `replace` directive; git init no longer hangs on gpg/stdin.

## analyze / doctor / config / safety
- analyze no longer false-warns on goca's own layout (finds cmd/server/main.go
  and os.Getenv in pkg/config); `--output json` emits valid JSON;
  `--fail-on-warn` exits 2; detects `:=` hardcoded secrets.
- `config validate` uses the real semantic validator (was a stub that passed
  invalid configs); `config init` validates --template/--database.
- doctor DI check no longer false-negatives; dry-run never errors on existing
  files.

## template / ui / version / test-integration
- `template list` lists templates; `template show`/`reset` implemented.
- `--quiet` suppresses file/table output; `version` still prints under
  `--quiet`; version reads VCS info from build metadata.
- test-integration: guards nonexistent entities, real MySQL setup (no
  permanent t.Skip), real testcontainers setup for `--container`.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@sazardev sazardev merged commit 550e88f into master Jun 14, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant