migrate 0.5.1

Generic file migration tool for applying ordered transformations to a project directory
Documentation
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
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use std::process::Command;

fn get_binary_path() -> PathBuf {
    let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    path.push("target/debug/migrate");
    path
}

fn create_temp_dir() -> tempfile::TempDir {
    tempfile::tempdir().expect("Failed to create temp dir")
}

#[test]
fn test_status_no_migrations_dir() {
    let temp_dir = create_temp_dir();
    let output = Command::new(get_binary_path())
        .args(["--root", temp_dir.path().to_str().unwrap(), "status"])
        .output()
        .expect("Failed to execute command");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("No migrations directory found"));
}

#[test]
fn test_status_empty_migrations_dir() {
    let temp_dir = create_temp_dir();
    let migrations_dir = temp_dir.path().join("migrations");
    fs::create_dir(&migrations_dir).unwrap();

    let output = Command::new(get_binary_path())
        .args(["--root", temp_dir.path().to_str().unwrap(), "status"])
        .output()
        .expect("Failed to execute command");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("No migrations found"));
}

#[test]
fn test_create_bash_migration() {
    let temp_dir = create_temp_dir();
    let migrations_dir = temp_dir.path().join("migrations");

    let output = Command::new(get_binary_path())
        .args([
            "--root",
            temp_dir.path().to_str().unwrap(),
            "create",
            "test-migration",
        ])
        .output()
        .expect("Failed to execute command");

    assert!(output.status.success());

    // Find the created migration file (version is time-based, so we search for pattern)
    let files: Vec<_> = fs::read_dir(&migrations_dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("-test-migration.sh")
        })
        .collect();
    assert_eq!(files.len(), 1, "Migration file should be created");

    let migration_file = files[0].path();

    // Verify filename format: 5 alphanumeric chars + dash + name + extension
    let filename = migration_file.file_name().unwrap().to_string_lossy();
    assert!(
        filename.len() > 6 && filename.chars().take(5).all(|c| c.is_ascii_alphanumeric()),
        "Filename should start with 5-char version: {}",
        filename
    );

    // Check file is executable
    let perms = fs::metadata(&migration_file).unwrap().permissions();
    assert!(perms.mode() & 0o111 != 0, "File should be executable");

    // Check content has shebang
    let content = fs::read_to_string(&migration_file).unwrap();
    assert!(content.starts_with("#!/usr/bin/env bash"));
}

#[test]
fn test_create_typescript_migration() {
    let temp_dir = create_temp_dir();
    let migrations_dir = temp_dir.path().join("migrations");

    let output = Command::new(get_binary_path())
        .args([
            "--root",
            temp_dir.path().to_str().unwrap(),
            "create",
            "ts-migration",
            "--template",
            "ts",
        ])
        .output()
        .expect("Failed to execute command");

    assert!(output.status.success());

    // Find the created migration file
    let files: Vec<_> = fs::read_dir(&migrations_dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("-ts-migration.ts")
        })
        .collect();
    assert_eq!(files.len(), 1, "Migration file should be created");

    let migration_file = files[0].path();
    let content = fs::read_to_string(&migration_file).unwrap();
    assert!(content.starts_with("#!/usr/bin/env -S npx tsx"));
}

#[test]
fn test_create_detects_version_collision() {
    let temp_dir = create_temp_dir();
    let migrations_dir = temp_dir.path().join("migrations");
    fs::create_dir(&migrations_dir).unwrap();

    // Create first migration via CLI
    let output1 = Command::new(get_binary_path())
        .args([
            "--root",
            temp_dir.path().to_str().unwrap(),
            "create",
            "first",
        ])
        .output()
        .expect("Failed to execute command");
    assert!(output1.status.success());

    // Creating second migration immediately should either succeed (different 10-min slot)
    // or fail with version collision message
    let output2 = Command::new(get_binary_path())
        .args([
            "--root",
            temp_dir.path().to_str().unwrap(),
            "create",
            "second",
        ])
        .output()
        .expect("Failed to execute command");

    // If it failed, it should be due to version collision
    if !output2.status.success() {
        let stderr = String::from_utf8_lossy(&output2.stderr);
        assert!(
            stderr.contains("already exists"),
            "Should fail with version collision: {}",
            stderr
        );
    }
}

