aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKunoiSayami <[email protected]>2025-03-07 20:40:46 +0800
committerKunoiSayami <[email protected]>2025-03-07 20:40:46 +0800
commit2591672ed9934393029cb5097c2d79bdad591c08 (patch)
treea2a8f6f144dbc0c2a4e5c681eb1036a9a6323736
parent58047f90f79b129e445cbf856a23b3a5518c0b12 (diff)
feat(ci): Update workflow file
* chore: Address clippy suggestion Signed-off-by: KunoiSayami <[email protected]>
-rw-r--r--.github/workflows/build-cross.yml36
-rw-r--r--.github/workflows/build.yml151
-rw-r--r--Cargo.lock77
-rw-r--r--Cargo.toml6
-rw-r--r--README.md2
-rw-r--r--src/database.rs1
-rw-r--r--src/datastructures.rs15
-rw-r--r--src/main.rs93
-rw-r--r--src/test.rs2
9 files changed, 183 insertions, 200 deletions
diff --git a/.github/workflows/build-cross.yml b/.github/workflows/build-cross.yml
deleted file mode 100644
index 4d7f548..0000000
--- a/.github/workflows/build-cross.yml
+++ /dev/null
@@ -1,36 +0,0 @@
-name: Build cross binary
-
-on:
- push:
- tags:
- - v**
- pull_request:
-
-jobs:
- build_aarch64:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v3
- - uses: actions-rs/toolchain@v1
- with:
- toolchain: stable
- target: aarch64-unknown-linux-musl
- override: true
- - name: Build aarch 64 binary
- uses: actions-rs/cargo@v1
- with:
- use-cross: true
- command: build
- args: --target aarch64-unknown-linux-musl --release
- - run: mv target/aarch64-unknown-linux-musl/release/cgit-simple-authentication target/aarch64-unknown-linux-musl/release/cgit-simple-authentication_linux_aarch64
- - uses: actions/upload-artifact@v2
- with:
- name: aarch64-artifact
- path: target/aarch64-unknown-linux-musl/release/cgit-simple-authentication_linux_aarch64
- - name: Release
- uses: softprops/action-gh-release@v1
- if: startsWith(github.ref, 'refs/tags/')
- with:
- files: target/aarch64-unknown-linux-musl/release/cgit-simple-authentication_linux_aarch64
- env:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 13cbc6f..dd10b0f 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -1,55 +1,150 @@
-name: Build binary
+name: Build Releases
on:
push:
tags:
- v**
- pull_request:
+
+ workflow_dispatch:
+ branches:
+ - master
+
+env:
+ CARGO_TERM_COLOR: always
jobs:
build:
strategy:
- fail-fast: true
matrix:
job:
- - { os: macos-latest }
- - { os: ubuntu-latest }
-
+ - os: macos-latest
+ - os: ubuntu-latest
name: Build
runs-on: ${{ matrix.job.os }}
+ env:
+ RUST_BACKTRACE: full
+
steps:
- - uses: actions/checkout@v3
- - uses: actions-rs/toolchain@v1
- with:
- profile: minimal
- toolchain: stable
- override: true
- - uses: actions-rs/cargo@v1
+ - uses: actions/checkout@v4
+ - name: Determine Binary Name
+ id: determine-os
+ shell: bash
+ run: |
+ if [ "$RUNNER_OS" == "Linux" ]; then
+ BINARY=cgit-simple-authentication_linux_amd64
+ PROTOC_BINARY=/usr/bin/protoc
+ elif [ "$RUNNER_OS" == "Windows" ]; then
+ BINARY=cgit-simple-authentication_windows_amd64.exe
+ PROTOC_BINARY=./bin/protoc.exe
+ else # macOS
+ #if [ "$(uname --machine)" == "arm64" ]; then
+ BINARY=cgit-simple-authentication_darwin_arm64
+ #else
+ #BINARY=cgit-simple-authentication_darwin_amd64
+ #fi
+ #echo "arch=$(uname --machine)" >> $GITHUB_OUTPUT
+ PROTOC_BINARY=$PWD/bin/protoc
+ fi
+ echo "binary_name=$BINARY" >> $GITHUB_OUTPUT
+ echo "PROTOC=$PROTOC_BINARY" >> $GITHUB_ENV
+ - name: Prepare protobuf
+ id: protobuf_init
+ shell: bash
+ run: |
+ if [ "$RUNNER_OS" == "Linux" ]; then
+ sudo apt-get install -qqy protobuf-compiler
+ else
+ if [ "$RUNNER_OS" == "Windows" ]; then
+ PROTOBUF_REMOTE=https://github.com/protocolbuffers/protobuf/releases/download/v25.6/protoc-25.6-win64.zip
+ else
+ PROTOBUF_REMOTE=https://github.com/protocolbuffers/protobuf/releases/download/v25.6/protoc-25.6-osx-universal_binary.zip
+ fi
+ curl -fL -o protoc.zip $PROTOBUF_REMOTE
+ unzip -qq protoc.zip
+ fi
+ #- name: Environment
+ # run: |
+ # git submodule update --init --recursive
+ - name: Cache Cargo packages
+ id: cache-cargo
+ uses: actions/cache@v4
with:
- command: build
- args: --release
+ key: ${{ runner.os }}-cargo
+ path: |
+ ~/.cargo
+ ~/.rustup
+ $PWD/target
+ - if: ${{ steps.cache-cargo.outputs.cache-hit != 'true' }}
+ name: Update rust
+ run: rustup update
+ - name: Build binary
+ run: |
+ cargo build --profile release
- name: Rename binary
id: rename
shell: bash
+ env:
+ BINARY_NAME: ${{ steps.determine-os.outputs.binary_name }}
run: |
- if [ "$RUNNER_OS" == "Linux" ]; then
- BIN='cgit-simple-authentication_linux_amd64'
- mv target/release/cgit-simple-authentication target/release/$BIN
- elif [ "$RUNNER_OS" == "macOS" ]; then
- BIN='cgit-simple-authentication_darwin_arm64'
- mv target/release/cgit-simple-authentication target/release/$BIN
+ if [ "$RUNNER_OS" == "Windows" ]; then
+ mv target/release/cgit-simple-authentication.exe target/release/$BINARY_NAME
+ else
+ mv target/release/cgit-simple-authentication target/release/$BINARY_NAME
fi
- echo "output_binary_name=target/release/$BIN" >> $GITHUB_ENV
- - uses: actions/upload-artifact@v2
+ echo "bin=target/release/$BINARY_NAME" >> $GITHUB_OUTPUT
+ - uses: actions/[email protected]
+ with:
+ name: ${{ steps.determine-os.outputs.binary_name }}
+ path: target/release/${{ steps.determine-os.outputs.binary_name }}
+
+ - name: Release
+ uses: softprops/action-gh-release@v2
+ if: startsWith(github.ref, 'refs/tags/')
+ with:
+ files: ${{ steps.rename.outputs.bin }}
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+
+ build_aarch64:
+ name: Cross build
+ runs-on: ubuntu-latest
+ env:
+ RUST_BACKTRACE: full
+
+ steps:
+ - uses: actions/checkout@v4
+ #- name: Environment
+ # run: |
+ # git submodule update --init --recursive
+ - name: Cache Cargo packages
+ id: cache-cargo
+ uses: actions/cache@v4
with:
- name: artifact
+ key: ${{ runner.os }}-cargo-cross
path: |
- target/release/cgit-simple-authentication_*
+ ~/.cargo
+ ~/.rustup
+ ~/work/cgit-simple-authentication/cgit-simple-authentication/target
+ - if: ${{ steps.cache-cargo.outputs.cache-hit != 'true' }}
+ name: Update rust
+ run: rustup update && rustup target install aarch64-unknown-linux-musl
+ - name: Install cross
+ run: cargo install cross
+ - name: Build binary
+ env:
+ PROTOC: /usr/bin/protoc
+ run: |
+ cross build --target aarch64-unknown-linux-musl --profile release
+ - run: mv target/aarch64-unknown-linux-musl/release/cgit-simple-authentication target/aarch64-unknown-linux-musl/release/cgit-simple-authentication_linux_aarch64
+ - uses: actions/[email protected]
+ with:
+ name: cgit-simple-authentication_linux_aarch64
+ path: target/aarch64-unknown-linux-musl/release/cgit-simple-authentication_linux_aarch64
- name: Release
- uses: softprops/action-gh-release@v1
+ uses: softprops/action-gh-release@v2
if: startsWith(github.ref, 'refs/tags/')
with:
- files: ${{ env.output_binary_name }}
+ files: target/aarch64-unknown-linux-musl/release/cgit-simple-authentication_linux_aarch64
env:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
diff --git a/Cargo.lock b/Cargo.lock
index 4402466..2e78d2b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -183,7 +183,7 @@ dependencies = [
"bitflags",
"cexpr",
"clang-sys",
- "itertools",
+ "itertools 0.12.1",
"lazy_static",
"lazycell",
"proc-macro2",
@@ -275,17 +275,17 @@ dependencies = [
"cpufeatures",
"env_logger",
"handlebars",
+ "itertools 0.14.0",
"log",
"log4rs",
"pam",
"rand 0.9.0",
- "rand_core 0.9.3",
"redis",
"regex",
"serde",
"serde_json",
"sqlx",
- "tempdir",
+ "tempfile",
"tokio",
"tokio-stream",
"toml",
@@ -664,12 +664,6 @@ dependencies = [
]
[[package]]
-name = "fuchsia-cprng"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba"
-
-[[package]]
name = "futures-channel"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1061,6 +1055,15 @@ dependencies = [
]
[[package]]
+name = "itertools"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
+dependencies = [
+ "either",
+]
+
+[[package]]
name = "itoa"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1529,19 +1532,6 @@ dependencies = [
[[package]]
name = "rand"
-version = "0.4.6"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "552840b97013b1a26992c11eac34bdd778e464601a4c2054b5f0bff7c6761293"
-dependencies = [
- "fuchsia-cprng",
- "libc",
- "rand_core 0.3.1",
- "rdrand",
- "winapi",
-]
-
-[[package]]
-name = "rand"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
@@ -1584,21 +1574,6 @@ dependencies = [
[[package]]
name = "rand_core"
-version = "0.3.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b"
-dependencies = [
- "rand_core 0.4.2",
-]
-
-[[package]]
-name = "rand_core"
-version = "0.4.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc"
-
-[[package]]
-name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
@@ -1616,15 +1591,6 @@ dependencies = [
]
[[package]]
-name = "rdrand"
-version = "0.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2"
-dependencies = [
- "rand_core 0.3.1",
-]
-
-[[package]]
name = "redis"
version = "0.29.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1685,15 +1651,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
[[package]]
-name = "remove_dir_all"
-version = "0.5.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7"
-dependencies = [
- "winapi",
-]
-
-[[package]]
name = "ring"
version = "0.17.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2239,16 +2196,6 @@ dependencies = [
]
[[package]]
-name = "tempdir"
-version = "0.3.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "15f2b5fb00ccdf689e0149d1b1b3c03fead81c2b37735d812fa8bddbbf41b6d8"
-dependencies = [
- "rand 0.4.6",
- "remove_dir_all",
-]
-
-[[package]]
name = "tempfile"
version = "3.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
diff --git a/Cargo.toml b/Cargo.toml
index f613b67..8de3ca4 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -9,7 +9,7 @@ anyhow = "1"
argon2 = "0.5.0"
async-trait = "0.1"
base64 = "0.22"
-clap = "4.0.15"
+clap = "4"
env_logger = "0.11"
handlebars = "6.0"
log = { version = "0.4", features = [
@@ -19,7 +19,6 @@ log = { version = "0.4", features = [
log4rs = "1"
pam = { version = "0.8.0", optional = true }
rand = "0.9"
-rand_core = { version = "0.9", features = ["std"] }
redis = { version = "0.29", features = ["tokio-comp"] }
regex = "1"
serde = { version = "1", features = ["derive"] }
@@ -29,7 +28,8 @@ sqlx = { version = "0.8", features = [
"sqlite",
"runtime-tokio-rustls",
] }
-tempdir = "0.3"
+tempfile = "3"
+itertools = "0.14"
tokio = { version = "1", features = ["full"] }
tokio-stream = "0.1"
toml = "0.8"
diff --git a/README.md b/README.md
index d94063a..0420c85 100644
--- a/README.md
+++ b/README.md
@@ -81,7 +81,7 @@ Most of the ideas come from: https://github.com/varphone/cgit-gogs-auth-filter
[![](https://www.gnu.org/graphics/agplv3-155x51.png)](https://www.gnu.org/licenses/agpl-3.0.txt)
-Copyright (C) 2021-2022 KunoiSayami
+Copyright (C) 2021-2025 KunoiSayami
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version.
diff --git a/src/database.rs b/src/database.rs
index 5ea93c4..8fa537a 100644
--- a/src/database.rs
+++ b/src/database.rs
@@ -93,4 +93,3 @@ pub mod v3 {
#[allow(deprecated)]
pub use v2 as previous;
pub use v3 as current;
-pub use v3::VERSION;
diff --git a/src/datastructures.rs b/src/datastructures.rs
index 1894d33..7f062b3 100644
--- a/src/datastructures.rs
+++ b/src/datastructures.rs
@@ -268,6 +268,7 @@ impl Config {
async fn write_current_timestamp_to_file<P: AsRef<Path>>(path: P) -> Result<()> {
let mut file = tokio::fs::OpenOptions::new()
.create(true)
+ .truncate(true)
.write(true)
.open(path)
.await?;
@@ -390,7 +391,7 @@ impl ProtectSettings {
let context = match context {
Ok(context) => context,
Err(e) => {
- error!("Got error while reading {:?}, {:?}", path, e);
+ error!("Got error while reading {path:?}, {e:?}");
if let std::io::ErrorKind::NotFound = e.kind() {
error!("File not found, did you forget to perform initialization?");
}
@@ -449,7 +450,7 @@ impl ProtectSettings {
if (white_list_mode && value.eq("false")) || (!white_list_mode && value.eq("true"))
{
if last_insert_repo.eq(last_repo) {
- log::warn!("Found duplicate options in repo {}", last_repo);
+ log::warn!("Found duplicate options in repo {last_repo}");
continue;
}
repos.push(last_repo.to_string());
@@ -516,6 +517,7 @@ impl FormData {
self.hash = Default::default();
}
+ #[allow(clippy::borrowed_box)]
pub async fn authorize(&self, authorizer: &Box<dyn Authorizer>) -> Result<bool> {
authorizer.verify(&self.user, &self.password).await
}
@@ -699,10 +701,10 @@ impl From<Config> for WrapConfigure {
#[cfg(not(feature = "pam"))]
fn from(cfg: Config) -> Self {
let authorizer = Box::new(SQLAuthorizer::from(&cfg));
- return Self {
+ Self {
config: cfg,
- authorizer: authorizer,
- };
+ authorizer,
+ }
}
#[cfg(feature = "pam")]
fn from(cfg: Config) -> Self {
@@ -770,6 +772,7 @@ impl WrapConfigure {
Ok(())
}
+ #[allow(clippy::borrowed_box)]
pub(crate) fn get_authorizer(&self) -> &Box<dyn Authorizer> {
&self.authorizer
}
@@ -795,7 +798,7 @@ impl Authorizer for SQLAuthorizer {
.fetch_one(&mut conn)
.await?;
- let parsed_hash = PasswordHash::new(passwd_hash.as_str()).unwrap();
+ let parsed_hash = PasswordHash::new(&passwd_hash).unwrap();
let argon2_alg = Argon2::default();
Ok(argon2_alg
diff --git a/src/main.rs b/src/main.rs
index 268cbe5..f392792 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -26,6 +26,7 @@ use crate::datastructures::{Config, Cookie, FormData, TestSuite, WrapConfigure};
use anyhow::Result;
use clap::{Arg, ArgMatches, Command};
use handlebars::Handlebars;
+use itertools::Itertools as _;
use log4rs::append::file::FileAppender;
use log4rs::config::{Appender, Root};
use log4rs::encode::pattern::PatternEncoder;
@@ -36,7 +37,7 @@ use sqlx::{ConnectOptions, Connection, SqliteConnection};
use std::env;
use std::io::{BufRead, Write};
use std::str::FromStr;
-use tempdir::TempDir;
+use tempfile::TempDir;
use tokio_stream::StreamExt as _;
struct IOModule<R, W> {
@@ -59,13 +60,13 @@ impl<R: BufRead, W: Write> IOModule<R, W> {
let ret = verify_login(&cfg, &data).await;
if let Err(ref e) = ret {
- eprintln!("{:?}", e);
+ eprintln!("{e:?}");
#[cfg(test)]
eprintln!(
"If database locked error occurs frequently, \
please use environment DISK_WAIT_TIME to specify longer time."
);
- log::error!("{:?}", e)
+ log::error!("{e:?}")
}
if ret.unwrap_or(false) {
@@ -76,7 +77,7 @@ impl<R: BufRead, W: Write> IOModule<R, W> {
conn.set_ex::<_, _, String>(
format!("cgit_auth_{}", cookie.get_key()),
cookie.get_body(),
- cfg.get_config().cookie_ttl as u64,
+ cfg.get_config().cookie_ttl,
)
.await?;
@@ -85,7 +86,7 @@ impl<R: BufRead, W: Write> IOModule<R, W> {
let is_secure = matches
.get_one::<String>("https")
.map(|s| s.as_str())
- .map_or(false, |x| matches!(x, "yes" | "on" | "1"));
+ .is_some_and(|x| matches!(x, "yes" | "on" | "1"));
let domain = matches
.get_one::<String>("http-host")
.map(|s| s.as_str())
@@ -100,11 +101,8 @@ impl<R: BufRead, W: Write> IOModule<R, W> {
writeln!(&mut self.writer, "Location: {}", location)?;
writeln!(
&mut self.writer,
- "Set-Cookie: cgit_auth={}; Domain={}; Max-Age={}; HttpOnly{}",
- cookie_value,
- domain,
+ "Set-Cookie: cgit_auth={cookie_value}; Domain={domain}; Max-Age={}; HttpOnly{cookie_suffix}",
cfg.get_config().cookie_ttl * 10,
- cookie_suffix
)?;
} else {
writeln!(&mut self.writer, "Status: 403 Forbidden")?;
@@ -145,7 +143,7 @@ async fn cmd_authenticate_cookie(matches: &ArgMatches, cfg: Config) -> Result<bo
let redis_conn = redis::Client::open("redis://127.0.0.1/")?;
let mut conn = redis_conn.get_multiplexed_async_connection().await?;
- let redis_key = format!("cgit_repo_{}", repo);
+ let redis_key = format!("cgit_repo_{repo}");
if !repo.is_empty() && !conn.exists(&redis_key).await? {
let sql_conn = SqliteConnectOptions::from_str(cfg.get_database_location())?
.read_only(true)
@@ -155,8 +153,7 @@ async fn cmd_authenticate_cookie(matches: &ArgMatches, cfg: Config) -> Result<bo
.await;
if let Err(ref e) = sql_conn {
log::error!(
- "Got error while open sqlite connection: {:?}\nDatabase location: {}",
- e,
+ "Got error while open sqlite connection: {e:?}\nDatabase location: {}",
cfg.get_database_location()
);
}
@@ -173,7 +170,7 @@ async fn cmd_authenticate_cookie(matches: &ArgMatches, cfg: Config) -> Result<bo
}
if let Ok(Some(cookie)) = Cookie::load_from_request(cookies) {
- log::debug!("Cookie is {:?}", &cookie);
+ log::debug!("Cookie is {cookie:?}");
if let Ok(r) = conn
.get::<_, String>(format!("cgit_auth_{}", cookie.get_key()))
.await
@@ -196,7 +193,7 @@ async fn cmd_authenticate_cookie(matches: &ArgMatches, cfg: Config) -> Result<bo
}
}
}
- log::debug!("{:?}", cookie);
+ log::debug!("{cookie:?}");
}
Ok(false)
@@ -262,11 +259,11 @@ async fn cmd_body(matches: &ArgMatches, _cfg: Config) {
action: matches
.get_one::<String>("login-url")
.map(|s| s.as_str())
- .unwrap_or(""),
+ .unwrap_or_default(),
redirect: matches
.get_one::<String>("current-url")
.map(|s| s.as_str())
- .unwrap_or(""),
+ .unwrap_or_default(),
version: env!("CARGO_PKG_VERSION"),
};
handlebars
@@ -279,11 +276,11 @@ async fn cmd_add_user(matches: &ArgMatches, cfg: Config) -> Result<()> {
let user = matches
.get_one::<String>("user")
.map(|s| s.as_str())
- .unwrap_or("");
+ .unwrap_or_default();
let passwd = matches
.get_one::<String>("password")
.map(|s| s.to_string())
- .unwrap_or_else(|| "".to_string());
+ .unwrap_or_default();
if user.is_empty() || passwd.is_empty() {
return Err(anyhow::Error::msg("Invalid user or password length"));
}
@@ -318,7 +315,7 @@ async fn cmd_add_user(matches: &ArgMatches, cfg: Config) -> Result<()> {
.execute(&mut conn)
.await?;
- println!("Insert {} ({}) to database", user, uid);
+ println!("Insert {user} ({uid}) to database");
drop(conn);
@@ -338,12 +335,11 @@ async fn cmd_list_user(cfg: Config) -> Result<()> {
sqlx::query_as::<_, (String,)>(r#"SELECT "user" FROM "accounts""#).fetch(&mut conn);
println!(
- "There is {} user{} in database",
- count,
+ "There is {count} user{} in database",
if count > 1 { "s" } else { "" }
);
while let Some(Ok((row,))) = iter.next().await {
- println!("{}", row)
+ println!("{row}")
}
} else {
println!("There is not user exists.")
@@ -369,7 +365,7 @@ async fn cmd_delete_user(matches: &ArgMatches, cfg: Config) -> Result<()> {
.await?;
if items.is_empty() {
- return Err(anyhow::Error::msg(format!("User {} not found", user)));
+ return Err(anyhow::Error::msg(format!("User {user} not found")));
}
sqlx::query(r#"DELETE FROM "accounts" WHERE "user" = ?"#)
@@ -377,7 +373,7 @@ async fn cmd_delete_user(matches: &ArgMatches, cfg: Config) -> Result<()> {
.execute(&mut conn)
.await?;
- println!("Delete {} from database", user);
+ println!("Delete {user} from database");
cfg.write_database_commit_timestamp().await?;
Ok(())
@@ -407,7 +403,7 @@ async fn cmd_reset_database(matches: &ArgMatches, cfg: Config) -> Result<()> {
}
async fn cmd_upgrade_database(cfg: Config) -> Result<()> {
- let tmp_dir = TempDir::new("rolling")?;
+ let tmp_dir = TempDir::new()?;
let v2_path = tmp_dir.path().join("v2.db");
let v3_path = tmp_dir.path().join("v3.db");
@@ -448,7 +444,7 @@ async fn cmd_upgrade_database(cfg: Config) -> Result<()> {
.bind(uid.as_str())
.execute(&mut conn)
.await?;
- log::debug!("Process user: {} ({})", user, uid);
+ log::debug!("Process user: {user} ({uid})");
}
drop(conn);
@@ -457,8 +453,7 @@ async fn cmd_upgrade_database(cfg: Config) -> Result<()> {
println!("Upgrade database successful");
} else {
eprintln!(
- "Got database version {} but {} required",
- v,
+ "Got database version {v} but {} required",
database::previous::VERSION
)
}
@@ -540,7 +535,7 @@ async fn cmd_repo_user_control(matches: &ArgMatches, cfg: Config, is_delete: boo
.execute(&mut conn)
.await?;
- let redis_key = format!("cgit_repo_{}", repo);
+ let redis_key = format!("cgit_repo_{repo}");
if redis_conn.exists::<_, i32>(&redis_key).await? == 0 {
redis_conn.sadd::<_, _, i32>(&redis_key, users).await?;
} else if is_delete {
@@ -560,7 +555,7 @@ async fn cmd_repo_user_control(matches: &ArgMatches, cfg: Config, is_delete: boo
if is_delete { "from" } else { "to" },
);
} else {
- println!("Clear all users from repository {} ACL", repo);
+ println!("Clear all users from repository {repo} ACL");
}
Ok(())
@@ -585,8 +580,7 @@ async fn cmd_list_repos_acl(arg_matches: &ArgMatches, cfg: Config) -> Result<()>
.unwrap_or((0,));
println!(
- "There is total {} {} in database",
- length,
+ "There is total {length} {} in database",
if length == 1 {
"repository"
} else {
@@ -597,15 +591,7 @@ async fn cmd_list_repos_acl(arg_matches: &ArgMatches, cfg: Config) -> Result<()>
let mut iter =
sqlx::query_as::<_, (String, String)>(r#"SELECT * FROM "repos""#).fetch(&mut conn);
while let Some(Ok((repo, users))) = iter.next().await {
- println!(
- "{}: {}",
- repo,
- users
- .split_whitespace()
- .into_iter()
- .collect::<Vec<&str>>()
- .join(",")
- )
+ println!("{repo}: {}", users.split_whitespace().join(","))
}
} else {
let ret =
@@ -614,17 +600,9 @@ async fn cmd_list_repos_acl(arg_matches: &ArgMatches, cfg: Config) -> Result<()>
.fetch_optional(&mut conn)
.await?;
if let Some((repo, users)) = ret {
- println!(
- "{}: {}",
- repo,
- users
- .split_whitespace()
- .into_iter()
- .collect::<Vec<&str>>()
- .join(",")
- )
+ println!("{repo}: {}", users.split_whitespace().join(","))
} else {
- println!("Repository {} not register in database", repo)
+ println!("Repository {repo} not register in database")
}
}
@@ -805,13 +783,11 @@ fn get_arg_matches(arguments: Option<Vec<&str>>) -> ArgMatches {
.display_order(0),
);
- let matches = if let Some(args) = arguments {
+ if let Some(args) = arguments {
app.get_matches_from(args)
} else {
app.get_matches()
- };
-
- matches
+ }
}
fn process_arguments() -> Result<()> {
@@ -839,8 +815,7 @@ fn main() -> Result<()> {
Ok(f) => f,
Err(e) => {
return Err(anyhow::Error::msg(format!(
- "Got error while append to {}: {:?}",
- &logfile_path, e
+ "Got error while append to {logfile_path}: {e:?}",
)));
}
};
@@ -865,13 +840,13 @@ fn main() -> Result<()> {
"{}",
env::args()
.enumerate()
- .map(|(nth, arg)| format!("[{}]={}", nth, arg))
+ .map(|(nth, arg)| format!("[{nth}]={arg}"))
.collect::<Vec<String>>()
.join(" ")
);
if let Err(e) = process_arguments() {
- log::error!("{:?}", e);
+ log::error!("{e:?}");
};
Ok(())
diff --git a/src/test.rs b/src/test.rs
index 54435e5..3d54d71 100644
--- a/src/test.rs
+++ b/src/test.rs
@@ -312,7 +312,7 @@ mod core {
#[test]
fn test_protected_repo_parser() {
- let tmpdir = tempdir::TempDir::new("test").unwrap();
+ let tmpdir = tempfile::TempDir::new().unwrap();
let another_file_path = format!(
"include={}/REPO_SETTING # TEST\ncgit-simple-auth-protect=part",