Skip to content

Commit

Permalink
refactor: 引入 clap 处理环境变量和命令行参数 (#119)
Browse files Browse the repository at this point in the history
  • Loading branch information
amtoaer authored Jun 8, 2024
1 parent 1744f86 commit 4818e62
Show file tree
Hide file tree
Showing 7 changed files with 77 additions and 59 deletions.
45 changes: 23 additions & 22 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

37 changes: 19 additions & 18 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,26 @@ publish = false
bili_sync_entity = { path = "crates/bili_sync_entity" }
bili_sync_migration = { path = "crates/bili_sync_migration" }

anyhow = { version = "1.0.81", features = ["backtrace"] }
arc-swap = { version = "1.7", features = ["serde"] }
async-std = { version = "1", features = ["attributes", "tokio1"] }
anyhow = { version = "1.0.86", features = ["backtrace"] }
arc-swap = { version = "1.7.1", features = ["serde"] }
async-std = { version = "1.12.0", features = ["attributes", "tokio1"] }
async-stream = "0.3.5"
chrono = { version = "0.4.35", features = ["serde"] }
cookie = "0.18.0"
chrono = { version = "0.4.38", features = ["serde"] }
clap = { version = "4.5.6", features = ["env"] }
cookie = "0.18.1"
dirs = "5.0.1"
filenamify = "0.1.0"
float-ord = "0.3.2"
futures = "0.3.30"
handlebars = "5.1.2"
hex = "0.4.3"
log = "0.4.21"
memchr = "2.5.0"
memchr = "2.7.2"
once_cell = "1.19.0"
prost = "0.12.4"
prost = "0.12.6"
quick-xml = { version = "0.31.0", features = ["async-tokio"] }
rand = "0.8.5"
regex = "1.10.3"
regex = "1.10.4"
reqwest = { version = "0.12.4", features = [
"charset",
"cookies",
Expand All @@ -44,20 +45,20 @@ reqwest = { version = "0.12.4", features = [
"stream",
], default-features = false }
rsa = { version = "0.9.6", features = ["sha2"] }
sea-orm = { version = "0.12", features = [
sea-orm = { version = "0.12.15", features = [
"macros",
"runtime-tokio-rustls",
"sqlx-sqlite",
] }
sea-orm-migration = { version = "0.12.0", features = [] }
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0"
strum = { version = "0.26", features = ["derive"] }
thiserror = "1.0.58"
tokio = { version = "1", features = ["full"] }
toml = "0.8.12"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["chrono"] }
sea-orm-migration = { version = "0.12.15", features = [] }
serde = { version = "1.0.203", features = ["derive"] }
serde_json = "1.0.117"
strum = { version = "0.26.2", features = ["derive"] }
thiserror = "1.0.61"
tokio = { version = "1.38.0", features = ["full"] }
toml = "0.8.14"
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18", features = ["chrono"] }

[profile.release]
strip = true
Expand Down
1 change: 1 addition & 0 deletions crates/bili_sync/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ async-stream = { workspace = true }
bili_sync_entity = { workspace = true }
bili_sync_migration = { workspace = true }
chrono = { workspace = true }
clap = { workspace = true }
cookie = { workspace = true }
dirs = { workspace = true }
filenamify = { workspace = true }
Expand Down
14 changes: 14 additions & 0 deletions crates/bili_sync/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ pub static CONFIG: Lazy<Config> = Lazy::new(|| {
config
});

pub static ARGS: Lazy<Args> = Lazy::new(Args::parse);

pub static CONFIG_DIR: Lazy<PathBuf> =
Lazy::new(|| dirs::config_dir().expect("No config path found").join("bili-sync"));

Expand Down Expand Up @@ -138,3 +140,15 @@ impl Config {
Ok(())
}
}

use clap::Parser;

#[derive(Parser)]
#[command(version, about, long_about = None)]
pub struct Args {
#[arg(short, long, env = "SCAN_ONLY")]
pub scan_only: bool,

#[arg(short, long, default_value = "None,bili_sync=info", env = "RUST_LOG")]
pub log_level: String,
}
8 changes: 2 additions & 6 deletions crates/bili_sync/src/core/command.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::collections::HashMap;
use std::env::{args, var};
use std::path::{Path, PathBuf};
use std::pin::Pin;

Expand All @@ -8,7 +7,6 @@ use bili_sync_entity::{favorite, page, video};
use filenamify::filenamify;
use futures::stream::{FuturesOrdered, FuturesUnordered};
use futures::{pin_mut, Future, StreamExt};
use once_cell::sync::Lazy;
use sea_orm::entity::prelude::*;
use sea_orm::ActiveValue::Set;
use sea_orm::TransactionTrait;
Expand All @@ -17,7 +15,7 @@ use tokio::fs;
use tokio::sync::{Mutex, Semaphore};

use crate::bilibili::{BestStream, BiliClient, BiliError, Dimension, FavoriteList, PageInfo, Video};
use crate::config::CONFIG;
use crate::config::{ARGS, CONFIG};
use crate::core::status::{PageStatus, VideoStatus};
use crate::core::utils::{
create_video_pages, create_videos, exist_labels, filter_unfilled_videos, handle_favorite_info, total_video_count,
Expand All @@ -26,8 +24,6 @@ use crate::core::utils::{
use crate::downloader::Downloader;
use crate::error::{DownloadAbortError, ProcessPageError};

pub static SCAN_ONLY: Lazy<bool> = Lazy::new(|| var("SCAN_ONLY").is_ok() || args().any(|arg| arg == "--scan-only"));

/// 处理某个收藏夹,首先刷新收藏夹信息,然后下载收藏夹中未下载成功的视频
pub async fn process_favorite_list(
bili_client: &BiliClient,
Expand All @@ -37,7 +33,7 @@ pub async fn process_favorite_list(
) -> Result<()> {
let favorite_model = refresh_favorite_list(bili_client, fid, path, connection).await?;
let favorite_model = fetch_video_details(bili_client, favorite_model, connection).await?;
if *SCAN_ONLY {
if ARGS.scan_only {
warn!("已开启仅扫描模式,跳过视频下载...");
return Ok(());
}
Expand Down
12 changes: 12 additions & 0 deletions crates/bili_sync/src/core/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use sea_orm::ActiveValue::Set;
use sea_orm::QuerySelect;
use serde_json::json;
use tokio::io::AsyncWriteExt;
use tracing_subscriber::util::SubscriberInitExt;

use crate::bilibili::{FavoriteListInfo, PageInfo, VideoInfo};
use crate::config::{NFOTimeType, CONFIG};
Expand Down Expand Up @@ -482,6 +483,17 @@ impl<'a> NFOSerializer<'a> {
}
}

pub fn init_logger(log_level: &str) {
tracing_subscriber::fmt::Subscriber::builder()
.with_env_filter(tracing_subscriber::EnvFilter::builder().parse_lossy(log_level))
.with_timer(tracing_subscriber::fmt::time::ChronoLocal::new(
"%Y-%m-%d %H:%M:%S%.3f".to_owned(),
))
.finish()
.try_init()
.expect("初始化日志失败");
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
19 changes: 6 additions & 13 deletions crates/bili_sync/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,27 +10,20 @@ mod error;

use std::time::Duration;

use config::ARGS;
use once_cell::sync::Lazy;
use tokio::time;
use tracing_subscriber::util::SubscriberInitExt;

use crate::bilibili::BiliClient;
use crate::config::CONFIG;
use crate::core::command::{process_favorite_list, SCAN_ONLY};
use crate::core::command::process_favorite_list;
use crate::core::utils::init_logger;
use crate::database::{database_connection, migrate_database};

#[tokio::main]
async fn main() -> ! {
let default_log_level = std::env::var("RUST_LOG").unwrap_or("None,bili_sync=info".to_owned());
tracing_subscriber::fmt::Subscriber::builder()
.with_env_filter(tracing_subscriber::EnvFilter::builder().parse_lossy(default_log_level))
.with_timer(tracing_subscriber::fmt::time::ChronoLocal::new(
"%Y-%m-%d %H:%M:%S%.3f".to_owned(),
))
.finish()
.try_init()
.expect("初始化日志失败");
Lazy::force(&SCAN_ONLY);
async fn main() {
Lazy::force(&ARGS);
init_logger(&ARGS.log_level);
Lazy::force(&CONFIG);
let mut anchor = chrono::Local::now().date_naive();
let bili_client = BiliClient::new();
Expand Down

0 comments on commit 4818e62

Please sign in to comment.