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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
use crate::generators::layout::{self, Layer};
use std::{fs, path::Path};

use crate::generators::naming::write_file;
use crate::generators::render::render;

/// The containers' tasks (`docker-compose.yml`): `--db`, the first mail and auth add them, once.
const COMPOSE_TASKS: &str = r#"
  docker-compose:up:
    desc: Arranca todos los contenedores (y espera a que estén sanos)
    cmd: docker compose up -d --wait

  docker-compose:down:
    desc: Para todos los contenedores
    cmd: docker compose down
"#;

const DB_TASKS: &str = r#"
  db:arrancar:
    desc: Arranca los contenedores de la base de datos
    deps: [docker-compose:up]

  db:parar:
    desc: Para los contenedores de la base de datos
    deps: [docker-compose:down]

  db:reiniciar:
    desc: "Vacía la base de datos y vuelve a aplicar las migraciones (DESTRUCTIVO; sin preguntar: task --yes db:reiniciar)"
    prompt: Esto destruye TODOS los datos de la base de datos. ¿Seguro?
    cmds:
      - docker compose down -v
      - docker compose up -d --wait
      - sqlx migrate run --source migraciones

  sqlx:online:
    desc: Pasa SQLx a modo ONLINE (comprueba contra la base de datos en marcha)
    cmd: printf '[env]\nSQLX_OFFLINE = "false"\n' > .cargo/config.toml

  sqlx:offline:
    desc: Pasa SQLx a modo OFFLINE (usa la caché guardada)
    cmd: printf '[env]\nSQLX_OFFLINE = "true"\n' > .cargo/config.toml

  sqlx:migrate:
    desc: Aplica las migraciones pendientes
    deps: [docker-compose:up]
    cmd: sqlx migrate run --source migraciones

  sqlx:prepare:
    desc: Regenera la caché offline de SQLx (necesita la base de datos en marcha)
    deps: [docker-compose:up]
    cmd: SQLX_OFFLINE=false cargo sqlx prepare --workspace

  sqlx:check:
    desc: Comprueba que la caché de SQLx coincide con las consultas actuales
    deps: [docker-compose:up]
    cmd: SQLX_OFFLINE=false cargo sqlx prepare --workspace --check

  generar:migracion:
    desc: Crea una migración SQLx nueva — task generar:migracion NOMBRE=anadir_usuarios
    requires:
      vars: [NOMBRE]
    cmd: puerto generar migracion {{.NOMBRE}}
"#;

/// Appends `tasks` (indented as entries of `tasks:`, the Taskfile's last key) to the project's
/// `Taskfile.yml`, unless the task `first` is already there. No Taskfile, nothing to do.
pub(crate) fn add_tasks(
    base: &Path,
    first: &str,
    tasks: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let path = base.join(layout::TASKFILE);
    let Ok(mut src) = fs::read_to_string(&path) else {
        return Ok(());
    };
    if src.contains(&format!("\n  {first}:\n")) {
        return Ok(());
    }
    if !src.ends_with('\n') {
        src.push('\n');
    }
    src.push_str(tasks);
    fs::write(&path, src)?;
    Ok(())
}

/// Adds `packages` to the `packages` list of the project's `devenv.nix` (Fase 34.2), after a
/// `comment` line that says who needs them, unless the first one is there. No devenv.nix, nothing.
pub(crate) fn add_devenv_packages(
    base: &Path,
    comment: &str,
    packages: &[&str],
) -> Result<(), Box<dyn std::error::Error>> {
    let path = base.join(layout::DEVENV_NIX);
    let Ok(src) = fs::read_to_string(&path) else {
        return Ok(());
    };
    let list = "packages = with pkgs; [\n";
    let (Some(start), Some(first)) = (src.find(list), packages.first()) else {
        return Ok(());
    };
    let Some(end) = src[start..].find("\n  ]").map(|at| start + at + 1) else {
        return Ok(());
    };
    if src[start..end].lines().any(|line| line.trim() == *first) {
        return Ok(());
    }
    let lines: String = packages.iter().map(|p| format!("    {p}\n")).collect();
    fs::write(
        &path,
        format!("{}    # {comment}\n{lines}{}", &src[..end], &src[end..]),
    )?;
    Ok(())
}