#[test]
fn test_list_templates() {
    let temp_dir = create_temp_dir();

    let output = Command::new(get_binary_path())
        .args([
            "--root",
            temp_dir.path().to_str().unwrap(),
            "create",
            "dummy",
            "--list-templates",
        ])
        .output()
        .expect("Failed to execute command");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("bash"));
    assert!(stdout.contains("ts"));
    assert!(stdout.contains("python"));
    assert!(stdout.contains("node"));
    assert!(stdout.contains("ruby"));
}

#[test]
fn test_up_applies_migrations() {
    let temp_dir = create_temp_dir();
    let migrations_dir = temp_dir.path().join("migrations");
    fs::create_dir(&migrations_dir).unwrap();

    // Create a simple migration with new 5-char version format
    let migration = migrations_dir.join("00001-create-file.sh");
    fs::write(
        &migration,
        r#"#!/usr/bin/env bash
set -euo pipefail
touch "$MIGRATE_PROJECT_ROOT/created-by-migration.txt"
"#,
    )
    .unwrap();

    // Make executable
    let mut perms = fs::metadata(&migration).unwrap().permissions();
    perms.set_mode(0o755);
    fs::set_permissions(&migration, perms).unwrap();

    // Run migrations
    let output = Command::new(get_binary_path())
        .args(["--root", temp_dir.path().to_str().unwrap(), "up"])
        .output()
        .expect("Failed to execute command");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "Migration should succeed: stdout={}, stderr={}",
        stdout,
        stderr
    );

    // Check file was created
    assert!(
        temp_dir.path().join("created-by-migration.txt").exists(),
        "Migration should have created the file"
    );

    // Check history file
    let history = migrations_dir.join("history");
    assert!(history.exists(), "History file should be created");

    let history_content = fs::read_to_string(&history).unwrap();
    assert!(history_content.contains("00001-create-file"));
}

#[test]
fn test_up_dry_run() {
    let temp_dir = create_temp_dir();
    let migrations_dir = temp_dir.path().join("migrations");
    fs::create_dir(&migrations_dir).unwrap();

    // Create a migration with 5-char version format
    let migration = migrations_dir.join("00001-create-file.sh");
    fs::write(
        &migration,
        r#"#!/usr/bin/env bash
touch "$MIGRATE_PROJECT_ROOT/should-not-exist.txt"
"#,
    )
    .unwrap();

    let mut perms = fs::metadata(&migration).unwrap().permissions();
    perms.set_mode(0o755);
    fs::set_permissions(&migration, perms).unwrap();

    // Run with --dry-run
    let output = Command::new(get_binary_path())
        .args([
            "--root",
            temp_dir.path().to_str().unwrap(),
            "up",
            "--dry-run",
        ])
        .output()
        .expect("Failed to execute command");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("dry run"));

    // File should NOT be created
    assert!(
        !temp_dir.path().join("should-not-exist.txt").exists(),
        "Dry run should not execute migration"
    );

    // History should NOT be updated
    assert!(
        !migrations_dir.join("history").exists(),
        "Dry run should not update history"
    );
}

#[test]
fn test_failed_migration_stops_execution() {
    let temp_dir = create_temp_dir();
    let migrations_dir = temp_dir.path().join("migrations");
    fs::create_dir(&migrations_dir).unwrap();

    // First migration succeeds (version 00001)
    let first = migrations_dir.join("00001-success.sh");
    fs::write(
        &first,
        r#"#!/usr/bin/env bash
touch "$MIGRATE_PROJECT_ROOT/first.txt"
"#,
    )
    .unwrap();
    let mut perms = fs::metadata(&first).unwrap().permissions();
    perms.set_mode(0o755);
    fs::set_permissions(&first, perms).unwrap();

    // Second migration fails (version 00002)
    let second = migrations_dir.join("00002-fail.sh");
    fs::write(
        &second,
        r#"#!/usr/bin/env bash
exit 1
"#,
    )
    .unwrap();
    let mut perms = fs::metadata(&second).unwrap().permissions();
    perms.set_mode(0o755);
    fs::set_permissions(&second, perms).unwrap();

    // Third migration should not run (version 00003)
    let third = migrations_dir.join("00003-never.sh");
    fs::write(
        &third,
        r#"#!/usr/bin/env bash
touch "$MIGRATE_PROJECT_ROOT/third.txt"
"#,
    )
    .unwrap();
    let mut perms = fs::metadata(&third).unwrap().permissions();
    perms.set_mode(0o755);
    fs::set_permissions(&third, perms).unwrap();

    // Run migrations
    let output = Command::new(get_binary_path())
        .args(["--root", temp_dir.path().to_str().unwrap(), "up"])
        .output()
        .expect("Failed to execute command");

    // Should fail
    assert!(!output.status.success());

    // First file should exist
    assert!(temp_dir.path().join("first.txt").exists());

    // Third file should NOT exist
    assert!(!temp_dir.path().join("third.txt").exists());

    // History should only contain first migration
    let history = fs::read_to_string(migrations_dir.join("history")).unwrap();
    assert!(history.contains("00001-success"));
    assert!(!history.contains("00002-fail"));
}

