forgex 0.9.0

CLI and runtime for the Forge full-stack 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
use anyhow::Result;
use clap::Parser;
use console::style;
use std::net::TcpListener;
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;
use tokio::process::Command;

use super::frontend_target::FrontendTarget;
use super::ui;

/// Run project tests (backend unit tests and frontend Playwright tests).
///
/// Builds the project with an embedded frontend, starts a PostgreSQL
/// container, runs the binary on a random port, and executes Playwright
/// tests against the single-origin server.
#[derive(Parser)]
pub struct TestCommand {
    /// Skip backend unit tests
    #[arg(long)]
    pub skip_backend: bool,

    /// Skip frontend Playwright tests
    #[arg(long)]
    pub skip_frontend: bool,

    /// Run Playwright in interactive UI mode
    #[arg(long)]
    pub ui: bool,

    /// Run tests in a visible browser window
    #[arg(long)]
    pub headed: bool,

    /// Extra arguments passed through to the test runner
    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
    pub args: Vec<String>,
}

impl TestCommand {
    pub async fn execute(self) -> Result<()> {
        if !Path::new("forge.toml").exists() {
            anyhow::bail!(
                "Not a FORGE project (forge.toml not found).\n\n\
                To create a new project:\n  forge new my-app --template with-svelte/minimal"
            );
        }

        ui::section("FORGE Test");

        let mut any_failed = false;

        if !self.skip_backend && !self.run_backend_tests().await? {
            any_failed = true;
        }

        if !self.skip_frontend {
            let result = self.run_frontend_tests().await;
            match result {
                Ok(passed) => {
                    if !passed {
                        any_failed = true;
                    }
                }
                Err(e) => return Err(e),
            }
        }

        println!();
        if any_failed {
            println!("{} Some tests failed.", ui::error());
            std::process::exit(1);
        } else {
            println!("{} All tests passed.", ui::ok());
        }

        Ok(())
    }

    async fn run_backend_tests(&self) -> Result<bool> {
        println!();
        println!("  {} {}", ui::step(), style("Backend Tests").bold());

        let mut cargo_args = vec!["test"];

        if self.skip_frontend {
            for arg in &self.args {
                cargo_args.push(arg);
            }
        }

        println!("  {} Running: cargo {}", ui::step(), cargo_args.join(" "));
        println!();

        let status = Command::new("cargo")
            .args(&cargo_args)
            .stdin(Stdio::inherit())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .status()
            .await?;

        if status.success() {
            println!();
            println!("  {} Backend tests passed.", ui::ok());
            Ok(true)
        } else {
            println!();
            println!("  {} Backend tests failed.", ui::error());
            Ok(false)
        }
    }

    async fn run_frontend_tests(&self) -> Result<bool> {
        let frontend_dir = Path::new("frontend");
        if !frontend_dir.exists() {
            println!();
            println!(
                "  {} No frontend/ directory, skipping frontend tests.",
                ui::info()
            );
            return Ok(true);
        }

        let tests_dir = frontend_dir.join("tests");
        if !tests_dir.exists() {
            println!();
            println!(
                "  {} No frontend/tests/ directory, skipping frontend tests.",
                ui::info()
            );
            return Ok(true);
        }

        println!();
        println!("  {} {}", ui::step(), style("Frontend Tests").bold());

        // If FORGE_TEST_URL is already set (CI or manual), skip build/start
        if let Some(url) = std::env::var("FORGE_TEST_URL")
            .ok()
            .filter(|v| !v.trim().is_empty())
        {
            print!("  {} Checking server...", ui::step());
            if wait_for_health(&url, Duration::from_secs(60)).await {
                println!(" {}", style("ready").green());
            } else {
                println!(" {}", style("not reachable").red());
                anyhow::bail!("FORGE_TEST_URL={url} is set but server is not reachable");
            }
            return self.execute_frontend_tests(frontend_dir, &url).await;
        }

        // Compiled test flow: build, start PG, run binary, test, cleanup
        if !check_docker_available().await {
            anyhow::bail!(
                "Docker is required for running frontend tests.\n\n\
                Install Docker or set FORGE_TEST_URL to point to a running server."
            );
        }

        let frontend_type = FrontendTarget::detect(frontend_dir);

        // Start PostgreSQL container
        let db_name = read_db_name();
        println!("  {} Starting PostgreSQL...", ui::step());
        let (pg_container, pg_port) = start_postgres(&db_name).await?;
        let db_url = format!("postgres://postgres:forge@localhost:{pg_port}/{db_name}");

        // Build project with embedded frontend
        let binary = match build_project(frontend_type).await {
            Ok(bin) => bin,
            Err(e) => {
                stop_postgres(&pg_container).await;
                return Err(e);
            }
        };

        // Pick random port and start the server
        let port = pick_random_port()?;
        let app_url = format!("http://localhost:{port}");

        println!("  {} Starting server on port {port}...", ui::step());
        let mut child = match start_server(&binary, port, &db_url).await {
            Ok(child) => child,
            Err(e) => {
                stop_postgres(&pg_container).await;
                return Err(e);
            }
        };

        // Wait for the server to become healthy
        print!("  {} Waiting for server...", ui::step());
        if !wait_for_health(&app_url, Duration::from_secs(120)).await {
            println!(" {}", style("timed out").red());
            let _ = child.kill().await;
            stop_postgres(&pg_container).await;
            anyhow::bail!(
                "Server did not become healthy within 120s.\n\
                Check the binary output for errors."
            );
        }
        println!(" {}", style("ready").green());

        // Run tests
        let result = self.execute_frontend_tests(frontend_dir, &app_url).await;

        // Cleanup
        println!();
        println!("  {} Stopping server...", ui::step());
        let _ = child.kill().await;
        stop_postgres(&pg_container).await;

        result
    }

