capy-cli 0.10.0

The command-line interface for the Capy web framework.
Documentation
//! Resource generation safety: failed plans must not damage application-owned code.
use capy_cli::{
    make_auth, make_resource, make_resource_with_access, make_resource_with_options,
    new_project_with_frontend, AccessProfile, FrontendDriver,
};
use std::{
    collections::BTreeMap,
    fs,
    path::{Path, PathBuf},
};

fn snapshot(root: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
    fn visit(base: &Path, path: &Path, files: &mut BTreeMap<PathBuf, Vec<u8>>) {
        for entry in fs::read_dir(path).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                visit(base, &path, files);
            } else {
                files.insert(
                    path.strip_prefix(base).unwrap().to_owned(),
                    fs::read(path).unwrap(),
                );
            }
        }
    }
    let mut files = BTreeMap::new();
    visit(root, root, &mut files);
    files
}
fn fields() -> Vec<String> {
    [
        "title:string",
        "slug:string:unique",
        "body:text",
        "published:boolean=false",
        "published_at:datetime?",
    ]
    .map(String::from)
    .to_vec()
}

#[test]
fn resources_generate_public_contracts_and_preserve_customizations() {
    for auth in [false, true] {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("blog");
        new_project_with_frontend(&root, "blog", FrontendDriver::None).unwrap();
        if auth {
            make_auth(&root).unwrap();
        }
        make_resource(&root, "Post", &fields(), false).unwrap();
        let model = fs::read_to_string(root.join("app/models/post.rs")).unwrap();
        assert!(!model.contains("Serialize"));
        assert_eq!(model.contains("owner_id"), auth);
        let response = fs::read_to_string(root.join("app/responses/post.rs")).unwrap();
        assert!(response.contains("PostResponse"));
        assert!(!response.contains("owner_id"));
        let controller =
            fs::read_to_string(root.join("app/controllers/post_controller.rs")).unwrap();
        assert_eq!(controller.contains("PostPolicy::authorize"), auth);
        fs::write(root.join("app/models/post.rs"), "// my custom model\n").unwrap();
        let before = snapshot(&root);
        assert!(make_resource(&root, "Post", &fields(), false).is_err());
        assert_eq!(snapshot(&root), before);
    }
}

#[test]
fn deterministic_output_and_independent_resources() {
    let temp = tempfile::tempdir().unwrap();
    let mut outputs = Vec::new();
    for dir in ["a", "b"] {
        let root = temp.path().join(dir);
        new_project_with_frontend(&root, "blog", FrontendDriver::None).unwrap();
        make_resource(&root, "Post", &fields(), false).unwrap();
        make_resource(&root, "Category", &["name:string:unique".into()], false).unwrap();
        outputs.push(snapshot(&root));
    }
    assert_eq!(outputs[0], outputs[1]);
}

#[test]
fn public_read_requires_auth_and_only_opens_read_paths() {
    let temp = tempfile::tempdir().unwrap();
    let root = temp.path().join("blog");
    new_project_with_frontend(&root, "blog", FrontendDriver::React).unwrap();
    let before = snapshot(&root);
    assert!(make_resource_with_access(
        &root,
        "Post",
        &fields(),
        true,
        Some(AccessProfile::PublicRead),
    )
    .unwrap_err()
    .to_string()
    .contains("make:auth"));
    assert_eq!(snapshot(&root), before);
    capy_cli::make_auth_with_frontend(&root, true).unwrap();
    make_resource_with_access(
        &root,
        "Post",
        &fields(),
        true,
        Some(AccessProfile::PublicRead),
    )
    .unwrap();
    let controller = fs::read_to_string(root.join("app/controllers/post_controller.rs")).unwrap();
    let index = controller
        .split("pub async fn index(")
        .nth(1)
        .unwrap()
        .split("pub async fn show(")
        .next()
        .unwrap();
    assert!(index.contains("Context(ctx): Context"));
    assert!(!index.contains("AuthUser"));
    assert!(controller.contains("pub async fn show(Context(ctx): Context"));
    let create = controller
        .split("pub async fn create(")
        .nth(1)
        .unwrap()
        .split("pub async fn update(")
        .next()
        .unwrap();
    assert!(create.contains("AuthUser(user): AuthUser"));
    assert!(!controller.contains("filter(post::Column::OwnerId"));
    assert!(controller.contains("PostPolicy::authorize(&user, PostAction::Update"));
    let routes = fs::read_to_string(root.join("routes/posts.rs")).unwrap();
    assert!(routes.contains("response::<Page<PostResponse>>()"));
    assert_eq!(routes.matches(".authenticated()").count(), 3);
    let tests = fs::read_to_string(root.join("tests/posts.rs")).unwrap();
    assert!(tests.contains("let mut guest = app.session()"));
    assert!(tests.contains("other.get(&path)"));
    let frontend = fs::read_to_string(root.join("frontend/src/features/posts/index.tsx")).unwrap();
    assert!(frontend.contains("render: () => <PostList />"));
    assert!(frontend.contains("<ProtectedRoute><PostCreate />"));
}