/// `docker-compose:up` / `docker-compose:down`, once.
pub(crate) fn add_compose_tasks(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    add_tasks(base, "docker-compose:up", COMPOSE_TASKS)
}

/// The task `task` of the Taskfile starts the containers first (`deps: [docker-compose:up]`),
/// once however many features ask.
pub(crate) fn add_compose_dependency(
    base: &Path,
    task: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let path = base.join(layout::TASKFILE);
    let Ok(src) = fs::read_to_string(&path) else {
        return Ok(());
    };
    let header = format!("\n  {task}:\n");
    let Some(at) = src.find(&header) else {
        return Ok(());
    };
    let body = at + header.len();
    let mut block = src[body..]
        .split_inclusive('\n')
        .take_while(|line| line.starts_with("   "));
    if block.any(|line| line.starts_with("    deps:")) {
        return Ok(());
    }
    fs::write(
        &path,
        format!(
            "{}    deps: [docker-compose:up]\n{}",
            &src[..body],
            &src[body..]
        ),
    )?;
    Ok(())
}

fn docker_compose_content(project_name: &str, db_name: &str) -> String {
    format!(
        "services:\n  postgres:\n    image: postgres:16\n    container_name: {project_name}-postgres\n    ports:\n      - \"${{DB_HOST_PORT:-5432}}:5432\"\n    environment:\n      POSTGRES_USER: devuser\n      POSTGRES_PASSWORD: password\n      POSTGRES_DB: {db_name}\n    volumes:\n      - postgres-data:/var/lib/postgresql/data\n    restart: unless-stopped\n    healthcheck:\n      test: [\"CMD-SHELL\", \"pg_isready -U devuser -d {db_name}\"]\n      interval: 5s\n      timeout: 5s\n      retries: 5\n\nvolumes:\n  postgres-data:\n"
    )
}

fn add_env_to_gitignore(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let path = base.join(".gitignore");
    if path.exists() {
        let mut src = fs::read_to_string(&path)?;
        if !src.contains(".env") {
            if !src.ends_with('\n') {
                src.push('\n');
            }
            src.push_str(".env\n");
            fs::write(&path, src)?;
        }
    } else {
        // `.sqlx/` is deliberately *not* ignored: `--db` projects compile with SQLX_OFFLINE=true,
        // so the query cache written by `task sqlx:prepare` must be committed for a clone (or CI)
        // to build without a live database.
        write_file(&path, "/target\n.env\n")?;
    }
    Ok(())
}

/// The tasks of a `--db` project: the containers, the database, SQLx; `run` and
/// `test:infraestructura` start the database first, and `run` no longer warns of the in-memory
/// repositories.
fn add_db_tasks(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    add_compose_tasks(base)?;
    add_tasks(base, "db:arrancar", DB_TASKS)?;
    for task in ["run", "test:infraestructura"] {
        add_compose_dependency(base, task)?;
    }
    let path = base.join(layout::TASKFILE);
    if let Ok(src) = fs::read_to_string(&path) {
        fs::write(
            &path,
            src.replace(" (en memoria: los datos se pierden al reiniciar)", ""),
        )?;
    }
    Ok(())
}

/// `migrador/`: the one `MIGRADOR` of the whole database (ADR-0023 § 6).
const MIGRADOR_MANIFEST: &str = r#"[package]
name = "migrador"
version = "0.1.0"
edition = "2024"

[dependencies]
sqlx = { workspace = true }
"#;

const MIGRADOR_LIB: &str = r#"//! Las migraciones de toda la base de datos (`migraciones/`), incrustadas al compilar: `api` las
//! aplica al arrancar y todos los tests de Postgres corren sobre ellas —
//! `#[sqlx::test(migrator = "migrador::MIGRADOR")]` (ADR-0023 § 6 de Puerto).

