From 86b7ced698508b4f02229c3a203447c6068ef082 Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Fri, 27 Oct 2023 20:54:14 +0800 Subject: [PATCH 01/18] update version --- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 13 +++++-------- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a54286a..a890348 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -798,7 +798,7 @@ checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" [[package]] name = "salvo-cli" -version = "0.1.11" +version = "0.1.12" dependencies = [ "ansi_term", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index 93fbd59..7e212bd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "salvo-cli" -version = "0.1.11" +version = "0.1.12" edition = "2021" authors = ["Fankai Liu liufankai137@outlook.com"] keywords = ["salvo", "cli","template"] diff --git a/README.md b/README.md index c30fb31..f914958 100644 --- a/README.md +++ b/README.md @@ -24,14 +24,11 @@ cargo install --force salvo-cli | Status |Plan | |:---:|:---:| |✅| web api template | -|✅| web site with template | -|✅|with sqlx template| -|✅|basic midware | -|✅|suport sqlite,pgsql,mysql| -|✅|with seaorm template| -|✅| better web site | -|✅| with diesel template| -|| with Rbatis template| +|✅| web site template | +|✅|Template with SQLx, SeaORM, Diesel, Rbatis (support for SQLite, PostgreSQL, MySQL)| +|✅|Basic middleware | +|⏳|More middleware| +|⏳|Support for MongoDB| ## License This project is licensed under the MIT OR Apache-2.0 License. From f4e8279f92a3e5c6c2d87baade748827eaf4bb46 Mon Sep 17 00:00:00 2001 From: fankaiLiu <93850567+fankaiLiu@users.noreply.github.com> Date: Fri, 27 Oct 2023 22:18:19 +0800 Subject: [PATCH 02/18] Create rust.yml --- .github/workflows/rust.yml | 49 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 .github/workflows/rust.yml diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml new file mode 100644 index 0000000..c4f0f63 --- /dev/null +++ b/.github/workflows/rust.yml @@ -0,0 +1,49 @@ +name: build + +on: + push: + branches: + - master + pull_request: + branches: + - master + +jobs: + build-rust: + strategy: + matrix: + platform: [ubuntu-latest] + runs-on: ${{ matrix.platform }} + steps: + - uses: actions/checkout@v2 + - name: Cache cargo registry + uses: actions/cache@v1 + with: + path: ~/.cargo/registry + key: ${{ runner.os }}-cargo-registry + - name: Cache cargo index + uses: actions/cache@v1 + with: + path: ~/.cargo/git + key: ${{ runner.os }}-cargo-index + - name: Cache cargo build + uses: actions/cache@v1 + with: + path: rust/target + key: ${{ runner.os }}-cargo-build-target + - name: Install stable + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + - name: Check code format + run: cargo fmt -- --check + - name: Check the package for errors + run: cargo check --all + - name: Lint rust sources + run: cargo clippy --all-targets --all-features --tests --benches -- -D warnings + - name: Run tests + run: RUST_BACKTRACE=1 cargo test --all-features -- --test-threads=1 --nocapture + - name: Generate docs + run: cargo doc --all-features --no-deps From 84f7ee6bde405c8c8205f419da8d26ac6b27f470 Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Fri, 27 Oct 2023 22:27:04 +0800 Subject: [PATCH 03/18] fix ci --- .github/workflows/rust.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index c4f0f63..e3c88ba 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -3,10 +3,10 @@ name: build on: push: branches: - - master + - main pull_request: branches: - - master + - main jobs: build-rust: From 2309e67dd22bc19c12edfe439f41b7c8f9ea4212 Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Fri, 27 Oct 2023 22:33:37 +0800 Subject: [PATCH 04/18] cargo clippy --- src/utils/create_project.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/create_project.rs b/src/utils/create_project.rs index af1a340..aed0cf1 100644 --- a/src/utils/create_project.rs +++ b/src/utils/create_project.rs @@ -33,7 +33,7 @@ pub fn create_project(project: Project) -> Result<()> { let config = get_user_selected()?; match config { Some(config) => { - write_project_file(project_path, config.clone(), project.clone())?; + write_project_file(project_path, config, project.clone())?; init_git(project_path)?; From 1a488a4603a32452dd33e849ccf3ccda4ae8b760 Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Fri, 27 Oct 2023 22:35:09 +0800 Subject: [PATCH 05/18] cargo clippy --- src/utils/create_project.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/utils/create_project.rs b/src/utils/create_project.rs index aed0cf1..524fbe4 100644 --- a/src/utils/create_project.rs +++ b/src/utils/create_project.rs @@ -59,11 +59,10 @@ pub fn create_project(project: Project) -> Result<()> { success(t!("create_success_mysql_or_pgsql").replace(r"\n", "\n")); } } - match (config.db_conn_type, config.db_type) { - (DbConnectionType::Rbatis, DbType::Mysql | DbType::Postgres | DbType::Mssql) => { - success(t!("create_success_rbatis")); - } - (_, _) => {} + if let (DbConnectionType::Rbatis, DbType::Mysql | DbType::Postgres | DbType::Mssql) = + (config.db_conn_type, config.db_type) + { + success(t!("create_success_rbatis")); } } None => anyhow::bail!("cli quit!"), From ea89b95281ffee43200ea17d8bad1bfc14413b80 Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Sat, 28 Oct 2023 13:34:00 +0800 Subject: [PATCH 06/18] Optimized code --- src/utils/create_project.rs | 39 +++++++++++++++++++++---------------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/src/utils/create_project.rs b/src/utils/create_project.rs index 524fbe4..29064a2 100644 --- a/src/utils/create_project.rs +++ b/src/utils/create_project.rs @@ -38,31 +38,36 @@ pub fn create_project(project: Project) -> Result<()> { init_git(project_path)?; success(t!("create_success", project_name = project_name).replace(r"\n", "\n")); - if config.db_conn_type == DbConnectionType::Sqlx - || config.db_conn_type == DbConnectionType::SeaOrm - || config.db_conn_type == DbConnectionType::Diesel - { - if config.db_conn_type == DbConnectionType::Sqlx { + match config.db_conn_type { + DbConnectionType::Sqlx => { success( t!("create_success_sqlx", project_name = project_name).replace(r"\n", "\n"), ); } - if config.db_conn_type == DbConnectionType::SeaOrm { + DbConnectionType::SeaOrm => { success( - t!("create_success_sea_orm", project_name = project_name) - .replace(r"\n", "\n"), + t!("create_success_sea_orm", project_name = project_name).replace(r"\n", "\n"), ); } - if config.db_type == DbType::Sqlite { - success(t!("create_success_sqlx_sqlite").replace(r"\n", "\n")); - } else { - success(t!("create_success_mysql_or_pgsql").replace(r"\n", "\n")); + DbConnectionType::Diesel => { + match config.db_type { + DbType::Sqlite => { + success(t!("create_success_sqlx_sqlite").replace(r"\n", "\n")); + } + _ => { + success(t!("create_success_mysql_or_pgsql").replace(r"\n", "\n")); + } + } } - } - if let (DbConnectionType::Rbatis, DbType::Mysql | DbType::Postgres | DbType::Mssql) = - (config.db_conn_type, config.db_type) - { - success(t!("create_success_rbatis")); + DbConnectionType::Rbatis => { + match config.db_type { + DbType::Mysql | DbType::Postgres | DbType::Mssql => { + success(t!("create_success_rbatis")); + } + _ => {} + } + } + _ => {} } } None => anyhow::bail!("cli quit!"), From 45fa18bc84c06a6dfa37cc7d1770d8a2dc93861a Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Sat, 28 Oct 2023 23:02:51 +0800 Subject: [PATCH 07/18] Optimized code --- src/utils/create_project.rs | 62 ++++++++++++++++++++----------------- 1 file changed, 33 insertions(+), 29 deletions(-) diff --git a/src/utils/create_project.rs b/src/utils/create_project.rs index 29064a2..cb9a436 100644 --- a/src/utils/create_project.rs +++ b/src/utils/create_project.rs @@ -37,42 +37,46 @@ pub fn create_project(project: Project) -> Result<()> { init_git(project_path)?; - success(t!("create_success", project_name = project_name).replace(r"\n", "\n")); - match config.db_conn_type { - DbConnectionType::Sqlx => { - success( - t!("create_success_sqlx", project_name = project_name).replace(r"\n", "\n"), - ); - } - DbConnectionType::SeaOrm => { - success( - t!("create_success_sea_orm", project_name = project_name).replace(r"\n", "\n"), - ); + after_print_info(project_name, config); + } + None => anyhow::bail!("cli quit!"), + } + Ok(()) +} + +fn after_print_info(project_name: &String, config: UserSelected) { + success(t!("create_success", project_name = project_name).replace(r"\n", "\n")); + match config.db_conn_type { + DbConnectionType::Sqlx => { + success( + t!("create_success_sqlx", project_name = project_name).replace(r"\n", "\n"), + ); + } + DbConnectionType::SeaOrm => { + success( + t!("create_success_sea_orm", project_name = project_name).replace(r"\n", "\n"), + ); + } + DbConnectionType::Diesel => { + match config.db_type { + DbType::Sqlite => { + success(t!("create_success_sqlx_sqlite").replace(r"\n", "\n")); } - DbConnectionType::Diesel => { - match config.db_type { - DbType::Sqlite => { - success(t!("create_success_sqlx_sqlite").replace(r"\n", "\n")); - } - _ => { - success(t!("create_success_mysql_or_pgsql").replace(r"\n", "\n")); - } - } + _ => { + success(t!("create_success_mysql_or_pgsql").replace(r"\n", "\n")); } - DbConnectionType::Rbatis => { - match config.db_type { - DbType::Mysql | DbType::Postgres | DbType::Mssql => { - success(t!("create_success_rbatis")); - } - _ => {} - } + } + } + DbConnectionType::Rbatis => { + match config.db_type { + DbType::Mysql | DbType::Postgres | DbType::Mssql => { + success(t!("create_success_rbatis")); } _ => {} } } - None => anyhow::bail!("cli quit!"), + _ => {} } - Ok(()) } fn write_project_file( From f2e346b8c47fc8301d6b49526d6d8cc44efb6627 Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Sat, 28 Oct 2023 23:29:05 +0800 Subject: [PATCH 08/18] fix bug update_user --- src/template/src/services/user.hbs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/template/src/services/user.hbs b/src/template/src/services/user.hbs index 4860e36..b1a729f 100644 --- a/src/template/src/services/user.hbs +++ b/src/template/src/services/user.hbs @@ -399,15 +399,19 @@ pub async fn login(req: UserLoginRequest) -> AppResult { pub async fn update_user(req: UserUpdateRequest) -> AppResult { let db = DB.get().ok_or(anyhow::anyhow!("数据库连接失败"))?; - let user = Users::select_by_column(db,"id",&req.id).await?; - if user.len()==0 { + let users = Users::select_by_column(db,"id",&req.id).await?; + if users.len()==0 { return Err(anyhow::anyhow!("用户不存在").into()); } - Users::update_by_column(db,&user[0],"id").await?; - + let user = Users { + id: users[0].clone().id, + username: users[0].clone().username, + password: rand_utils::hash_password(req.password).await?, + }; + Users::update_by_column(db,&user,"id").await?; Ok(UserResponse { - id: user[0].id.clone(), - username: user[0].username.clone(), + id: users[0].id.clone(), + username: users[0].username.clone(), }) } From dcbd0964715bdaefdd81c96184656b64e2fb60a6 Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Sat, 28 Oct 2023 23:30:08 +0800 Subject: [PATCH 09/18] cargo fmt --- src/utils/create_project.rs | 36 ++++++++++++++---------------------- 1 file changed, 14 insertions(+), 22 deletions(-) diff --git a/src/utils/create_project.rs b/src/utils/create_project.rs index cb9a436..e62efee 100644 --- a/src/utils/create_project.rs +++ b/src/utils/create_project.rs @@ -48,33 +48,25 @@ fn after_print_info(project_name: &String, config: UserSelected) { success(t!("create_success", project_name = project_name).replace(r"\n", "\n")); match config.db_conn_type { DbConnectionType::Sqlx => { - success( - t!("create_success_sqlx", project_name = project_name).replace(r"\n", "\n"), - ); + success(t!("create_success_sqlx", project_name = project_name).replace(r"\n", "\n")); } DbConnectionType::SeaOrm => { - success( - t!("create_success_sea_orm", project_name = project_name).replace(r"\n", "\n"), - ); + success(t!("create_success_sea_orm", project_name = project_name).replace(r"\n", "\n")); } - DbConnectionType::Diesel => { - match config.db_type { - DbType::Sqlite => { - success(t!("create_success_sqlx_sqlite").replace(r"\n", "\n")); - } - _ => { - success(t!("create_success_mysql_or_pgsql").replace(r"\n", "\n")); - } + DbConnectionType::Diesel => match config.db_type { + DbType::Sqlite => { + success(t!("create_success_sqlx_sqlite").replace(r"\n", "\n")); } - } - DbConnectionType::Rbatis => { - match config.db_type { - DbType::Mysql | DbType::Postgres | DbType::Mssql => { - success(t!("create_success_rbatis")); - } - _ => {} + _ => { + success(t!("create_success_mysql_or_pgsql").replace(r"\n", "\n")); } - } + }, + DbConnectionType::Rbatis => match config.db_type { + DbType::Mysql | DbType::Postgres | DbType::Mssql => { + success(t!("create_success_rbatis")); + } + _ => {} + }, _ => {} } } From 3d080475b15d39a2e0d4b9e3cb79e13bf9f6c7c8 Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Sat, 28 Oct 2023 23:32:25 +0800 Subject: [PATCH 10/18] update version --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a890348..f33b3ad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -798,7 +798,7 @@ checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" [[package]] name = "salvo-cli" -version = "0.1.12" +version = "0.1.13" dependencies = [ "ansi_term", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index 7e212bd..57ac9ce 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "salvo-cli" -version = "0.1.12" +version = "0.1.13" edition = "2021" authors = ["Fankai Liu liufankai137@outlook.com"] keywords = ["salvo", "cli","template"] From 327cd14e5f6e079c147da3e5ad39f55ceb44696f Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Sun, 29 Oct 2023 16:10:24 +0800 Subject: [PATCH 11/18] update readme --- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 14 +++++++++++--- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f33b3ad..8cd00f5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -798,7 +798,7 @@ checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" [[package]] name = "salvo-cli" -version = "0.1.13" +version = "0.1.14" dependencies = [ "ansi_term", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index 57ac9ce..91e76d4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "salvo-cli" -version = "0.1.13" +version = "0.1.14" edition = "2021" authors = ["Fankai Liu liufankai137@outlook.com"] keywords = ["salvo", "cli","template"] diff --git a/README.md b/README.md index f914958..19f47db 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,14 @@ - -# Salvo CLI - +
+

Savlo

+

+ + build status + +crates.io +Download +License +

+
Salvo CLI is a command-line interface tool for the [Salvo](https://github.com/salvo-rs/salvo) web framework. It helps streamline the process of setting up a new Salvo project by generating a template structure. ## Installation From 7e943b9153874a63099ec3e6e93b4c4ccd8617c8 Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Sun, 29 Oct 2023 19:28:10 +0800 Subject: [PATCH 12/18] update salvo version --- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 5 +- locales/app.yml | 20 +++++++- locales/code_comment.yml | 82 +++++++++++++++++++------------ src/template/src/routers/user.hbs | 8 +-- src/utils/create_project.rs | 34 ++++++++++--- 7 files changed, 104 insertions(+), 49 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8cd00f5..9d30dab 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -798,7 +798,7 @@ checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" [[package]] name = "salvo-cli" -version = "0.1.14" +version = "0.1.15" dependencies = [ "ansi_term", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index 91e76d4..84c1733 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "salvo-cli" -version = "0.1.14" +version = "0.1.15" edition = "2021" authors = ["Fankai Liu liufankai137@outlook.com"] keywords = ["salvo", "cli","template"] diff --git a/README.md b/README.md index 19f47db..a0b1ec1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,5 @@
-

Savlo

-

+

Savlo build status @@ -9,6 +8,8 @@ License

+ +## Introduction Salvo CLI is a command-line interface tool for the [Salvo](https://github.com/salvo-rs/salvo) web framework. It helps streamline the process of setting up a new Salvo project by generating a template structure. ## Installation diff --git a/locales/app.yml b/locales/app.yml index ff37518..415693e 100644 --- a/locales/app.yml +++ b/locales/app.yml @@ -382,4 +382,22 @@ select_db_type: uk: виберіть тип бази даних th: เลือกประเภทฐานข้อมูล el: επιλέξτε τύπο βάσης δεδομένων - da: vælg databasetype \ No newline at end of file + da: vælg databasetype +access_instructions: + en: After running it, you can access /login with the default username:zhangsan and password:123 + zh_CN: 运行之后,您可以使用默认用户名:zhangsan和密码:123访问/login + zh_TW: 運行之後,您可以使用預設的使用者名稱:zhangsan和密碼:123來訪問/login + fr: Après l'avoir exécuté, vous pouvez accéder à /login avec le nom d'utilisateur par défaut:zhangsan et le mot de passe:123 + ja: 実行した後、デフォルトのユーザー名:zhangsanとパスワード:123で/loginにアクセスできます + es: Después de ejecutarlo, puedes acceder a /login con el nombre de usuario predeterminado:zhangsan y la contraseña:123 + de: Nach dem Ausführen können Sie sich mit dem Standard-Benutzernamen:zhangsan und Passwort:123 bei /login anmelden + ru: После запуска вы можете войти в /login с использованием стандартного имени пользователя:zhangsan и пароля:123 + it: Dopo averlo eseguito, è possibile accedere a /login con il nome utente predefinito:zhangsan e la password:123 + pt: Depois de executá-lo, você pode acessar /login com o nome de usuário padrão:zhangsan e a senha:123 + ko: 실행한 후 기본 사용자 이름:zhangsan 및 비밀번호:123으로 /login에 접속할 수 있습니다 + no: Etter at du har kjørt det, kan du få tilgang til /login med standard brukernavn:zhangsan og passord:123 + is: Eftir að hafa keyrt það, getur þú notað /login með sjálfgefna notendanafnið:zhangsan og lykilorðið:123 + uk: Після його запуску Ви можете отримати доступ до /login за допомогою стандартного імені користувача:zhangsan та пароля:123 + th: หลังจากทำการรันแล้ว คุณสามารถเข้าถึง /login ด้วยชื่อผู้ใช้งานเริ่มต้น:zhangsan และรหัสผ่าน:123 + el: Αφού το τρέξετε, μπορείτε να προσπελάσετε το /login με το προεπιλεγμένο όνομα χρήστη:zhangsan και τον κωδικό πρόσβασης:123 + da: Efter du har kørt det, kan du få adgang til /login med standard brugernavn:zhangsan og adgangskode:123 \ No newline at end of file diff --git a/locales/code_comment.yml b/locales/code_comment.yml index 605811b..b5a8956 100644 --- a/locales/code_comment.yml +++ b/locales/code_comment.yml @@ -437,23 +437,23 @@ create_success_sea_orm: el: 🐚 Επιλέξατε sea-orm, η τεκμηρίωση μπορεί να προβληθεί εδώ:https://www.sea-ql.org/SeaORM/docs/index/ da: 🐚 Du har valgt sea-orm, dokumentationen kan ses her:https://www.sea-ql.org/SeaORM/docs/index/ create_success_sqlx_sqlite: - en: 🎯 Default database created in `/data/demo.db`.\n After running it, you can access /login with the default username:zhangsan and password:123. - zh_CN: 🎯 默认数据库创建在`/data/demo.db`。\n 运行后,您可以使用默认用户名:zhangsan和密码:123访问/login。 - zh_TW: 🎯 預設資料庫創建在`/data/demo.db`。\n 運行後,您可以使用預設用戶名:zhangsan和密碼:123訪問/login。 - fr: 🎯 Base de données par défaut créée dans `/data/demo.db`. \n Après l'avoir exécuté, vous pouvez accéder à /login avec le nom d'utilisateur par défaut:zhangsan et le mot de passe:123. - ja: 🎯 デフォルトのデータベースが`/data/demo.db`に作成されました。\n 実行後、デフォルトのユーザー名:zhangsanとパスワード:123で/loginにアクセスできます。 - es: 🎯 Base de datos predeterminada creada en `/data/demo.db`. \n Después de ejecutarlo, puede acceder a /login con el nombre de usuario predeterminado:zhangsan y la contraseña:123. + en: 🎯 Default database created in `/data/demo.db`.\n After running it, you can access /login with the default username:zhangsan and password:123 + zh_CN: 🎯 默认数据库创建在`/data/demo.db`。\n 运行后,您可以使用默认用户名:zhangsan和密码:123访问/login + zh_TW: 🎯 預設資料庫創建在`/data/demo.db`。\n 運行後,您可以使用預設用戶名:zhangsan和密碼:123訪問/login + fr: 🎯 Base de données par défaut créée dans `/data/demo.db`. \n Après l'avoir exécuté, vous pouvez accéder à /login avec le nom d'utilisateur par défaut:zhangsan et le mot de passe:123 + ja: 🎯 デフォルトのデータベースが`/data/demo.db`に作成されました。\n 実行後、デフォルトのユーザー名:zhangsanとパスワード:123で/loginにアクセスできます + es: 🎯 Base de datos predeterminada creada en `/data/demo.db`. \n Después de ejecutarlo, puede acceder a /login con el nombre de usuario predeterminado:zhangsan y la contraseña:123 de: 🎯 Standarddatenbank erstellt in `/data/demo.db`. \n Nach dem Ausführen können Sie mit dem Standardbenutzernamen:zhangsan und dem Passwort:123 auf /login zugreifen. - ru: 🎯 База данных по умолчанию создана в `/data/demo.db`. \n После запуска вы можете получить доступ к /login с именем пользователя по умолчанию:zhangsan и паролем:123. - it: 🎯 Database predefinita creata in `/data/demo.db`. \n Dopo l'esecuzione, è possibile accedere a /login con l'username predefinito:zhangsan e la password:123. - pt: 🎯 Banco de dados padrão criado em `/data/demo.db`. \n Após executá-lo, você pode acessar /login com o nome de usuário padrão:zhangsan e a senha:123. + ru: 🎯 База данных по умолчанию создана в `/data/demo.db`. \n После запуска вы можете получить доступ к /login с именем пользователя по умолчанию:zhangsan и паролем:123 + it: 🎯 Database predefinita creata in `/data/demo.db`. \n Dopo l'esecuzione, è possibile accedere a /login con l'username predefinito:zhangsan e la password:123 + pt: 🎯 Banco de dados padrão criado em `/data/demo.db`. \n Após executá-lo, você pode acessar /login com o nome de usuário padrão:zhangsan e a senha:123 ko: 🎯 기본 데이터베이스가 `/data/demo.db`에 생성되었습니다. \n 실행 후 기본 사용자 이름:zhangsan과 비밀번호:123으로 /login에 접속할 수 있습니다. - no: 🎯 Standarddatabasen er opprettet i `/data/demo.db`. \n Etter å ha kjørt det, kan du få tilgang til /login med standard brukernavn:zhangsan og passord:123. - is: 🎯 Sjálfgefin gagnagrunn búin til í `/data/demo.db`. \n Eftir að hafa keyrt það, getur þú fengið aðgang að /login með sjálfgefnum notandanafni:zhangsan og lykilorði:123. - uk: 🎯 База даних за замовчуванням створена в `/data/demo.db`. \n Після запуску ви можете отримати доступ до /login за допомогою імені користувача за замовчуванням:zhangsan та пароля:123. - th: 🎯 สร้างฐานข้อมูลเริ่มต้นใน `/data/demo.db`. \n หลังจากเรียกใช้งาน คุณสามารถเข้าถึง /login ด้วยชื่อผู้ใช้เริ่มต้น:zhangsan และรหัสผ่าน:123. - el: 🎯 Δημιουργήθηκε η προεπιλεγμένη βάση δεδομένων στο `/data/demo.db`. \n Μετά την εκτέλεσή του, μπορείτε να αποκτήσετε πρόσβαση στο /login με το όνομα χρήστη:zhangsan και τον κωδικό πρόσβασης:123. - da: 🎯 Standarddatabasen er oprettet i `/data/demo.db`. \n Efter at have kørt det, kan du få adgang til /login med standardbrugernavnet:zhangsan og adgangskoden:123. + no: 🎯 Standarddatabasen er opprettet i `/data/demo.db`. \n Etter å ha kjørt det, kan du få tilgang til /login med standard brukernavn:zhangsan og passord:123 + is: 🎯 Sjálfgefin gagnagrunn búin til í `/data/demo.db`. \n Eftir að hafa keyrt það, getur þú fengið aðgang að /login með sjálfgefnum notandanafni:zhangsan og lykilorði:123 + uk: 🎯 База даних за замовчуванням створена в `/data/demo.db`. \n Після запуску ви можете отримати доступ до /login за допомогою імені користувача за замовчуванням:zhangsan та пароля:123 + th: 🎯 สร้างฐานข้อมูลเริ่มต้นใน `/data/demo.db`. \n หลังจากเรียกใช้งาน คุณสามารถเข้าถึง /login ด้วยชื่อผู้ใช้เริ่มต้น:zhangsan และรหัสผ่าน:123 + el: 🎯 Δημιουργήθηκε η προεπιλεγμένη βάση δεδομένων στο `/data/demo.db`. \n Μετά την εκτέλεσή του, μπορείτε να αποκτήσετε πρόσβαση στο /login με το όνομα χρήστη:zhangsan και τον κωδικό πρόσβασης:123 + da: 🎯 Standarddatabasen er oprettet i `/data/demo.db`. \n Efter at have kørt det, kan du få adgang til /login med standardbrugernavnet:zhangsan og adgangskoden:123 create_success_mysql_or_pgsql: en: 📊 Follow the instructions in the data/init_sql.sql file to complete the initialization of data zh_CN: 📊 按照data/init_sql.sql文件中的说明完成数据初始化 @@ -545,20 +545,38 @@ create_success_diesel__mysql_or_pgsql_fist_use: el: -- Παρακαλώ αλλάξτε πρώτα τη συμβολοσειρά σύνδεσης στη βάση δεδομένων στο .env και config/config.toml \n -- Βεβαιωθείτε ότι η βάση δεδομένων υπάρχει, στη συνέχεια εκτελέστε τη μετεγκατάσταση diesel για να επαναφέρετε τη βάση δεδομένων, και εκτελέστε το παρακάτω SQL στη βάση δεδομένων για να προσθέσετε τα προεπιλεγμένα δεδομένα. \n -- Μετά την εκτέλεση, μπορείτε να χρησιμοποιήσετε το προεπιλεγμένο όνομα χρήστη:zhangsan και τον κωδικό:123 για να έχετε πρόσβαση στο /login. \n -- Για περισσότερες λειτουργίες του diesel-cli, παρακαλώ δείτε το /migration/README.md. da: -- Ændre først forbindelsesstrengen til databasen i .env og config/config.toml \n -- Sørg for, at databasen eksisterer, kør derefter diesel migration run for at gendanne databasen, og kør den følgende SQL i databasen for at tilføje standarddataene. \n -- Efter kørsel, kan du bruge standard brugernavnet:zhangsan og adgangskoden:123 for at få adgang til /login. \n -- For mere funktionalitet fra diesel-cli, se venligst /migration/README.md. create_success_rbatis: - en: 🎯 Reminder:Please modify the database connection string in the /config/config.toml file before running it - zh_CN: 🎯 提醒:在运行之前,请在 /config/config.toml 文件中修改数据库连接字符串 - zh_TW: 🎯 提醒:在運行之前,請在 /config/config.toml 文件中修改數據庫連接字符串 - fr: 🎯 Rappel:Veuillez modifier la chaîne de connexion à la base de données dans le fichier /config/config.toml avant de l'exécuter - ja: 🎯 リマインダー:実行する前に、/config/config.toml ファイル内のデータベース接続文字列を変更してください - es: 🎯 Recordatorio:Por favor modifique la cadena de conexión de la base de datos en el archivo /config/config.toml antes de ejecutarlo - de: 🎯 Erinnerung:Bitte ändern Sie die Datenbankverbindungszeichenfolge in der /config/config.toml-Datei, bevor Sie sie ausführen - ru: 🎯 Напоминание:Перед запуском измените строку подключения к базе данных в файле /config/config.toml - it: 🎯 Promemoria:Modificare la stringa di connessione al database nel file /config/config.toml prima di eseguirlo - pt: 🎯 Lembrete:Por favor, modifique a string de conexão do banco de dados no arquivo /config/config.toml antes de executá-lo - ko: 🎯 알림:실행하기 전에 /config/config.toml 파일에서 데이터베이스 연결 문자열을 수정하세요 - no: 🎯 Påminnelse:Vennligst endre databaseforbindelsesstrengen i /config/config.toml-filen før du kjører den - is: 🎯 Áminning:Vinsamlegast breyttu gagnagrunnstengistrenginu í /config/config.toml skránni áður en þú keyrir það - uk: 🎯 Нагадування:Будь ласка, змініть рядок підключення до бази даних у файлі /config/config.toml перед його запуском - th: 🎯 แจ้งเตือน:โปรดแก้ไขสตริงการเชื่อมต่อฐานข้อมูลในไฟล์ /config/config.toml ก่อนที่จะทำการรัน - el: 🎯 Υπενθύμιση:Παρακαλώ τροποποιήστε τη συμβολοσειρά σύνδεσης βάσης δεδομένων στο αρχείο /config/config.toml πριν το τρέξετε - da: 🎯 Påmindelse:Ændr venligst databaseforbindelsesstrengen i /config/config.toml-filen, før du kører den \ No newline at end of file + en: 🎯 Reminder:Please modify the database connection string in the /config/config.toml file before running it \n you can access /login with the default username:zhangsan and password:123 + zh_CN: 🎯 提醒:在运行之前,请在 /config/config.toml 文件中修改数据库连接字符串 \n 您可以使用默认用户名:zhangsan和密码:123访问/login + zh_TW: 🎯 提醒:在運行之前,請在 /config/config.toml 文件中修改數據庫連接字符串 \n 您可以使用默認用戶名:zhangsan和密碼:123訪問/login + fr: 🎯 Rappel:Veuillez modifier la chaîne de connexion à la base de données dans le fichier /config/config.toml avant de l'exécuter \n vous pouvez accéder à /login avec le nom d'utilisateur par défaut:zhangsan et le mot de passe:123 + ja: 🎯 リマインダー:実行する前に、/config/config.toml ファイル内のデータベース接続文字列を変更してください \n デフォルトのユーザー名:zhangsanとパスワード:123で/loginにアクセスできます + es: 🎯 Recordatorio:Por favor modifique la cadena de conexión de la base de datos en el archivo /config/config.toml antes de ejecutarlo \n puede acceder a /login con el nombre de usuario predeterminado:zhangsan y la contraseña:123 + de: 🎯 Erinnerung:Bitte ändern Sie die Datenbankverbindungszeichenfolge in der /config/config.toml-Datei, bevor Sie sie ausführen \n Sie können sich mit dem Standard-Benutzernamen:zhangsan und Passwort:123 bei /login anmelden + ru: 🎯 Напоминание:Перед запуском измените строку подключения к базе данных в файле /config/config.toml \n вы можете войти в /login с использованием стандартного имени пользователя:zhangsan и пароля:123 + it: 🎯 Promemoria:Modificare la stringa di connessione al database nel file /config/config.toml prima di eseguirlo \n è possibile accedere a /login con il nome utente predefinito:zhangsan e la password:123 + pt: 🎯 Lembrete:Por favor, modifique a string de conexão do banco de dados no arquivo /config/config.toml antes de executá-lo \n você pode acessar /login com o nome de usuário padrão:zhangsan e a senha:123 + ko: 🎯 알림:실행하기 전에 /config/config.toml 파일에서 데이터베이스 연결 문자열을 수정하세요 \n 기본 사용자 이름:zhangsan 및 비밀번호:123으로 /login에 접속할 수 있습니다 + no: 🎯 Påminnelse:Vennligst endre databaseforbindelsesstrengen i /config/config.toml-filen før du kjører den \n du kan få tilgang til /login med standard brukernavn:zhangsan og passord:123 + is: 🎯 Áminning:Vinsamlegast breyttu gagnagrunnstengistrenginu í /config/config.toml skránni áður en þú keyrir það \n þú getur notað /login með sjálfgefna notendanafnið:zhangsan og lykilorðið:123 + uk: 🎯 Нагадування:Будь ласка, змініть рядок підключення до бази даних у файлі /config/config.toml перед його запуском \n Ви можете отримати доступ до /login за допомогою стандартного імені користувача:zhangsan та пароля:123 + th: 🎯 แจ้งเตือน:โปรดแก้ไขสตริงการเชื่อมต่อฐานข้อมูลในไฟล์ /config/config.toml ก่อนที่จะทำการรัน \n คุณสามารถเข้าถึง /login ด้วยชื่อผู้ใช้งานเริ่มต้น:zhangsan และรหัสผ่าน:123 + el: 🎯 Υπενθύμιση:Παρακαλώ τροποποιήστε τη συμβολοσειρά σύνδεσης βάσης δεδομένων στο αρχείο /config/config.toml πριν το τρέξετε \n μπορείτε να προσπελάσετε το /login με το προεπιλεγμένο όνομα χρήστη:zhangsan και τον κωδικό πρόσβασης:123 + da: 🎯 Påmindelse:Ændr venligst databaseforbindelsesstrengen i /config/config.toml-filen, før du kører den \n du kan få adgang til /login med standard brugernavn:zhangsan og adgangskode:123 +create_success_sqlx_diesel: + en: 🎯 Default database created in `/data/test.db`.\n After running it, you can access /login with the default username:zhangsan and password:123 + zh_CN: 🎯 默认数据库创建在`/data/test.db`。\n 运行后,您可以使用默认用户名:zhangsan和密码:123访问/login + zh_TW: 🎯 預設資料庫創建在`/data/test.db`。\n 運行後,您可以使用預設用戶名:zhangsan和密碼:123訪問/login + fr: 🎯 Base de données par défaut créée dans `/data/test.db`. \n Après l'avoir exécuté, vous pouvez accéder à /login avec le nom d'utilisateur par défaut:zhangsan et le mot de passe:123 + ja: 🎯 デフォルトのデータベースが`/data/test.db`に作成されました。\n 実行後、デフォルトのユーザー名:zhangsanとパスワード:123で/loginにアクセスできます + es: 🎯 Base de datos predeterminada creada en `/data/test.db`. \n Después de ejecutarlo, puede acceder a /login con el nombre de usuario predeterminado:zhangsan y la contraseña:123 + de: 🎯 Standarddatenbank erstellt in `/data/test.db`. \n Nach dem Ausführen können Sie mit dem Standardbenutzernamen:zhangsan und dem Passwort:123 auf /login zugreifen. + ru: 🎯 База данных по умолчанию создана в `/data/test.db`. \n После запуска вы можете получить доступ к /login с именем пользователя по умолчанию:zhangsan и паролем:123 + it: 🎯 Database predefinita creata in `/data/test.db`. \n Dopo l'esecuzione, è possibile accedere a /login con l'username predefinito:zhangsan e la password:123 + pt: 🎯 Banco de dados padrão criado em `/data/test.db`. \n Após executá-lo, você pode acessar /login com o nome de usuário padrão:zhangsan e a senha:123 + ko: 🎯 기본 데이터베이스가 `/data/test.db`에 생성되었습니다. \n 실행 후 기본 사용자 이름:zhangsan과 비밀번호:123으로 /login에 접속할 수 있습니다. + no: 🎯 Standarddatabasen er opprettet i `/data/test.db`. \n Etter å ha kjørt det, kan du få tilgang til /login med standard brukernavn:zhangsan og passord:123 + is: 🎯 Sjálfgefin gagnagrunn búin til í `/data/test.db`. \n Eftir að hafa keyrt það, getur þú fengið aðgang að /login með sjálfgefnum notandanafni:zhangsan og lykilorði:123 + uk: 🎯 База даних за замовчуванням створена в `/data/test.db`. \n Після запуску ви можете отримати доступ до /login за допомогою імені користувача за замовчуванням:zhangsan та пароля:123 + th: 🎯 สร้างฐานข้อมูลเริ่มต้นใน `/data/test.db`. \n หลังจากเรียกใช้งาน คุณสามารถเข้าถึง /login ด้วยชื่อผู้ใช้เริ่มต้น:zhangsan และรหัสผ่าน:123 + el: 🎯 Δημιουργήθηκε η προεπιλεγμένη βάση δεδομένων στο `/data/test.db`. \n Μετά την εκτέλεσή του, μπορείτε να αποκτήσετε πρόσβαση στο /login με το όνομα χρήστη:zhangsan και τον κωδικό πρόσβασης:123 + da: 🎯 Standarddatabasen er oprettet i `/data/test.db`. \n Efter at have kørt det, kan du få adgang til /login med standardbrugernavnet:zhangsan og adgangskoden:123 diff --git a/src/template/src/routers/user.hbs b/src/template/src/routers/user.hbs index 4144290..5a54a7c 100644 --- a/src/template/src/routers/user.hbs +++ b/src/template/src/routers/user.hbs @@ -41,10 +41,10 @@ pub async fn post_login(req: JsonBody, res: &mut Response) { match result { Ok(data) => { let jwt_token = data.token.clone(); - let cookie = Cookie::build("jwt_token", jwt_token) + let cookie = Cookie::build(("jwt_token", jwt_token)) .path("/") .http_only(true) - .finish(); + .build(); res.add_cookie(cookie); } Err(e) => ErrRes::with_err(&e.to_string()).into_response(res), @@ -134,10 +134,10 @@ pub async fn post_login(req: JsonBody, res: &mut Response) { match result { Ok(data) => { let jwt_token = data.token.clone(); - let cookie = Cookie::build("jwt_token", jwt_token) + let cookie = Cookie::build(("jwt_token", jwt_token)) .path("/") .http_only(true) - .finish(); + .build(); res.add_cookie(cookie); } Err(e) => ErrRes::with_err(&e.to_string()).into_response(res), diff --git a/src/utils/create_project.rs b/src/utils/create_project.rs index e62efee..1fe0fbc 100644 --- a/src/utils/create_project.rs +++ b/src/utils/create_project.rs @@ -48,22 +48,40 @@ fn after_print_info(project_name: &String, config: UserSelected) { success(t!("create_success", project_name = project_name).replace(r"\n", "\n")); match config.db_conn_type { DbConnectionType::Sqlx => { - success(t!("create_success_sqlx", project_name = project_name).replace(r"\n", "\n")); + success(t!("create_success_sqlx").replace(r"\n", "\n")); + match config.db_type + { + DbType::Sqlite => { + success(t!("create_success_sqlx_sqlite").replace(r"\n", "\n")); + }, + _=>{ + success(t!("create_success_mysql_or_pgsql").replace(r"\n", "\n")); + } + } } DbConnectionType::SeaOrm => { - success(t!("create_success_sea_orm", project_name = project_name).replace(r"\n", "\n")); + success(t!("create_success_sea_orm").replace(r"\n", "\n")); + match config.db_type + { + DbType::Sqlite => { + success(t!("create_success_sqlx_sqlite").replace(r"\n", "\n")); + }, + _=>{ + success(t!("create_success_mysql_or_pgsql").replace(r"\n", "\n")); + } + } } DbConnectionType::Diesel => match config.db_type { DbType::Sqlite => { - success(t!("create_success_sqlx_sqlite").replace(r"\n", "\n")); - } - _ => { - success(t!("create_success_mysql_or_pgsql").replace(r"\n", "\n")); + success(t!("create_success_sqlx_diesel").replace(r"\n", "\n")); + }, + _=>{ + success(t!("create_success_mysql_or_pgsql").replace(r"\n", "\n")); } }, DbConnectionType::Rbatis => match config.db_type { DbType::Mysql | DbType::Postgres | DbType::Mssql => { - success(t!("create_success_rbatis")); + success(t!("create_success_rbatis").replace(r"\n", "\n")); } _ => {} }, @@ -96,7 +114,7 @@ fn write_project_file( "jsonwebtoken": "8.3.0", "once_cell": "1.18.0", "salvo": { - "version": "0.57", + "version": "0.58", "features": ["anyhow", "logging", "cors", "oapi", "jwt-auth", "rustls", "catch-panic","cookie"] }, "serde": "1.0.188", From 3cb512ef428190bdaa4b53c03b0e97e876f10f7d Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Sun, 29 Oct 2023 19:36:11 +0800 Subject: [PATCH 13/18] update version --- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 45 ++++++++++++++++++++++++------------- src/utils/create_project.rs | 24 +++++++++----------- 4 files changed, 42 insertions(+), 31 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9d30dab..5d00334 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -798,7 +798,7 @@ checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" [[package]] name = "salvo-cli" -version = "0.1.15" +version = "0.1.16" dependencies = [ "ansi_term", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index 84c1733..31186f2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "salvo-cli" -version = "0.1.15" +version = "0.1.16" edition = "2021" authors = ["Fankai Liu liufankai137@outlook.com"] keywords = ["salvo", "cli","template"] diff --git a/README.md b/README.md index a0b1ec1..b56cc72 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,21 @@
-

Savlo - - build status - -crates.io -Download -License -

+ Savlo +
+ ## Introduction + Salvo CLI is a command-line interface tool for the [Salvo](https://github.com/salvo-rs/salvo) web framework. It helps streamline the process of setting up a new Salvo project by generating a template structure. ## Installation @@ -17,29 +23,36 @@ Salvo CLI is a command-line interface tool for the [Salvo](https://github.com/sa ```bash cargo install salvo-cli ``` + ## Usage + To create a new Salvo project, use the new command followed by the name of your project: ```bash salvo-cli new project_name ``` + ## Update + ```bashs cargo install --force salvo-cli ``` ### Feature Development Plan -| Status |Plan | -|:---:|:---:| -|✅| web api template | -|✅| web site template | -|✅|Template with SQLx, SeaORM, Diesel, Rbatis (support for SQLite, PostgreSQL, MySQL)| -|✅|Basic middleware | -|⏳|More middleware| -|⏳|Support for MongoDB| +| Status | Plan | +| :----: | :--------------------------------------------------------------------------------: | +| ✅ | web api template | +| ✅ | web site template | +| ✅ | Template with SQLx, SeaORM, Diesel, Rbatis (support for SQLite, PostgreSQL, MySQL) | +| ✅ | Basic middleware | +| ⏳ | More middleware | +| ⏳ | Support for MongoDB | + ## License + This project is licensed under the MIT OR Apache-2.0 License. ## Contributing + Contributions are welcome! Please feel free to submit a Pull Request. diff --git a/src/utils/create_project.rs b/src/utils/create_project.rs index 1fe0fbc..e57155f 100644 --- a/src/utils/create_project.rs +++ b/src/utils/create_project.rs @@ -49,34 +49,32 @@ fn after_print_info(project_name: &String, config: UserSelected) { match config.db_conn_type { DbConnectionType::Sqlx => { success(t!("create_success_sqlx").replace(r"\n", "\n")); - match config.db_type - { + match config.db_type { DbType::Sqlite => { success(t!("create_success_sqlx_sqlite").replace(r"\n", "\n")); - }, - _=>{ - success(t!("create_success_mysql_or_pgsql").replace(r"\n", "\n")); + } + _ => { + success(t!("create_success_mysql_or_pgsql").replace(r"\n", "\n")); } } } DbConnectionType::SeaOrm => { success(t!("create_success_sea_orm").replace(r"\n", "\n")); - match config.db_type - { + match config.db_type { DbType::Sqlite => { success(t!("create_success_sqlx_sqlite").replace(r"\n", "\n")); - }, - _=>{ - success(t!("create_success_mysql_or_pgsql").replace(r"\n", "\n")); + } + _ => { + success(t!("create_success_mysql_or_pgsql").replace(r"\n", "\n")); } } } DbConnectionType::Diesel => match config.db_type { DbType::Sqlite => { success(t!("create_success_sqlx_diesel").replace(r"\n", "\n")); - }, - _=>{ - success(t!("create_success_mysql_or_pgsql").replace(r"\n", "\n")); + } + _ => { + success(t!("create_success_mysql_or_pgsql").replace(r"\n", "\n")); } }, DbConnectionType::Rbatis => match config.db_type { From e0cde27e109f6b76316d9c436f032e519898b0cc Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Tue, 7 Nov 2023 19:35:08 +0800 Subject: [PATCH 14/18] fix bug i18n --- src/i18n.rs | 17 ++++++++++++----- src/main.rs | 2 +- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/i18n.rs b/src/i18n.rs index c4a9158..4cae160 100644 --- a/src/i18n.rs +++ b/src/i18n.rs @@ -1,7 +1,9 @@ -use rust_i18n::i18n; +const SUPPORTED_LANGUAGES: [&str; 17] = [ + "en", "zh_CN", "zh_TW", "fr", "ja", "es", "de", "ru", + "it", "pt", "ko", "no", "is", "uk", "th", "el", "da" +]; pub fn set_locale() { - i18n!("locales", fallback = "en"); match get_language() { Some(lang) => { rust_i18n::set_locale(lang.as_str()); @@ -11,12 +13,17 @@ pub fn set_locale() { } } } + fn get_language() -> Option { match std::env::var("LANG") { Ok(lang) => { - let language = lang.split('.').next(); - language.map(|s| s.to_string()) + let language = lang.split('.').next()?.to_string(); + if SUPPORTED_LANGUAGES.contains(&language.as_str()) { + Some(language) + } else { + None + } } Err(_) => None, } -} +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 0100c71..0bf8643 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,7 +6,7 @@ use i18n::set_locale; mod i18n; rust_i18n::i18n!("locales"); #[derive(Parser, Debug)] -#[clap(version = "0.0.1", author = "Fankai liu ")] +#[clap(version = "0.1.17", author = "Fankai liu ")] struct Opts { #[clap(subcommand)] subcmd: SubCommand, From 9db4e93751ecaa8bd3d9c85243227a4bb4c9c1d3 Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Tue, 7 Nov 2023 19:36:38 +0800 Subject: [PATCH 15/18] update version --- Cargo.lock | 2 +- Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5d00334..44df435 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -798,7 +798,7 @@ checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" [[package]] name = "salvo-cli" -version = "0.1.16" +version = "0.1.17" dependencies = [ "ansi_term", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index 31186f2..3bb2232 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "salvo-cli" -version = "0.1.16" +version = "0.1.17" edition = "2021" authors = ["Fankai Liu liufankai137@outlook.com"] keywords = ["salvo", "cli","template"] From 4b717771c34dc4dc96d8b3bf9460cc48e5ff3d8d Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Tue, 7 Nov 2023 19:54:00 +0800 Subject: [PATCH 16/18] use rust-i18n fallbake --- Cargo.lock | 2 +- Cargo.toml | 2 +- src/i18n.rs | 16 +++------------- src/main.rs | 4 ++-- 4 files changed, 7 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 44df435..f2bccaf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -798,7 +798,7 @@ checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" [[package]] name = "salvo-cli" -version = "0.1.17" +version = "0.1.18" dependencies = [ "ansi_term", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index 3bb2232..7d9d57f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "salvo-cli" -version = "0.1.17" +version = "0.1.18" edition = "2021" authors = ["Fankai Liu liufankai137@outlook.com"] keywords = ["salvo", "cli","template"] diff --git a/src/i18n.rs b/src/i18n.rs index 4cae160..7d3e98d 100644 --- a/src/i18n.rs +++ b/src/i18n.rs @@ -1,8 +1,3 @@ -const SUPPORTED_LANGUAGES: [&str; 17] = [ - "en", "zh_CN", "zh_TW", "fr", "ja", "es", "de", "ru", - "it", "pt", "ko", "no", "is", "uk", "th", "el", "da" -]; - pub fn set_locale() { match get_language() { Some(lang) => { @@ -13,17 +8,12 @@ pub fn set_locale() { } } } - fn get_language() -> Option { match std::env::var("LANG") { Ok(lang) => { - let language = lang.split('.').next()?.to_string(); - if SUPPORTED_LANGUAGES.contains(&language.as_str()) { - Some(language) - } else { - None - } + let language = lang.split('.').next(); + language.map(|s| s.to_string()) } Err(_) => None, } -} \ No newline at end of file +} diff --git a/src/main.rs b/src/main.rs index 0bf8643..6c3714d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,9 +4,9 @@ use clap::Parser; mod utils; use i18n::set_locale; mod i18n; -rust_i18n::i18n!("locales"); +rust_i18n::i18n!("locales", fallback = "en"); #[derive(Parser, Debug)] -#[clap(version = "0.1.17", author = "Fankai liu ")] +#[clap(version = "0.1.18", author = "Fankai liu ")] struct Opts { #[clap(subcommand)] subcmd: SubCommand, From 475e74d7bf9b518171bc30ca9f2bbce3ad3c53f6 Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Thu, 9 Nov 2023 21:54:35 +0800 Subject: [PATCH 17/18] can set the language when using the command --- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/i18n.rs | 26 ++++++++++++++++++++------ src/main.rs | 4 +++- 5 files changed, 77 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f2bccaf..4cc1cda 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -798,7 +798,7 @@ checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" [[package]] name = "salvo-cli" -version = "0.1.18" +version = "0.1.19" dependencies = [ "ansi_term", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index 7d9d57f..e3abfe2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "salvo-cli" -version = "0.1.18" +version = "0.1.19" edition = "2021" authors = ["Fankai Liu liufankai137@outlook.com"] keywords = ["salvo", "cli","template"] diff --git a/README.md b/README.md index b56cc72..0d34a23 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,59 @@ cargo install salvo-cli To create a new Salvo project, use the new command followed by the name of your project: ```bash +//use the local language salvo-cli new project_name + +// Use English +salvo-cli new project_name --lang=en + +// 使用简体中文 +salvo-cli new project_name --lang=zh + +// 使用繁體中文 +salvo-cli new project_name --lang=zh_TW + +// Utilisez le français +salvo-cli new project_name --lang=fr + +// 日本語を使用する +salvo-cli new project_name --lang=ja + +// Usa el español +salvo-cli new project_name --lang=es + +// Verwenden Sie Deutsch +salvo-cli new project_name --lang=de + +// Используйте русский +salvo-cli new project_name --lang=ru + +// Usa l `italiano +salvo-cli new project_name --lang=it + +// Use o português +salvo-cli new project_name --lang=pt + +// 한국어를 사용하십시오 +salvo-cli new project_name --lang=ko + +// Bruk norsk +salvo-cli new project_name --lang=no + +// Notaðu íslensku +salvo-cli new project_name --lang=is + +// Використовуйте українську +salvo-cli new project_name --lang=uk + +// ใช้ภาษาไทย +salvo-cli new project_name --lang=th + +// Χρησιμοποιήστε την ελληνική +salvo-cli new project_name --lang=el + +// Brug dansk +salvo-cli new project_name --lang=da ``` ## Update diff --git a/src/i18n.rs b/src/i18n.rs index 7d3e98d..36a3a5f 100644 --- a/src/i18n.rs +++ b/src/i18n.rs @@ -1,11 +1,25 @@ -pub fn set_locale() { - match get_language() { +const SUPPORTED_LANGUAGES: [&str; 17] = [ + "en", "zh_CN", "zh_TW", "fr", "ja", "es", "de", "ru", "it", "pt", "ko", "no", "is", "uk", "th", + "el", "da", +]; +pub fn set_locale(language: &Option) { + match language { Some(lang) => { - rust_i18n::set_locale(lang.as_str()); - } - None => { - rust_i18n::set_locale("en"); + let lang = if lang == "zh" { "zh_CN" } else { lang }; + if SUPPORTED_LANGUAGES.contains(&lang) { + rust_i18n::set_locale(lang); + } else { + rust_i18n::set_locale("en"); + } } + None => match get_language() { + Some(lang) => { + rust_i18n::set_locale(lang.as_str()); + } + None => { + rust_i18n::set_locale("en"); + } + }, } } fn get_language() -> Option { diff --git a/src/main.rs b/src/main.rs index 6c3714d..e246ea8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,13 +19,15 @@ enum SubCommand { #[derive(Parser, Debug, Clone)] pub struct Project { pub project_name: String, + #[clap(short, long)] + lang: Option, } fn main() -> Result<()> { - set_locale(); utils::print_logo(); let opts: Opts = Opts::parse(); match opts.subcmd { SubCommand::New(project) => { + set_locale(&project.lang); match utils::create_project(project) { Ok(_) => (), Err(e) => utils::error(e.to_string()), From 41407023abbee3915817f0603543bc9bafcccce7 Mon Sep 17 00:00:00 2001 From: Fankai Liu Date: Thu, 9 Nov 2023 22:03:59 +0800 Subject: [PATCH 18/18] update version --- src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index e246ea8..756f66b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,7 +6,7 @@ use i18n::set_locale; mod i18n; rust_i18n::i18n!("locales", fallback = "en"); #[derive(Parser, Debug)] -#[clap(version = "0.1.18", author = "Fankai liu ")] +#[clap(version = "0.1.19", author = "Fankai liu ")] struct Opts { #[clap(subcommand)] subcmd: SubCommand,