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
//! `puerto generar campo <Entidad> -- <campo:Tipo> …` (Fase 33.3): new fields on an entity that
//! already has code, without losing what the user wrote in its files.
//!
//! The entity is generated twice, in throwaway copies of the project: as `puerto.toml` describes it
//! and with the new fields. Every file that differs between the two is merged into the project's
//! (three-way, like git): the field lands, the user's edits stay, and a field that lands on a line
//! the user changed leaves conflict markers. A `--db` project also gets an `ALTER TABLE` migration.

use std::fs;
use std::path::{Path, PathBuf};

use crate::generators::infrastructure::{foreign_key_name, join_table_sql, sql_ddl_col};
use crate::generators::layout;
use crate::generators::naming::{is_crud_entity, pascal_to_snake, pluralize, to_pascal_case};
use crate::generators::types::{
    columns, example_of, is_composite_vo, is_enum_vo, is_reference, is_vec_reference,
};
use crate::puerto_toml::{Field, ValueObjectDefinition};

/// Never copied: build output, dependencies, history, the devenv/direnv state.
const NOT_COPIED: &[&str] = &[
    "target",
    "node_modules",
    ".git",
    "dist",
    ".devenv",
    ".direnv",
];

/// Never merged: the migrations, which this command writes itself.
const NOT_MERGED: &str = "migraciones";

pub fn run_add_fields(
    name: &str,
    base: &Path,
    new_fields: &[Field],
) -> Result<(), Box<dyn std::error::Error>> {
    let config = crate::puerto_toml::read(base)?;
    let pascal = to_pascal_case(name);
    let snake = pascal_to_snake(&pascal);
    let Some(entity) = config.entity.iter().find(|e| e.name == pascal) else {
        return Err(format!(
            "{pascal} no está en puerto.toml; una entidad nueva se crea con `puerto generar \
             scaffold {pascal} -- …`"
        )
        .into());
    };
    if !is_crud_entity(&snake, &entity.use_cases)
        || !base.join(layout::domain_file(&snake, "modelo")).exists()
    {
        return Err(format!(
            "{pascal} no es una entidad CRUD con código: `generar campo` añade campos a una entidad \
             que escribió `puerto generar scaffold`"
        )
        .into());
    }
    if new_fields.is_empty() {
        return Err(format!(
            "faltan los campos, tras --: puerto generar campo {pascal} -- stock:i64"
        )
        .into());
    }
    let db = config.project.db;
    check_new_fields(new_fields, db)?;

    // An entity without fields has the default `nombre`: it stays.
    let mut fields = crate::generators::effective_fields(&entity.fields);
    fields.extend(new_fields.iter().cloned());
    // What `scaffold` checks, on the whole list: a new field that repeats one, a reserved word…
    crate::validation::validate_unique_field_names(&fields)?;
    if db {
        for c in fields.iter().flat_map(columns) {
            crate::validation::validate_sql_field_name(&c.name)?;
        }
    }
    let vo_conflicts = crate::validation::validate_vo_coherence(&fields, &config.value_object);
    if !vo_conflicts.is_empty() {
        return Err(vo_conflicts.join("\n  ").into());
    }
    crate::validation::validate_references_before_writing(&pascal, &fields, &config, base)?;

    let before = rendered(base, &pascal, db, &entity.fields, &config.value_object)?;
    let after = rendered(base, &pascal, db, &fields, &config.value_object)?;
    let merged = merge_into(base, before.path(), after.path())?;

    let names: Vec<&str> = new_fields.iter().map(|f| f.name.as_str()).collect();
    println!("✓ puerto.toml: {pascal} gana {}", names.join(", "));
    println!(
        "✓ {} fichero(s) puestos al día, sin tocar lo que habías escrito",
        merged.updated
    );
    if db {
        // As `puerto.toml` reads them: a composite with its parts, a shared VO with its example.
        let added: Vec<Field> = crate::puerto_toml::read(after.path())?
            .entity
            .into_iter()
            .find(|e| e.name == pascal)
            .map(|e| e.fields)
            .unwrap_or_default()
            .into_iter()
            .filter(|f| names.contains(&f.name.as_str()))
            .collect();
        let migration = format!("anadir_{}_a_{}", names.join("_y_"), pluralize(&snake));
        crate::generators::migration::run_migration(
            &migration,
            base,
            Some(&add_columns_sql(&snake, &added)),
        )?;
        let initial = initial_values(&added);
        if !initial.is_empty() {
            println!(
                "  Las filas que ya existen reciben {}: cámbialo en la migración antes de aplicarla \
                 si no es lo que quieres.",
                initial.join(", ")
            );
        }
    }
    if config.project.web {
        println!(
            "\nLa API cambió. Siguiente: task web:sync   (exporta la especificación y regenera los \
             tipos de la web)"
        );
    }

    if merged.conflicts.is_empty() {
        return Ok(());
    }
    let list: Vec<String> = merged
        .conflicts
        .iter()
        .map(|p| format!("  {}", p.display()))
        .collect();
    Err(format!(
        "{} fichero(s) con conflictos: el campo cae sobre líneas que cambiaste a mano. Busca \
         `<<<<<<<` en cada uno, quédate con lo que quieras de los dos lados y compila:\n{}",
        merged.conflicts.len(),
        list.join("\n")
    )
    .into())
}