pub static MIGRADOR: sqlx::migrate::Migrator = sqlx::migrate!("../migraciones");
"#;

/// Without it, `migrate!` does not see a new migration until some `.rs` file changes.
const MIGRADOR_BUILD: &str = r#"fn main() {
    println!("cargo:rerun-if-changed=../migraciones");
}
"#;

/// The workspace side of `--db`: `migrador` as a member, `sqlx` and `puerto-sqlx` as dependencies,
/// and the `api` binary on both (the pool, the migrations at startup, the readiness ping).
fn add_migrador(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    write_file(
        &base.join(layout::MIGRADOR_DIR).join("Cargo.toml"),
        MIGRADOR_MANIFEST,
    )?;
    write_file(
        &base.join(layout::MIGRADOR_DIR).join("src/lib.rs"),
        MIGRADOR_LIB,
    )?;
    write_file(
        &base.join(layout::MIGRADOR_DIR).join("build.rs"),
        MIGRADOR_BUILD,
    )?;
    let manifest = base.join(layout::WORKSPACE_MANIFEST);
    let src = fs::read_to_string(&manifest)?;
    if !src.contains("\"migrador\"") {
        fs::write(
            &manifest,
            src.replacen("\"nucleo\", ", "\"nucleo\", \"migrador\", ", 1),
        )?;
    }
    add_workspace_dependency(base, "puerto-sqlx")?;
    crate::generators::crates::add_internal_dependency(base, "migrador", layout::MIGRADOR_DIR)?;
    for name in ["migrador", "puerto-sqlx"] {
        crate::generators::bootstrap::add_crate_dependency(
            base,
            layout::API_MANIFEST,
            "dependencies",
            name,
            "{ workspace = true }",
        )?;
    }
    crate::generators::crates::sync_workspace_dependencies(base)?;
    Ok(())
}

/// Adds the service `name` (its YAML, indented as a service) to `docker-compose.yml`: after the
/// last service, before the top-level volumes. Creates the file when the project has none.
pub(crate) fn add_compose_service(
    base: &Path,
    name: &str,
    service: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let path = base.join("docker-compose.yml");
    if !path.exists() {
        write_file(&path, &format!("services:\n{service}"))?;
        return Ok(());
    }
    let src = fs::read_to_string(&path)?;
    if src.contains(&format!("\n  {name}:\n")) {
        return Ok(());
    }
    let out = match src.find("\nvolumes:\n") {
        Some(at) => format!("{}{service}{}", &src[..=at], &src[at..]),
        None => {
            let sep = if src.ends_with('\n') { "" } else { "\n" };
            format!("{src}{sep}{service}")
        }
    };
    fs::write(&path, out)?;
    Ok(())
}

/// Adds runtime crate `name` to the root `[workspace.dependencies]`, after the runtime crates the
/// template declares and on the same minor as this CLI.
pub(crate) fn add_workspace_dependency(
    base: &Path,
    name: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    let version = format!(
        "\"{}\"",
        crate::runtime::requirement(env!("CARGO_PKG_VERSION"))
    );
    let path = base.join(layout::WORKSPACE_MANIFEST);
    let src = fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
    // No runtime crate left (`--sin-demo` without web): under the block's comment again.
    let comment = "# en estos crates, en la misma versión minor que la CLI `puerto` que generó este proyecto.\n";
    if !src.lines().any(|l| l.starts_with("puerto-")) && src.contains(comment) {
        fs::write(
            &path,
            src.replacen(comment, &format!("{comment}{name} = {version}\n"), 1),
        )?;
        return Ok(());
    }
    insert_workspace_dependency(base, name, &version, Some("puerto-"))
}