#[test]
fn test_status_shows_applied_and_pending() {
    let temp_dir = create_temp_dir();
    let migrations_dir = temp_dir.path().join("migrations");
    fs::create_dir(&migrations_dir).unwrap();

    // Create migrations with 5-char version format
    let first = migrations_dir.join("00001-first.sh");
    fs::write(&first, "#!/usr/bin/env bash\necho first").unwrap();
    let mut perms = fs::metadata(&first).unwrap().permissions();
    perms.set_mode(0o755);
    fs::set_permissions(&first, perms).unwrap();

    let second = migrations_dir.join("00002-second.sh");
    fs::write(&second, "#!/usr/bin/env bash\necho second").unwrap();
    let mut perms = fs::metadata(&second).unwrap().permissions();
    perms.set_mode(0o755);
    fs::set_permissions(&second, perms).unwrap();

    // Write history for first migration only
    fs::write(
        migrations_dir.join("history"),
        "00001-first 2024-01-01T00:00:00+00:00\n",
    )
    .unwrap();

    // Check status
    let output = Command::new(get_binary_path())
        .args(["--root", temp_dir.path().to_str().unwrap(), "status"])
        .output()
        .expect("Failed to execute command");

    let stdout = String::from_utf8_lossy(&output.stdout);
    // Check for version summary line
    assert!(
        stdout.contains("Version:"),
        "Should show version line: {}",
        stdout
    );
    assert!(stdout.contains("Applied (1)"));
    assert!(stdout.contains("00001-first"));
    assert!(stdout.contains("Pending (1)"));
    assert!(stdout.contains("00002-second"));
}

#[test]
fn test_up_baseline_cleans_stale_migrations() {
    let temp_dir = create_temp_dir();
    let migrations_dir = temp_dir.path().join("migrations");
    fs::create_dir(&migrations_dir).unwrap();

    // Create a migration and apply it with --baseline
    let migration = migrations_dir.join("00001-init.sh");
    fs::write(
        &migration,
        "#!/usr/bin/env bash\nset -euo pipefail\necho init\n",
    )
    .unwrap();
    let mut perms = fs::metadata(&migration).unwrap().permissions();
    perms.set_mode(0o755);
    fs::set_permissions(&migration, perms).unwrap();

    let output = Command::new(get_binary_path())
        .args([
            "--root",
            temp_dir.path().to_str().unwrap(),
            "up",
            "--baseline",
        ])
        .output()
        .expect("Failed to execute command");
    assert!(output.status.success());

    // Migration file should be deleted by baseline
    assert!(
        !migrations_dir.join("00001-init.sh").exists(),
        "Migration file should have been deleted by baseline"
    );

    // Now simulate the old migration file reappearing (e.g., git merge)
    let reappeared = migrations_dir.join("00001-init.sh");
    fs::write(
        &reappeared,
        "#!/usr/bin/env bash\nset -euo pipefail\necho init\n",
    )
    .unwrap();
    let mut perms = fs::metadata(&reappeared).unwrap().permissions();
    perms.set_mode(0o755);
    fs::set_permissions(&reappeared, perms).unwrap();

    assert!(
        migrations_dir.join("00001-init.sh").exists(),
        "Migration file should exist again after simulated reappearance"
    );

    // Run up --baseline again. No migrations should be applied, but the stale
    // file should be cleaned up.
    let output = Command::new(get_binary_path())
        .args([
            "--root",
            temp_dir.path().to_str().unwrap(),
            "up",
            "--baseline",
        ])
        .output()
        .expect("Failed to execute command");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(output.status.success(), "Should succeed: {}", stdout);
    assert!(
        stdout.contains("No pending migrations"),
        "Should report no pending migrations: {}",
        stdout
    );
    assert!(
        stdout.contains("stale migration"),
        "Should report cleaning stale migrations: {}",
        stdout
    );

    // The reappeared migration file should be deleted
    assert!(
        !migrations_dir.join("00001-init.sh").exists(),
        "Stale migration file should have been cleaned up"
    );
}