px-cli 0.1.13

Phoenix-rs application CLI (px new / make / migrate / dev)
Documentation
use std::{
    env, fs,
    path::{Path, PathBuf},
    process::Command,
    sync::atomic::{AtomicU64, Ordering},
    time::{SystemTime, UNIX_EPOCH},
};

static NEXT_TEMPORARY_DIRECTORY: AtomicU64 = AtomicU64::new(0);

fn temporary_directory() -> PathBuf {
    let id = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("valid clock")
        .as_nanos();
    let sequence = NEXT_TEMPORARY_DIRECTORY.fetch_add(1, Ordering::Relaxed);
    env::temp_dir().join(format!(
        "phoenix-cli-command-{}-{id}-{sequence}",
        std::process::id()
    ))
}

fn run(cwd: &Path, arguments: &[&str]) {
    let status = Command::new(env!("CARGO_BIN_EXE_px"))
        .args(arguments)
        .current_dir(cwd)
        .status()
        .expect("CLI should start");
    assert!(status.success(), "command failed: {arguments:?}");
}

#[test]
fn command_surface_generates_and_registers_every_artifact() {
    let root = temporary_directory();
    fs::create_dir_all(&root).expect("temporary root");
    let framework = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../..")
        .canonicalize()
        .expect("framework root");
    run(
        &root,
        &[
            "new",
            "demo",
            "--framework-path",
            framework.to_str().expect("UTF-8 path"),
            "--database",
            "sqlite",
            "--no-install",
            "--no-git",
        ],
    );
    let project = root.join("demo");

    run(&project, &["make:controller", "Report", "--route"]);
    run(&project, &["make:model", "Post", "--migration"]);
    run(&project, &["make:migration", "add_status_to_posts"]);
    run(&project, &["make:request", "PublishPost"]);
    run(&project, &["make:resource", "PostSummary"]);
    run(&project, &["make:middleware", "RequireLogin"]);
    run(&project, &["make:page", "reports/index"]);
    run(&project, &["make:island", "LikeButton"]);
    run(&project, &["make:command", "Update"]);
    run(&project, &["make:auth"]);

    for path in [
        "app/controllers/report_controller.rs",
        "app/models/post.rs",
        "app/requests/publish_post_request.rs",
        "app/resources/post_summary_resource.rs",
        "app/middleware/require_login_middleware.rs",
        "app/commands/update.rs",
        "routes/reports.rs",
        "views/pages/reports/index.tsx",
        "views/islands/counter.tsx",
        "views/islands/like-button.tsx",
        "views/pages/demo/spa.tsx",
        "views/pages/demo/ssr.tsx",
        "views/pages/demo/islands.tsx",
        "routes/auth.rs",
        "app/controllers/auth_controller.rs",
        "app/requests/login_input.rs",
        "views/pages/auth/login.tsx",
        "views/pages/auth/register.tsx",
        "views/pages/auth/forgot-password.tsx",
    ] {
        assert!(project.join(path).is_file(), "missing {path}");
    }
    let auth_routes = fs::read_to_string(project.join("routes/auth.rs")).expect("auth routes");
    assert!(auth_routes.contains(".name(\"login.store\")"));
    assert!(auth_routes.contains(".action::<LoginInput, AuthSessionResource>()"));
    let commands = fs::read_to_string(project.join("app/commands/mod.rs")).expect("commands");
    assert!(commands.contains("pub mod update;"));
    assert!(commands.contains("update,"));
    let main = fs::read_to_string(project.join("src/main.rs")).expect("main");
    assert!(main.contains("Console::new"));
    assert!(main.contains("commands::registry()"));
    // Three migrations are registered by this command surface: the model's own
    // table, the standalone `make:migration`, and the users table `make:auth`
    // brings with it.
    let migrations =
        fs::read_to_string(project.join("database/migrations/mod.rs")).expect("migration registry");
    assert_eq!(
        migrations.matches("phoenix:migration:").count(),
        3,
        "registry:\n{migrations}"
    );
    for expected in [
        "create_posts_table",
        "add_status_to_posts",
        "create_users_table",
    ] {
        assert!(migrations.contains(expected), "{expected} is registered");
    }
    fs::remove_dir_all(root).expect("remove temporary project");
}