    async fn execute_frontend_tests(&self, frontend_dir: &Path, app_url: &str) -> Result<bool> {
        // Install dependencies if needed
        if !frontend_dir.join("node_modules").exists() {
            println!("  {} Installing frontend dependencies...", ui::step());
            let status = Command::new("bun")
                .args(["install"])
                .current_dir(frontend_dir)
                .stdout(Stdio::inherit())
                .stderr(Stdio::inherit())
                .status()
                .await?;

            if !status.success() {
                anyhow::bail!("Failed to install frontend dependencies");
            }
        }

        // Check Playwright browsers are installed
        let pw_check = Command::new("bunx")
            .args(["playwright", "test", "--list"])
            .current_dir(frontend_dir)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .await;

        let needs_install = match pw_check {
            Ok(status) => !status.success(),
            Err(_) => true,
        };

        if needs_install {
            println!("  {} Installing Playwright browsers...", ui::step());
            let status = Command::new("bunx")
                .args(["playwright", "install", "chromium"])
                .current_dir(frontend_dir)
                .stdout(Stdio::inherit())
                .stderr(Stdio::inherit())
                .status()
                .await?;

            if !status.success() {
                anyhow::bail!("Failed to install Playwright browsers");
            }
        }

        // Build Playwright command
        let mut pw_args = vec!["playwright", "test"];

        if self.ui {
            pw_args.push("--ui");
        }

        if self.headed {
            pw_args.push("--headed");
        }

        if self.skip_backend {
            for arg in &self.args {
                pw_args.push(arg);
            }
        }

        println!();
        println!("  {} Running: bunx {}", ui::step(), pw_args.join(" "));
        println!();

        let status = Command::new("bunx")
            .args(&pw_args)
            .current_dir(frontend_dir)
            .env("FORGE_TEST_URL", app_url)
            .stdin(Stdio::inherit())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .status()
            .await?;

        if status.success() {
            println!();
            println!("  {} Frontend tests passed.", ui::ok());
            Ok(true)
        } else {
            println!();
            println!("  {} Frontend tests failed.", ui::error());
            println!(
                "  Debug with: {} or {}",
                style("forge test --skip-backend --ui").cyan(),
                style("forge test --skip-backend --headed").cyan()
            );
            Ok(false)
        }
    }
}

fn read_db_name() -> String {
    read_env_file(Path::new(".env"))
        .into_iter()
        .find(|(k, _)| k == "POSTGRES_DB")
        .map(|(_, v)| v)
        .unwrap_or_else(|| "test_db".to_string())
}

fn pick_random_port() -> Result<u16> {
    let listener = TcpListener::bind("127.0.0.1:0")?;
    let port = listener.local_addr()?.port();
    drop(listener);
    Ok(port)
}

