-
[rust] 규칙에 맞는 프로젝트 템플릿을 통해 새로운 rust 프로젝트 생성을 돕는 cargo-generateRust 2024. 11. 10. 10:31반응형
cargo new 명령을 통한 프로젝트 생성은 실행프로그램을 생성하는 --bin 과 라이브러리 생성인 --lib 두가지이다. 그 후 webapi 이든 ui 프로그램이든 생성하고자 하는 프로그램 유형에 따라 crate 를 일일히 추가해줘야 한다.
매번 생성하는게 귀찮다면 cargo-generate 를 설치해 보는 것을 추천한다.
cargo binstall cargo-generate
설치 후 아래와 같이 사용하면 된다. 아래 예시는 rust + axum + utoipa 조합으로 webapi 개발을 위해 직접 생성한 webapi 브랜치이다.
cargo generate --git https://github.com/ddochea0314/template-axum-webapi
생성하면 입력한 프로젝트명에 따라
README.md
파일과main.rs
의 Info::new() title 부분에 입력한 프로젝트명이 들어가는 것을 확인할 수 있다.PS /Users/ddochea/source/repos> cargo generate --git https://github.com/ddochea0314/template-axum-webapi 🤷 Project Name: my-test-api 🔧 Destination: /Users/ddochea/source/repos/my-test-api ... 🔧 project-name: my-test-api ... 🔧 Generating template ... 🔧 Moving generated files into: `/Users/ddochea/source/repos/my-test-api`... 🔧 Initializing a fresh Git repository ✨ Done! New project created /Users/ddochea/source/repos/my-test-api
로컬에 생성한 템플릿도 사용가능하다. --git 대신 --path를 사용하면 된다.
cargo generate --path ./cargo-gen-test/
템플릿 소스코드를 살펴보면 {{project-name}}과 {{authors}} 를 확인할 수 있다. 이를 code generate 에서
placeholder
라고 부르며, {{project-name}}과 {{authors}}는 code generate에서 기본적으로 사용하는 빌트인 placeholder 이다. 보다 자세한 정보는 아래 링크를 통해 확인할 수 있다.https://cargo-generate.github.io/cargo-generate/templates/builtin_placeholders.html
기본적으로 제공하는 빌트인 placeholder 외에도 직접 생성할 수 있다. 템플릿 프로젝트 루트경로에
cargo-generate.toml
를 생성하고 아래와 같이 입력한다.[placeholders] placeholder_name = { prompt = "Enter your name", choices = ["Alice", "Bob"], default = "Alice", type = "string" }
그리고
placeholder_name
을 README.md 파일이나 소스코드 내부에 {{placeholder_name}} 를 추가해보자.fn main() { println!("Hello, world!, {{placeholder_name}}"); }
cargo generate 로 프로젝트를 생성해준다.
PS /Users/ddochea/source/repos> cargo generate --path ./cargo-gen-test/ 🤷 Project Name: gen-test123 🔧 Destination: /Users/ddochea/source/repos/gen-test123 ... 🔧 project-name: gen-test123 ... 🔧 Generating template ... ✔ 🤷 Enter your name · Alice 🔧 Moving generated files into: `/Users/ddochea/source/repos/gen-test123`... 🔧 Initializing a fresh Git repository ✨ Done! New project created /Users/ddochea/source/repos/gen-test123
생성된 프로젝트의 소스코드를 살펴보면
Enter your name
프롬프트로 입력받은 이름이 코드에 반영된 것을 확인할 수 있다.fn main() { println!("Hello, world!, Alice"); }
https://github.com/cargo-generate/cargo-generate
반응형'Rust' 카테고리의 다른 글
[rust] tokio 비동기 동시 처리 기본 예시 코드 (0) 2024.11.24 [rust] tokio, bb8, tokio_postgres DB 연결 예시 코드 (0) 2024.11.24 [rust] axum 과 utoipa 로 swagger를 지원하는 web api 구현 예제 (1) 2024.09.18