/// A unique field would take the same value in every existing row; a required reference has no
/// id to give them.
fn check_new_fields(fields: &[Field], db: bool) -> Result<(), String> {
    for f in fields {
        if f.unique {
            return Err(format!(
                "{}: un campo único (`!`) no se añade con `generar campo`, porque las filas que ya \
                 existen tendrían todas el mismo valor. Añádelo sin `!`, y su índice único con \
                 `puerto generar migracion`",
                f.name
            ));
        }
        let required_reference =
            is_reference(f) && !is_vec_reference(f) && !f.field_type.starts_with("Option<");
        if db && required_reference {
            return Err(format!(
                "{}: una referencia obligatoria no se puede añadir a una tabla que ya tiene filas \
                 (no hay un id que darles). Añádela opcional, con `ref:opt:`",
                f.name
            ));
        }
    }
    Ok(())
}

/// A copy of the project with the entity written from `fields`, formatted like the project's own
/// files (every command ends with `cargo fmt`, ADR-0019): what its files would be without hand edits.
fn rendered(
    base: &Path,
    pascal: &str,
    db: bool,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> Result<tempfile::TempDir, Box<dyn std::error::Error>> {
    let copy = tempfile::tempdir()?;
    copy_project(base, copy.path())?;
    crate::generators::scaffold::write_entity(pascal, copy.path(), db, fields, shared_vos)?;
    crate::generators::format::format_project(copy.path())
        .map_err(|e| format!("no se puede comparar sin formatear: {e}"))?;
    Ok(copy)
}

/// Links are skipped: no entity file is one, and `.devenv` points into the nix store.
fn copy_project(from: &Path, to: &Path) -> std::io::Result<()> {
    for entry in fs::read_dir(from).map_err(copy_error(from))? {
        let entry = entry.map_err(copy_error(from))?;
        let path = entry.path();
        let name = entry.file_name();
        let target = to.join(&name);
        let file_type = entry.file_type().map_err(copy_error(&path))?;
        if file_type.is_symlink() {
            continue;
        }
        if file_type.is_dir() {
            if NOT_COPIED.iter().any(|d| name == *d) {
                continue;
            }
            fs::create_dir_all(&target).map_err(copy_error(&target))?;
            copy_project(&path, &target)?;
        } else {
            fs::copy(&path, &target).map_err(copy_error(&path))?;
        }
    }
    Ok(())
}

fn copy_error(path: &Path) -> impl FnOnce(std::io::Error) -> std::io::Error + '_ {
    move |e| {
        std::io::Error::new(
            e.kind(),
            format!("no se puede copiar {}: {e}", path.display()),
        )
    }
}