async fn start_postgres(db_name: &str) -> Result<(String, u16)> {
    let container_name = format!(
        "forge-test-pg-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0)
    );

    let _ = Command::new("docker")
        .args(["rm", "-f", &container_name])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .await;

    let status = Command::new("docker")
        .args([
            "run",
            "-d",
            "--name",
            &container_name,
            "-e",
            "POSTGRES_USER=postgres",
            "-e",
            "POSTGRES_PASSWORD=forge",
            "-e",
            &format!("POSTGRES_DB={db_name}"),
            "-p",
            "0:5432",
            "postgres:18",
        ])
        .stdout(Stdio::null())
        .stderr(Stdio::inherit())
        .status()
        .await?;

    if !status.success() {
        anyhow::bail!("Failed to start PostgreSQL container");
    }

    let output = Command::new("docker")
        .args(["port", &container_name, "5432"])
        .output()
        .await?;

    // Output is like "0.0.0.0:12345\n" or "[::]:12345\n"
    let port_str = String::from_utf8_lossy(&output.stdout);
    let port: u16 = port_str
        .trim()
        .rsplit(':')
        .next()
        .and_then(|p| p.parse().ok())
        .ok_or_else(|| anyhow::anyhow!("Could not parse PostgreSQL port from: {port_str}"))?;

    for _ in 0..30 {
        let check = Command::new("docker")
            .args([
                "exec",
                &container_name,
                "pg_isready",
                "-U",
                "postgres",
                "-d",
                db_name,
            ])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .await;

        if matches!(check, Ok(s) if s.success()) {
            return Ok((container_name, port));
        }
        tokio::time::sleep(Duration::from_secs(1)).await;
    }

    let _ = Command::new("docker")
        .args(["rm", "-f", &container_name])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .await;

    anyhow::bail!("PostgreSQL did not become ready within 30s")
}

async fn stop_postgres(container_name: &str) {
    let _ = Command::new("docker")
        .args(["rm", "-f", container_name])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .await;
}

async fn build_project(frontend_type: Option<FrontendTarget>) -> Result<std::path::PathBuf> {
    println!("  {} Building project...", ui::step());

    let frontend_env = Path::new("frontend/.env");

    // For Svelte: SvelteKit reads PUBLIC_API_URL from frontend/.env at build time.
    // Patch it to empty so the frontend uses relative URLs (same-origin serving).
    let original_frontend_env = std::fs::read_to_string(frontend_env).ok();
    if matches!(frontend_type, Some(FrontendTarget::SvelteKit))
        && let Some(ref content) = original_frontend_env
    {
        let patched: String = content
            .lines()
            .map(|l| {
                if l.trim_start().starts_with("PUBLIC_API_URL=") {
                    "PUBLIC_API_URL="
                } else {
                    l
                }
            })
            .collect::<Vec<_>>()
            .join("\n");
        std::fs::write(frontend_env, patched)?;
    }

    // For Dioxus: build WASM first so frontend/dist/ has real files before cargo build.
    // build.rs only creates a placeholder in debug, and rust_embed needs the folder to exist.
    if matches!(frontend_type, Some(FrontendTarget::Dioxus)) {
        println!("  {} Building Dioxus WASM frontend...", ui::step());
        let frontend_dir = Path::new("frontend");
        let status = Command::new("dx")
            .args(["build", "--platform", "web"])
            .current_dir(frontend_dir)
            .env("FORGE_API_URL", "")
            .stdin(Stdio::inherit())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .status()
            .await?;

        if !status.success() {
            anyhow::bail!(
                "Dioxus frontend build failed.\n\
                Make sure dioxus-cli (dx) is installed: cargo install dioxus-cli"
            );
        }

        // dx outputs to target/dx/{name}/{profile}/web/public/; copy to frontend/dist/
        let dx_target = frontend_dir.join("target/dx");
        if let Ok(entries) = std::fs::read_dir(&dx_target) {
            for entry in entries.flatten() {
                for profile in ["debug", "release"] {
                    let public_dir = entry.path().join(profile).join("web/public");
                    if public_dir.exists() {
                        let dist_dir = frontend_dir.join("dist");
                        let _ = std::fs::remove_dir_all(&dist_dir);
                        copy_dir_recursive(&public_dir, &dist_dir)?;
                        break;
                    }
                }
            }
        }
    }

    // Build backend with embedded frontend
    let status = Command::new("cargo")
        .args(["build", "--features", "embedded-frontend"])
        .stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status()
        .await;

    // Restore before checking build result so a failed build doesn't leave a patched .env
    if let Some(content) = original_frontend_env
        && let Err(e) = std::fs::write(frontend_env, content)
    {
        eprintln!("Warning: failed to restore frontend/.env: {e}");
    }

    if !status?.success() {
        anyhow::bail!("cargo build failed");
    }

    find_binary()
}