#[cfg(unix)]
#[test]
fn database_commands_dispatch_to_the_project_management_binary() {
    use std::os::unix::fs::PermissionsExt;

    let root = temporary_directory();
    fs::create_dir_all(&root).expect("temporary root");
    let framework = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../..")
        .canonicalize()
        .expect("framework root");
    run(
        &root,
        &[
            "new",
            "demo",
            "--framework-path",
            framework.to_str().expect("UTF-8 path"),
            "--database",
            "sqlite",
            "--no-install",
            "--no-git",
        ],
    );
    let project = root.join("demo");
    let capture = root.join("cargo-invocations.txt");
    let fake_cargo = root.join("cargo");
    fs::write(
        &fake_cargo,
        "#!/bin/sh\nprintf '%s' \"$PWD\" >> \"$PX_CAPTURE\"\nfor argument in \"$@\"; do printf '\\t%s' \"$argument\" >> \"$PX_CAPTURE\"; done\nprintf '\\n' >> \"$PX_CAPTURE\"\n",
    )
    .expect("fake cargo");
    let mut permissions = fs::metadata(&fake_cargo)
        .expect("fake cargo metadata")
        .permissions();
    permissions.set_mode(0o755);
    fs::set_permissions(&fake_cargo, permissions).expect("make fake cargo executable");

    for arguments in [
        vec!["status"],
        vec!["migrate"],
        vec!["rollback", "--step", "3"],
        vec!["fresh", "--seed"],
        vec!["seed"],
    ] {
        let status = Command::new(env!("CARGO_BIN_EXE_px"))
            .args(&arguments)
            .current_dir(&project)
            .env("CARGO", &fake_cargo)
            .env("PX_CAPTURE", &capture)
            .status()
            .expect("CLI should start");
        assert!(status.success(), "command failed: {arguments:?}");
    }

    let project = project.canonicalize().expect("canonical project path");
    let invocations = fs::read_to_string(&capture).expect("captured cargo invocations");
    // `seed` is the one command that needs the project's `factory` feature:
    // without it the factories compile away and seeding inserts nothing while
    // reporting success.
    let expected = [
        ("status", ""),
        ("migrate", ""),
        ("rollback\t3", ""),
        ("fresh\t--seed", ""),
        ("seed", "--features\tfactory\t"),
    ];
    for (line, (command, features)) in invocations.lines().zip(expected) {
        assert_eq!(
            line,
            format!(
                "{}\trun\t--quiet\t--bin\tphoenix-manage\t{features}--\t{command}",
                project.display()
            )
        );
    }
    assert_eq!(invocations.lines().count(), expected.len());

    // A project generated before factories existed has no such feature, and
    // passing an unknown one to Cargo is a hard error — so `px seed` must fall
    // back to the plain invocation rather than break for them.
    let manifest_path = project.join("Cargo.toml");
    let manifest = fs::read_to_string(&manifest_path).expect("manifest");
    fs::write(
        &manifest_path,
        manifest.replace("factory = [\"phoenix/factory\"]", ""),
    )
    .expect("rewrite manifest");
    fs::write(&capture, "").expect("reset capture");
    let status = Command::new(env!("CARGO_BIN_EXE_px"))
        .args(["seed"])
        .current_dir(&project)
        .env("CARGO", &fake_cargo)
        .env("PX_CAPTURE", &capture)
        .status()
        .expect("CLI should start");
    assert!(status.success());
    let invocations = fs::read_to_string(&capture).expect("captured cargo invocations");
    assert_eq!(
        invocations.trim_end(),
        format!(
            "{}\trun\t--quiet\t--bin\tphoenix-manage\t--\tseed",
            project.display()
        )
    );
    fs::remove_dir_all(root).expect("remove temporary project");
}