#[derive(Debug, Default)]
struct Merged {
    updated: usize,
    conflicts: Vec<PathBuf>,
}

/// Every file `after` changed with respect to `before`, merged into `base`: written as is where
/// `base` still has what `before` has, merged three-way where it was edited. A file the user
/// deleted stays deleted.
fn merge_into(
    base: &Path,
    before: &Path,
    after: &Path,
) -> Result<Merged, Box<dyn std::error::Error>> {
    let mut merged = Merged::default();
    for rel in files_under(after, Path::new(""))? {
        let theirs = fs::read(after.join(&rel))?;
        let ancestor = fs::read(before.join(&rel)).ok();
        if ancestor.as_deref() == Some(theirs.as_slice()) {
            continue;
        }
        let ours = fs::read(base.join(&rel)).ok();
        let content = match (ours, ancestor) {
            (Some(ours), _) if ours == theirs => continue,
            // Deleted by hand: it stays deleted.
            (None, Some(_)) => continue,
            (None, None) => theirs,
            (Some(ours), Some(ancestor)) if ours == ancestor => theirs,
            // Edited by hand, or a file of the user's where the new one goes: three-way.
            (Some(ours), ancestor) => {
                let text = |bytes: Vec<u8>| String::from_utf8(bytes).ok();
                let (Some(ancestor), Some(ours), Some(new)) =
                    (text(ancestor.unwrap_or_default()), text(ours), text(theirs))
                else {
                    merged.conflicts.push(rel);
                    continue;
                };
                match diffy::merge(&ancestor, &ours, &new) {
                    Ok(clean) => clean.into_bytes(),
                    Err(with_markers) => {
                        merged.conflicts.push(rel.clone());
                        with_markers.into_bytes()
                    }
                }
            }
        };
        let path = base.join(&rel);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(path, content)?;
        merged.updated += 1;
    }
    Ok(merged)
}

/// The files under `root/rel`, relative to `root`, outside [`NOT_COPIED`] and [`NOT_MERGED`].
fn files_under(root: &Path, rel: &Path) -> std::io::Result<Vec<PathBuf>> {
    let mut files = vec![];
    for entry in fs::read_dir(root.join(rel))? {
        let entry = entry?;
        let path = rel.join(entry.file_name());
        if entry.file_type()?.is_dir() {
            let name = entry.file_name();
            if name == NOT_MERGED || NOT_COPIED.iter().any(|d| name == *d) {
                continue;
            }
            files.extend(files_under(root, &path)?);
        } else {
            files.push(path);
        }
    }
    Ok(files)
}

/// The migration that adds `fields` to the entity's table. A required column gets a `DEFAULT` for
/// the rows that already exist, dropped right after: a fresh `CREATE TABLE` has none.
pub fn add_columns_sql(snake: &str, fields: &[Field]) -> String {
    let table = pluralize(snake);
    let initial = initial_values(fields);
    let mut sql = String::new();
    if !initial.is_empty() {
        sql.push_str(&format!(
            "-- Las filas que ya existen reciben: {}.\n-- Si no es lo que quieres, cámbialo aquí \
             antes de aplicarla: después, cada fila conserva su valor.\n\n",
            initial.join(", ")
        ));
    }
    for field in fields {
        if is_vec_reference(field) {
            // A set: the existing rows start with none.
            sql.push_str(join_table_sql(snake, field).trim_start());
            continue;
        }
        for column in columns(field) {
            let ddl = sql_ddl_col(&column.name, &column.field_type);
            let ddl = ddl.trim_start();
            match (initial_value(field, &column), field.references.as_deref()) {
                (_, Some(target)) => {
                    // Only an optional reference gets here (`check_new_fields`).
                    sql.push_str(&format!(
                        "ALTER TABLE {table} ADD COLUMN {ddl} CONSTRAINT {} REFERENCES {} (id);\n\
                         CREATE INDEX {table}_{name}_idx ON {table} ({name});\n",
                        foreign_key_name(&table, &column.name),
                        pluralize(&pascal_to_snake(target)),
                        name = column.name,
                    ));
                }
                (Some(value), None) => sql.push_str(&format!(
                    "ALTER TABLE {table} ADD COLUMN {ddl} DEFAULT {value};\n\
                     ALTER TABLE {table} ALTER COLUMN {} DROP DEFAULT;\n",
                    column.name
                )),
                (None, None) => sql.push_str(&format!("ALTER TABLE {table} ADD COLUMN {ddl};\n")),
            }
        }
    }
    sql
}