fn find_binary() -> Result<std::path::PathBuf> {
    // Read package name from Cargo.toml (cargo preserves hyphens for bin names)
    let cargo_toml = std::fs::read_to_string("Cargo.toml")?;
    let name = cargo_toml
        .lines()
        .find(|l| l.starts_with("name"))
        .and_then(|l| l.split('=').nth(1))
        .map(|v| v.trim().trim_matches('"').to_string())
        .ok_or_else(|| anyhow::anyhow!("Could not find package name in Cargo.toml"))?;

    // Workspace members output to the workspace root target/debug/.
    // Find the workspace root by looking for the Cargo.toml with [workspace].
    let mut search_dir = std::env::current_dir()?;
    loop {
        let ws_toml = search_dir.join("Cargo.toml");
        if ws_toml.exists()
            && let Ok(content) = std::fs::read_to_string(&ws_toml)
            && content.contains("[workspace]")
        {
            let candidate = search_dir.join("target/debug").join(&name);
            if candidate.exists() {
                return Ok(candidate);
            }
        }
        if !search_dir.pop() {
            break;
        }
    }

    // Fallback: check local target/debug/
    let local = std::path::PathBuf::from(format!("target/debug/{name}"));
    if local.exists() {
        return Ok(local);
    }

    anyhow::bail!(
        "Built binary not found for package '{name}'.\n\
        Checked workspace and local target/debug/ directories."
    )
}

/// Parse all key=value pairs from a dotenv file.
fn read_env_file(path: &Path) -> Vec<(String, String)> {
    let content = match std::fs::read_to_string(path) {
        Ok(c) => c,
        Err(_) => return Vec::new(),
    };
    content
        .lines()
        .filter_map(|line| {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                return None;
            }
            let (key, value) = line.split_once('=')?;
            Some((key.trim().to_string(), value.trim().to_string()))
        })
        .collect()
}

async fn start_server(binary: &Path, port: u16, db_url: &str) -> Result<tokio::process::Child> {
    let mut cmd = Command::new(binary);

    // Load all vars from .env so secrets, config, and custom vars carry through
    for (key, value) in read_env_file(Path::new(".env")) {
        cmd.env(&key, &value);
    }

    // Override the vars we control for the test environment
    cmd.env("PORT", port.to_string())
        .env("HOST", "0.0.0.0")
        .env("DATABASE_URL", db_url)
        .env("RUST_LOG", "warn")
        .stdout(Stdio::null())
        .stderr(Stdio::inherit());

    let child = cmd.spawn()?;
    Ok(child)
}

async fn wait_for_health(base_url: &str, timeout: Duration) -> bool {
    let health_url = format!("{base_url}/_api/health");
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(2))
        .build()
        .unwrap_or_default();
    let start = std::time::Instant::now();

    while start.elapsed() < timeout {
        if client.get(&health_url).send().await.is_ok() {
            return true;
        }
        tokio::time::sleep(Duration::from_secs(1)).await;
        print!(".");
    }
    false
}

fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
    std::fs::create_dir_all(dst)?;
    for entry in std::fs::read_dir(src)? {
        let entry = entry?;
        let dest_path = dst.join(entry.file_name());
        if entry.file_type()?.is_dir() {
            copy_dir_recursive(&entry.path(), &dest_path)?;
        } else {
            std::fs::copy(entry.path(), dest_path)?;
        }
    }
    Ok(())
}

async fn check_docker_available() -> bool {
    let result = Command::new("docker")
        .args(["info"])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .await;

    matches!(result, Ok(status) if status.success())
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    fn default_cmd() -> TestCommand {
        TestCommand {
            skip_backend: false,
            skip_frontend: false,
            ui: false,
            headed: false,
            args: vec![],
        }
    }

    #[test]
    fn test_command_default_runs_both() {
        let cmd = default_cmd();
        assert!(!cmd.skip_backend);
        assert!(!cmd.skip_frontend);
    }

    #[test]
    fn test_command_skip_backend() {
        let cmd = TestCommand {
            skip_backend: true,
            ..default_cmd()
        };
        assert!(cmd.skip_backend);
        assert!(!cmd.skip_frontend);
    }

    #[test]
    fn test_command_skip_frontend() {
        let cmd = TestCommand {
            skip_frontend: true,
            ..default_cmd()
        };
        assert!(!cmd.skip_backend);
        assert!(cmd.skip_frontend);
    }

    #[test]
    fn test_command_with_ui_and_args() {
        let cmd = TestCommand {
            ui: true,
            args: vec!["tests/todo.spec.ts".into()],
            ..default_cmd()
        };
        assert!(cmd.ui);
        assert_eq!(cmd.args.len(), 1);
    }

    #[test]
    fn test_command_headed() {
        let cmd = TestCommand {
            headed: true,
            ..default_cmd()
        };
        assert!(cmd.headed);
    }

    #[test]
    fn test_read_db_name_default() {
        assert!(!read_db_name().is_empty());
    }

    #[test]
    fn test_pick_random_port() {
        let port1 = pick_random_port().unwrap();
        let port2 = pick_random_port().unwrap();
        assert!(port1 > 0);
        assert!(port2 > 0);
    }
}