/// Adds `name = value` to the root `[workspace.dependencies]` unless it is there: after the last
/// entry starting with `after` when there is one, else at the end of the table.
pub(crate) fn insert_workspace_dependency(
    base: &Path,
    name: &str,
    value: &str,
    after: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    let path = base.join(layout::WORKSPACE_MANIFEST);
    let src = fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
    if src.lines().any(|l| l.starts_with(&format!("{name} = "))) {
        return Ok(());
    }
    let header = "[workspace.dependencies]\n";
    let Some(at) = src.find(header) else {
        return Err(format!(
            "{}: no tiene tabla [workspace.dependencies]",
            path.display()
        )
        .into());
    };
    let line = format!("{name} = {value}");
    let body = at + header.len();
    let table_end = src[body..].find("\n[").map_or(src.len(), |i| body + i + 1);
    let table = &src[body..table_end];
    // The end of the last `after…` line, else of the table's last entry.
    let anchor = after
        .and_then(|prefix| {
            let mut offset = 0;
            let mut found = None;
            for l in table.split_inclusive('\n') {
                if l.starts_with(prefix) {
                    found = Some(offset + l.trim_end().len());
                }
                offset += l.len();
            }
            found
        })
        .unwrap_or_else(|| table.trim_end().len());
    let end = body + anchor;
    let out = if anchor > 0 {
        format!("{}\n{line}{}", &src[..end], &src[end..])
    } else {
        format!("{}{line}\n{}", &src[..body], &src[body..])
    };
    fs::write(&path, out)?;
    Ok(())
}

/// Write the base `.env` and `.env.example` for every new project (db or not).
/// `scripts/sembrar.sh` (27.21): the example data `task sembrar` sends to the running API, with the
/// helpers of the project's auth. Written once, executable; the user's from then on.
pub fn write_seed_script(
    base: &Path,
    auth: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
    let path = base.join("scripts/sembrar.sh");
    if path.exists() {
        return Ok(());
    }
    let mut ctx = tera::Context::new();
    ctx.insert("auth", &auth.unwrap_or_default());
    let name = crate::puerto_toml::read(base)
        .map(|c| c.project.name)
        .unwrap_or_default();
    ctx.insert("host", &name.replace('_', "-"));
    crate::generators::naming::write_file(
        &path,
        &crate::generators::render::render("scripts/sembrar.sh.tera", &ctx)?,
    )?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))?;
    }
    Ok(())
}

pub fn apply_base_env(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let content = "SERVICE_PORT=8080\nENV=development\nRUST_LOG=info\nCORS_ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173\n";
    write_file(&base.join(".env"), content)?;
    write_file(&base.join(".env.example"), content)?;
    add_env_to_gitignore(base)?;
    Ok(())
}

/// Write the extra files that `puerto nuevo --db` adds on top of the base template.
pub fn apply_db_to_new_project(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let project_name = base.file_name().and_then(|n| n.to_str()).unwrap_or("myapp");
    let db_name = project_name.replace('-', "_");

    // docker-compose.yml
    write_file(
        &base.join("docker-compose.yml"),
        &docker_compose_content(project_name, &db_name),
    )?;

    // Append DB vars to .env and .env.example (apply_base_env already created them)
    let db_vars = format!(
        "\n# Base de datos\nDB_HOST_PORT=5432\nDATABASE_URL=postgres://devuser:password@localhost:5432/{db_name}\n"
    );
    for file in &[".env", ".env.example"] {
        let path = base.join(file);
        let mut content = if path.exists() {
            fs::read_to_string(&path)?
        } else {
            String::new()
        };
        if !content.contains("DATABASE_URL") {
            if !content.ends_with('\n') && !content.is_empty() {
                content.push('\n');
            }
            content.push_str(&db_vars);
            fs::write(&path, content)?;
        }
    }

    // .cargo/config.toml — SQLX_OFFLINE so CI compiles without a live DB
    write_file(
        &base.join(".cargo/config.toml"),
        "[env]\nSQLX_OFFLINE = \"true\"\n",
    )?;

    // migraciones/ (empty: sqlx needs it) and the crate that embeds it.
    fs::create_dir_all(base.join(layout::MIGRATIONS_DIR))?;
    add_migrador(base)?;

    add_db_tasks(base)?;
    add_devenv_packages(
        base,
        "--db: las migraciones y la caché de consultas (task sqlx:*)",
        &["sqlx-cli"],
    )?;

    // Mark the project as db-enabled in puerto.toml
    let mut config = crate::puerto_toml::read(base)?;
    config.project.db = true;
    crate::puerto_toml::write(base, &config)?;

    Ok(())
}