/// `columna = valor` for each required column `fields` add.
fn initial_values(fields: &[Field]) -> Vec<String> {
    fields
        .iter()
        .filter(|f| !is_vec_reference(f) && !is_reference(f))
        .flat_map(|f| {
            columns(f)
                .into_iter()
                .filter_map(move |c| initial_value(f, &c).map(|v| format!("{} = {v}", c.name)))
        })
        .collect()
}

/// What the rows that already exist get in `column` of `field` (decided with Sergio, 2026-11-26): a
/// zero of its type. `None` for a nullable column, and for an array or `JSONB` one, whose `'{}'`
/// default is already in its type (as in a `CREATE TABLE`). A value object whose `new` rejects the
/// zero — the row could no longer be read — gets the valid value its tests use instead.
fn initial_value(field: &Field, column: &Field) -> Option<String> {
    let ty = column.field_type.as_str();
    if ty.starts_with("Option<") || ty.starts_with("Vec<") || ty.starts_with("HashMap<") {
        return None;
    }
    let quoted = |text: &str| format!("'{}'", text.replace('\'', "''"));
    if is_enum_vo(field) {
        return field
            .enum_variants
            .as_ref()
            .and_then(|variants| variants.first())
            .map(|first| quoted(first));
    }
    // A composite rejects an empty required part; a plain value object, an empty string.
    let validated = is_composite_vo(field) || field.value_object.is_some();
    match ty {
        "String" if validated => Some(quoted(example_of(field).unwrap_or("example"))),
        "String" => Some(quoted("")),
        "i64" | "f64" => Some(
            example_of(field)
                .filter(|_| field.value_object.is_some())
                .unwrap_or("0")
                .to_string(),
        ),
        "bool" => Some("FALSE".to_string()),
        "Uuid" => Some(quoted("00000000-0000-0000-0000-000000000000")),
        "DateTime<Utc>" => Some("NOW()".to_string()),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::generators::naming::write_file;
    use crate::puerto_toml::parse_field_arg;

    fn field(arg: &str) -> Field {
        parse_field_arg(arg).unwrap()
    }

    #[test]
    fn should_give_existing_rows_a_zero_and_drop_the_default_for_a_required_column() {
        // Act
        let sql = add_columns_sql("producto", &[field("stock:i64")]);

        // Assert
        assert!(
            sql.contains("ALTER TABLE productos ADD COLUMN stock BIGINT NOT NULL DEFAULT 0;"),
            "{sql}"
        );
        assert!(
            sql.contains("ALTER TABLE productos ALTER COLUMN stock DROP DEFAULT;"),
            "{sql}"
        );
        assert!(
            sql.starts_with("-- Las filas que ya existen reciben: stock = 0.\n"),
            "{sql}"
        );
    }

    #[test]
    fn should_add_an_optional_column_as_null_without_a_default() {
        // Act
        let sql = add_columns_sql("producto", &[field("nota:opt:String")]);

        // Assert
        assert_eq!(sql, "ALTER TABLE productos ADD COLUMN nota TEXT;\n");
    }

    #[test]
    fn should_give_each_type_its_zero() {
        for (arg, value) in [
            ("nombre:String", "''"),
            ("precio:f64", "0"),
            ("activo:bool", "FALSE"),
            ("externo:Uuid", "'00000000-0000-0000-0000-000000000000'"),
            ("visto:DateTime", "NOW()"),
        ] {
            // Act
            let f = field(arg);
            let sql = add_columns_sql("producto", std::slice::from_ref(&f));

            // Assert
            assert!(
                sql.contains(&format!(
                    "{} DEFAULT {value};",
                    sql_ddl_col(&f.name, &f.field_type).trim_start()
                )),
                "{arg}: {sql}"
            );
        }
    }

    #[test]
    fn should_give_a_value_object_a_value_its_new_accepts() {
        // An empty string would make every existing row unreadable: `Nombre::new("")` rejects it.
        for (arg, value) in [
            ("titulo:Titulo:String", "'example'"),
            ("estado:Estado:enum:Borrador/Publicado", "'Borrador'"),
            ("contacto:Contacto:email", "'ana@ejemplo.es'"),
            ("precio:Precio:dinero", "0"),
        ] {
            // Act
            let sql = add_columns_sql("producto", &[field(arg)]);

            // Assert
            assert!(sql.contains(&format!("DEFAULT {value};")), "{arg}: {sql}");
        }
    }

    #[test]
    fn should_keep_the_array_default_of_its_type() {
        // Act
        let sql = add_columns_sql("producto", &[field("etiquetas:vec:String")]);

        // Assert
        assert_eq!(
            sql,
            "ALTER TABLE productos ADD COLUMN etiquetas TEXT[] NOT NULL DEFAULT '{}';\n"
        );
    }

    #[test]
    fn should_add_an_optional_reference_with_its_foreign_key_and_index() {
        // Act
        let sql = add_columns_sql("pedido", &[field("revisor_id:ref:opt:Cliente")]);

        // Assert
        assert!(
            sql.contains(
                "ALTER TABLE pedidos ADD COLUMN revisor_id UUID CONSTRAINT pedidos_revisor_id_fkey \
                 REFERENCES clientes (id);"
            ),
            "{sql}"
        );
        assert!(
            sql.contains("CREATE INDEX pedidos_revisor_id_idx ON pedidos (revisor_id);"),
            "{sql}"
        );
    }

    #[test]
    fn should_add_a_set_as_its_join_table() {
        // Act
        let sql = add_columns_sql("pedido", &[field("etiquetas:vec:ref:Etiqueta")]);

        // Assert
        assert!(sql.starts_with("CREATE TABLE pedidos_etiquetas ("), "{sql}");
        assert!(!sql.contains("ALTER TABLE"), "{sql}");
    }

    #[test]
    fn should_refuse_a_unique_field_and_a_required_reference_with_a_database() {
        // Act / Assert
        assert!(
            check_new_fields(&[field("sku:String!")], false)
                .unwrap_err()
                .contains("único")
        );
        assert!(
            check_new_fields(&[field("cliente_id:ref:Cliente")], true)
                .unwrap_err()
                .contains("ref:opt:")
        );
        assert!(check_new_fields(&[field("cliente_id:ref:Cliente")], false).is_ok());
        assert!(check_new_fields(&[field("cliente_id:ref:opt:Cliente")], true).is_ok());
    }

    fn tree(files: &[(&str, &str)]) -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        for (path, content) in files {
            write_file(&dir.path().join(path), content).unwrap();
        }
        dir
    }

    #[test]
    fn should_write_the_new_file_where_nothing_was_changed_by_hand() {
        // Arrange
        let before = tree(&[("a.rs", "uno\ndos\n")]);
        let after = tree(&[("a.rs", "uno\ndos\ntres\n"), ("nuevo.rs", "x\n")]);
        let project = tree(&[("a.rs", "uno\ndos\n")]);

        // Act
        let merged = merge_into(project.path(), before.path(), after.path()).unwrap();

        // Assert
        assert_eq!(merged.updated, 2);
        assert!(merged.conflicts.is_empty());
        assert_eq!(
            fs::read_to_string(project.path().join("a.rs")).unwrap(),
            "uno\ndos\ntres\n"
        );
        assert_eq!(
            fs::read_to_string(project.path().join("nuevo.rs")).unwrap(),
            "x\n"
        );
    }

    #[test]
    fn should_keep_a_hand_edit_away_from_the_new_lines() {
        // Arrange
        let before = tree(&[("a.rs", "uno\ndos\ntres\ncuatro\ncinco\n")]);
        let after = tree(&[("a.rs", "uno\ndos\ntres\ncuatro\ncinco\nseis\n")]);
        let project = tree(&[("a.rs", "UNO a mano\ndos\ntres\ncuatro\ncinco\n")]);

        // Act
        let merged = merge_into(project.path(), before.path(), after.path()).unwrap();

        // Assert
        assert!(merged.conflicts.is_empty());
        assert_eq!(
            fs::read_to_string(project.path().join("a.rs")).unwrap(),
            "UNO a mano\ndos\ntres\ncuatro\ncinco\nseis\n"
        );
    }

    #[test]
    fn should_leave_conflict_markers_where_the_new_lines_meet_a_hand_edit() {
        // Arrange
        let before = tree(&[("a.rs", "uno\ndos\n")]);
        let after = tree(&[("a.rs", "uno\ndos generado\n")]);
        let project = tree(&[("a.rs", "uno\ndos a mano\n")]);

        // Act
        let merged = merge_into(project.path(), before.path(), after.path()).unwrap();

        // Assert
        assert_eq!(merged.conflicts, [PathBuf::from("a.rs")]);
        let content = fs::read_to_string(project.path().join("a.rs")).unwrap();
        assert!(content.contains("<<<<<<<"), "{content}");
        assert!(
            content.contains("dos a mano") && content.contains("dos generado"),
            "{content}"
        );
    }

    #[test]
    fn should_not_bring_back_a_file_deleted_by_hand() {
        // Arrange
        let before = tree(&[("a.rs", "uno\n")]);
        let after = tree(&[("a.rs", "uno\ndos\n")]);
        let project = tree(&[("otro.rs", "x\n")]);

        // Act
        merge_into(project.path(), before.path(), after.path()).unwrap();

        // Assert
        assert!(!project.path().join("a.rs").exists());
    }

    #[cfg(unix)]
    #[test]
    fn should_copy_neither_links_nor_the_devenv_state() {
        // Arrange
        let project = tempfile::tempdir().unwrap();
        let elsewhere = tempfile::tempdir().unwrap();
        write_file(&project.path().join("src/lib.rs"), "").unwrap();
        write_file(&project.path().join(".devenv/state/x"), "").unwrap();
        write_file(&project.path().join(".direnv/x"), "").unwrap();
        write_file(&elsewhere.path().join("f"), "").unwrap();
        std::os::unix::fs::symlink(elsewhere.path(), project.path().join("dir")).unwrap();
        std::os::unix::fs::symlink(elsewhere.path().join("f"), project.path().join("f")).unwrap();
        let copy = tempfile::tempdir().unwrap();

        // Act
        copy_project(project.path(), copy.path()).unwrap();

        // Assert
        assert!(copy.path().join("src/lib.rs").exists());
        for skipped in [".devenv", ".direnv", "dir", "f"] {
            assert!(!copy.path().join(skipped).exists(), "{skipped}");
        }
    }

    #[test]
    fn should_say_which_path_it_could_not_copy() {
        // Act
        let err = copy_project(Path::new("/no/existe"), Path::new("/tampoco"))
            .unwrap_err()
            .to_string();

        // Assert
        assert!(err.starts_with("no se puede copiar /no/existe: "), "{err}");
    }
}