#[test]
fn references_generate_foreign_keys_relations_and_parent_fixtures_atomically() {
    let temp = tempfile::tempdir().unwrap();
    let root = temp.path().join("blog");
    new_project_with_frontend(&root, "blog", FrontendDriver::None).unwrap();
    make_auth(&root).unwrap();
    make_resource(&root, "Post", &["title:string".into()], false).unwrap();
    let before = snapshot(&root);
    assert!(make_resource(
        &root,
        "Comment",
        &["missing_id:references:Missing".into(), "body:text".into()],
        false,
    )
    .is_err());
    assert_eq!(snapshot(&root), before);
    make_resource(
        &root,
        "Comment",
        &["post_id:references:Post".into(), "body:text".into()],
        false,
    )
    .unwrap();
    let migration =
        fs::read_to_string(root.join("database/migrations/m_resource_comment.rs")).unwrap();
    assert!(migration.contains("ForeignKeyAction::Restrict"));
    assert!(migration.contains("fk_comments_0"));
    assert!(migration.contains("idx_comments_0"));
    let model = fs::read_to_string(root.join("app/models/comment.rs")).unwrap();
    assert!(model.contains("belongs_to = \"super::post::Entity\""));
    assert!(model.contains("impl Related<super::post::Entity> for Entity"));
    let reverse = fs::read_to_string(root.join("app/models/comment_relations.rs")).unwrap();
    assert!(reverse.contains("impl Related<super::comment::Entity> for super::post::Entity"));
    let tests = fs::read_to_string(root.join("tests/comments.rs")).unwrap();
    assert!(tests.contains("post_fixture::PostFactory"));
    assert!(tests.contains("parent_post.id"));
    let response = fs::read_to_string(root.join("app/responses/comment.rs")).unwrap();
    assert!(response.contains("pub post_id: i32"));
    assert!(!response.contains("pub post:"));
    let before_repeat = snapshot(&root);
    assert!(make_resource(
        &root,
        "Comment",
        &["post_id:references:Post".into(), "body:text".into()],
        false,
    )
    .is_err());
    assert_eq!(snapshot(&root), before_repeat);
}

#[test]
fn nested_routes_bind_children_to_their_parent() {
    let temp = tempfile::tempdir().unwrap();
    let root = temp.path().join("blog");
    new_project_with_frontend(&root, "blog", FrontendDriver::None).unwrap();
    make_auth(&root).unwrap();
    make_resource(&root, "Post", &["title:string".into()], false).unwrap();
    let fields = ["post_id:references:Post".into(), "body:text".into()];
    let before = snapshot(&root);
    assert!(
        make_resource_with_options(&root, "Comment", &fields, false, None, Some("User"))
            .unwrap_err()
            .to_string()
            .contains("requires a user_id")
    );
    assert_eq!(snapshot(&root), before);
    make_resource_with_options(&root, "Comment", &fields, false, None, Some("Post")).unwrap();
    let routes = fs::read_to_string(root.join("routes/comments.rs")).unwrap();
    assert!(routes.contains("/posts/{post_id}/comments"));
    assert!(routes.contains("/posts/{post_id}/comments/{id}"));
    assert!(routes.contains("listCommentsForPost"));
    let controller =
        fs::read_to_string(root.join("app/controllers/comment_controller.rs")).unwrap();
    assert!(controller.contains("pub async fn index_nested"));
    assert!(controller.contains("pub async fn create_nested"));
    assert!(controller.contains("pub async fn show_nested"));
    assert!(controller.contains("Column::PostId.eq(parent_id)"));
    assert!(controller.contains("if input.post_id != parent_id"));
}