/// The root `AGENTS.md` section an `events` project gets (ADR-0010: what it names is tested).
const AGENTS_EVENTS_SECTION: &str = r#"## Eventos de dominio (`[proyecto] eventos`)

Toda escritura de una entidad CRUD pasa por su unidad de trabajo, que guarda la entidad y registra
un evento en la tabla `outbox` en una sola transacción (ADR-0018 de Puerto). El repositorio solo
lee.

- **No edites nunca a mano `contextos/<c>/dominio/src/eventos.rs`**: se reescribe a partir de
  `puerto.toml` (el snapshot sigue los campos de la entidad). Añade un evento con
  `puerto generar evento <Entidad> <nombre>`.
- **La entidad emite sus eventos** (ADR-0026 de Puerto): `Producto::crear(props)` devuelve la
  entidad y su `Creado`; `actualizar` y `borrar`, su evento. Un evento propio lo emite un método
  tuyo de la entidad: `pub fn publicar(&mut self) -> EventoProducto { …;
  EventoProducto::Publicado(SnapshotProducto::from_entidad(self)) }`. Un evento que nadie guarda
  es un aviso (`#[must_use]`), y `task lint` lo rechaza.
- Un caso de uso de escritura guarda la entidad y su evento con `uow_factory.guardar(&entidad,
  evento)`: los dos en una transacción, o ninguno. Para escribir más de una vez, la unidad de
  trabajo a mano: `begin()` → `guardar` → `registrar` → `commit`; salir antes con `?`, sin llegar
  al `commit`, deshace todo.
- El snapshot es un contrato público: los consumidores lo decodifican. Renombrar un campo lo cambia.
- `presentacion/worker/` es el segundo proceso: hace de relay del outbox y ejecuta los consumidores
  (`task worker`). **No edites nunca a mano `presentacion/worker/src/generado/registro.rs`.**
  Añade un consumidor con `puerto generar consumidor <nombre> --tras <tipo_evento>`; su handler
  debe ser idempotente: la entrega es al menos una vez. Ver `presentacion/worker/AGENTS.md`.

"#;

/// Turns a fresh `--db` project into an `events` one (`puerto nuevo --db --eventos <transport>`):
/// `[proyecto] eventos`, the outbox migration, serde for the event snapshots and the `AGENTS.md`
/// section that says how writes work.
pub fn apply_events_to_new_project(
    base: &Path,
    transport: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    crate::validation::validate_events_transport(transport)?;
    let mut config = crate::puerto_toml::read(base)?;
    if !config.project.db {
        return Err("--eventos necesita una base de datos: añade --db".into());
    }
    config.project.events = Some(transport.to_string());
    crate::puerto_toml::write(base, &config)?;

    let outbox = render("infrastructure/outbox.sql", &tera::Context::new())?;
    let outbox = if transport == crate::generators::worker::KAFKA_TRANSPORT {
        without_event_deliveries(&outbox)?
    } else {
        outbox
    };
    crate::generators::migration::run_migration("outbox", base, Some(&outbox))?;

    let agents_path = base.join("AGENTS.md");
    let agents = fs::read_to_string(&agents_path)?;
    if !agents.contains(AGENTS_EVENTS_SECTION) {
        // Before the conventions: next to the rules about generated files.
        let out = match agents.find("## Convenciones") {
            Some(at) => format!("{}{AGENTS_EVENTS_SECTION}{}", &agents[..at], &agents[at..]),
            None => format!("{agents}\n{AGENTS_EVENTS_SECTION}"),
        };
        fs::write(&agents_path, out)?;
    }

    crate::generators::worker::apply_worker_to_new_project(base)?;
    Ok(())
}