#[test]
fn enum_resource_stays_closed_across_rust_schema_and_react() {
    let temp = tempfile::tempdir().unwrap();
    let root = temp.path().join("blog");
    new_project_with_frontend(&root, "blog", FrontendDriver::React).unwrap();
    capy_cli::make_auth_with_frontend(&root, true).unwrap();
    make_resource_with_access(
        &root,
        "Post",
        &[
            "title:string".into(),
            "status:enum[draft,published,archived]=draft".into(),
        ],
        true,
        Some(AccessProfile::PublicRead),
    )
    .unwrap();
    let model = fs::read_to_string(root.join("app/models/post.rs")).unwrap();
    assert!(model.contains("pub enum PostStatus"));
    assert!(model.contains("string_value = \"published\""));
    let migration =
        fs::read_to_string(root.join("database/migrations/m_resource_post.rs")).unwrap();
    assert!(migration.contains(".check("));
    assert!(migration.contains("\"archived\""));
    let request = fs::read_to_string(root.join("app/requests/create_post.rs")).unwrap();
    assert!(request.contains("PostStatus"));
    let form = fs::read_to_string(root.join("frontend/src/features/posts/components/PostForm.tsx"))
        .unwrap();
    assert!(form.contains("UpdatePostRequest['status']"));
    assert!(form.contains("Invalid status"));
}

#[test]
fn collisions_and_missing_anchors_are_atomic_with_exact_instructions() {
    for (path, contents) in [
        ("app/models/mod.rs", "pub type PostModel = ();"),
        (
            "app/controllers/mod.rs",
            "use external::custom as post_controller;",
        ),
        (
            "routes/api.rs",
            "use capy::Routes; pub fn routes() -> Routes { Routes::new() }",
        ),
        ("database/seeds.rs", "// customized seed entry point"),
        (
            "database/migrations/mod.rs",
            "mod m_resource_post {}\n// capy:modules\n// capy:migrations",
        ),
        (
            "database/migrations/mod.rs",
            "// customized migration entry point",
        ),
        ("src/bootstrap.rs", "// customized application factory"),
    ] {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("blog");
        new_project_with_frontend(&root, "blog", FrontendDriver::None).unwrap();
        fs::write(root.join(path), contents).unwrap();
        let before = snapshot(&root);
        let error = make_resource(&root, "Post", &fields(), false).unwrap_err();
        if path == "routes/api.rs" {
            assert!(error
                .to_string()
                .contains(".merge(crate::routes::posts::routes())"));
        }
        assert_eq!(snapshot(&root), before, "{path}");
    }
}

#[cfg(unix)]
#[test]
fn symlinked_destination_is_rejected_before_any_commit() {
    let temp = tempfile::tempdir().unwrap();
    let root = temp.path().join("blog");
    new_project_with_frontend(&root, "blog", FrontendDriver::None).unwrap();
    let outside = temp.path().join("outside");
    fs::create_dir(&outside).unwrap();
    std::os::unix::fs::symlink(&outside, root.join("app/responses")).unwrap();
    assert!(make_resource(&root, "Post", &fields(), false)
        .unwrap_err()
        .to_string()
        .contains("symlink"));
    assert!(fs::read_dir(outside).unwrap().next().is_none());
    assert!(!root.join("app/models/post.rs").exists());
}