/// The outbox migration of the `kafka` transport: Kafka holds the deliveries, so the `db`
/// transport's `entregas_eventos` table and its index are left out. The template stays the byte
/// copy of `puerto-sqlx`'s migration (tested), so this cuts it rather than keeping a second one.
fn without_event_deliveries(sql: &str) -> Result<String, Box<dyn std::error::Error>> {
    let start = sql.find("CREATE TABLE entregas_eventos");
    let index = "CREATE INDEX entregas_eventos_vencidas";
    let end = sql
        .find(index)
        .and_then(|at| sql[at..].find(";\n\n").map(|i| at + i + ";\n\n".len()));
    match (start, end) {
        (Some(start), Some(end)) if start < end => Ok(format!("{}{}", &sql[..start], &sql[end..])),
        _ => Err(
            "la migración del outbox no tiene el bloque `entregas_eventos` que hay que quitar"
                .into(),
        ),
    }
}

/// An already-absent file is what a removal wants; any other failure is a real error.
fn ignore_not_found(result: std::io::Result<()>) -> std::io::Result<()> {
    match result {
        Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
        _ => Ok(()),
    }
}

/// Strip the Saludo demo entity from a freshly generated project (`puerto nuevo --sin-demo`):
/// its context's four crates and their declarations, its entity in puerto.toml, and the wiring
/// regenerated without it.
pub fn apply_no_demo(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    ignore_not_found(fs::remove_dir_all(base.join(layout::context_dir("saludo"))))?;
    ignore_not_found(fs::remove_dir_all(
        base.join(layout::cableado_context_dir("saludo")),
    ))?;
    crate::generators::crates::remove_contexts_member(base)?;
    for layer in Layer::ALL {
        let name = layout::crate_name("saludo", layer);
        crate::generators::crates::remove_internal_dependency(base, &name)?;
        crate::generators::crates::remove_dependency_line(base, layout::API_MANIFEST, &name)?;
    }

    let mut config = crate::puerto_toml::read(base)?;
    config.entity.clear();
    crate::puerto_toml::write(base, &config)?;

    crate::generators::bootstrap::regenerate_bootstrap(base)?;

    Ok(())
}

/// The heading of the root `AGENTS.md` section that describes `web/`.
const AGENTS_WEB_SECTION: &str = "## Frontend (`web/`)";

/// Strip the web frontend from a freshly generated project (`puerto nuevo --sin-web`): the `web/`
/// directory, `[proyecto] web`, the root `AGENTS.md` section that describes it and the spec export
/// test in `bootstrap.rs`.
pub fn apply_no_web(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    ignore_not_found(fs::remove_dir_all(base.join("web")))?;

    let agents_path = base.join("AGENTS.md");
    let agents = fs::read_to_string(&agents_path)?;
    fs::write(&agents_path, without_section(&agents, AGENTS_WEB_SECTION))?;
    write_web_blocks(base, false)?;

    let mut config = crate::puerto_toml::read(base)?;
    config.project.web = false;
    crate::puerto_toml::write(base, &config)?;

    crate::generators::bootstrap::regenerate_bootstrap(base)?;

    Ok(())
}

/// The markers around the lines that only hold with `web/` — inside sections that stay, so
/// [`without_section`] cannot drop them. In a YAML or nix file they are a comment (`# <!-- web -->`).
const WEB_BLOCK_START: &str = "<!-- web -->";
const WEB_BLOCK_END: &str = "<!-- /web -->";

/// The project files with web-only blocks.
const WEB_BLOCK_FILES: [&str; 3] = ["AGENTS.md", "Taskfile.yml", "devenv.nix"];

/// `text` with its web-only blocks kept (`web`) or dropped, and the marker lines gone.
fn web_blocks(text: &str, web: bool) -> String {
    let mut out = String::with_capacity(text.len());
    let mut inside = false;
    for line in text.split_inclusive('\n') {
        match line.trim().trim_start_matches('#').trim_start() {
            WEB_BLOCK_START => inside = true,
            WEB_BLOCK_END => inside = false,
            _ if inside && !web => {}
            _ => out.push_str(line),
        }
    }
    out
}

/// Keeps (`web`) or drops the web-only blocks of [`WEB_BLOCK_FILES`], without their markers.
fn write_web_blocks(base: &Path, web: bool) -> Result<(), Box<dyn std::error::Error>> {
    for file in WEB_BLOCK_FILES {
        let path = base.join(file);
        fs::write(&path, web_blocks(&fs::read_to_string(&path)?, web))?;
    }
    Ok(())
}

/// Keeps the web-only blocks of a project with `web/`, without their markers.
pub fn keep_web_blocks(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    write_web_blocks(base, true)
}

/// `puerto nuevo --portada` (ADR-0028): `[proyecto] portada` and `ruta_app`, the welcome portada
/// at `/` (`portada/bienvenida`) with its test, and `rutaApp` in `generado/rutas.tsx`.
pub fn apply_portada(base: &Path, app_path: &str) -> Result<(), Box<dyn std::error::Error>> {
    crate::validation::validate_app_path(app_path)?;
    let mut config = crate::puerto_toml::read(base)?;
    config.project.portada = true;
    config.project.app_path = Some(app_path.to_string());
    crate::puerto_toml::write(base, &config)?;
    crate::generators::blocks::run_install(
        "portada/bienvenida",
        base,
        crate::generators::conflict::OverwritePolicy::Force,
    )?;
    write_file(
        &base
            .join(layout::WEB_DIR)
            .join("src/paginas/portada.test.tsx"),
        &render("web/portada.test.tsx.tera", &tera::Context::new())?,
    )?;
    crate::generators::web::regenerate_web(base, &config)?;
    write_main(base)
}

/// `web/src/main.tsx` of a project with auth or a portada: the pages outside the app's frame (the
/// portada, the access pages) and the app in `Marco`. Without either, the template's stays.
pub fn write_main(base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let config = crate::puerto_toml::read(base)?;
    let mut ctx = tera::Context::new();
    ctx.insert("auth", &config.project.has_auth());
    ctx.insert("local", &(config.project.auth.as_deref() == Some("local")));
    ctx.insert("portada", &config.project.portada);
    write_file(
        &base.join(layout::WEB_DIR).join("src/main.tsx"),
        &render("web/main.tsx.tera", &ctx)?,
    )?;
    Ok(())
}

/// `markdown` without the `## ` section that starts at `heading`, up to the next `## ` heading.
fn without_section(markdown: &str, heading: &str) -> String {
    let Some(start) = markdown.find(&format!("{heading}\n")) else {
        return markdown.to_string();
    };
    let body = start + heading.len();
    let end = markdown[body..]
        .find("\n## ")
        .map_or(markdown.len(), |offset| body + offset + 1);
    format!("{}{}", &markdown[..start], &markdown[end..])
}

#[cfg(test)]
mod tests {
    use super::without_section;

    #[test]
    fn should_drop_web_blocks_and_their_markers_when_there_is_no_web() {
        let markdown = "a\n<!-- web -->\nw\n<!-- /web -->\nb\n";
        assert_eq!(super::web_blocks(markdown, false), "a\nb\n");
    }

    #[test]
    fn should_keep_web_blocks_without_their_markers_when_there_is_web() {
        let markdown = "a\n<!-- web -->\nw\n<!-- /web -->\nb\n";
        assert_eq!(super::web_blocks(markdown, true), "a\nw\nb\n");
    }

    #[test]
    fn should_keep_the_next_section_when_removing_one_in_the_middle() {
        let markdown = "# T\n\n## A\n\na\n\n## Web\n\nw\n\n## B\n\nb\n";
        assert_eq!(
            without_section(markdown, "## Web"),
            "# T\n\n## A\n\na\n\n## B\n\nb\n"
        );
    }

    #[test]
    fn should_drop_up_to_the_end_when_the_section_is_the_last_one() {
        assert_eq!(
            without_section("## A\n\na\n\n## Web\n\nw\n", "## Web"),
            "## A\n\na\n\n"
        );
    }

    #[test]
    fn should_leave_the_markdown_alone_when_the_section_is_absent() {
        assert_eq!(without_section("## A\n\na\n", "## Web"), "## A\n\na\n");
    }
}