Skip to content

Commit

Permalink
refactor: move common args of run in struct CommonArgs
Browse files Browse the repository at this point in the history
There are some common args in `run` and related subcommands `fight`
or coming `copilot`, so move them in a struct `CommonArgs` to avoid
repeating.
  • Loading branch information
wangl-cc committed Nov 25, 2023
1 parent 430e65b commit 256df5b
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 100 deletions.
103 changes: 30 additions & 73 deletions maa-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,66 +187,19 @@ enum SubCommand {
/// The task file must be in the TOML, YAML or JSON format.
#[arg(verbatim_doc_comment)]
task: String,
/// ADB serial number of device or MaaTools address set in PlayCover
///
/// By default, MaaCore connects to game with ADB,
/// and this parameter is the serial number of the device
/// (default to `emulator-5554` if not specified here and not set in config file).
/// And if you want to use PlayCover,
/// you need to set the connection type to PlayCover in the config file
/// and then you can specify the address of MaaTools here.
#[arg(short, long, verbatim_doc_comment)]
addr: Option<String>,
/// Load resources from the config directory
///
/// By default, MaaCore loads resources from the resource installed with MaaCore.
/// If you want to modify some configuration of MaaCore or you want to use your own resources,
/// you can use this option to load resources from the `resource` directory,
/// which is a subdirectory of the config directory.
///
/// This option can also be enabled by setting the value of the key `user_resource` to true
/// in the asst configure file `$MAA_CONFIG_DIR/asst.toml`.
///
/// Note:
/// CLI will load resources shipped with MaaCore firstly,
/// then some client specific or platform specific when needed,
/// lastly, it will load resources from the config directory.
/// MaaCore will overwrite the resources loaded before,
/// if there are some resources with the same name.
/// Use at your own risk!
#[arg(long, verbatim_doc_comment)]
user_resource: bool,
/// Run tasks in batch mode
///
/// If there are some input parameters in the task file,
/// some prompts will be displayed to ask for input.
/// In batch mode, the prompts will be skipped,
/// and parameters will be set to default values.
#[arg(short, long, verbatim_doc_comment)]
batch: bool,
/// Parse the your config but do not connect to the game
///
/// This option is useful when you want to check your config file.
/// It will parse your config file and set the log level to debug.
/// If there are some errors in your config file,
/// it will print the error message and exit.
#[arg(long, verbatim_doc_comment)]
dry_run: bool,
#[command(flatten)]
common: run::CommonArgs,
},
/// Run fight task
Fight {
#[arg(short, long)]
addr: Option<String>,
#[arg(long)]
user_resource: bool,
#[arg(short, long)]
batch: bool,
/// Run startup task before the fight
#[arg(long)]
startup: bool,
/// Close the game after the fight
#[arg(long)]
closedown: bool,
#[command(flatten)]
common: run::CommonArgs,
},
/// List all available tasks
List,
Expand Down Expand Up @@ -375,20 +328,12 @@ fn main() -> Result<()> {
println!("MaaCore {}", run::core_version(&proj_dirs)?);
}
},
SubCommand::Run {
task,
addr,
user_resource,
batch,
dry_run,
} => run::run(&proj_dirs, task, addr, user_resource, batch, dry_run)?,
SubCommand::Run { task, common } => run::run(&proj_dirs, task, common)?,
SubCommand::Fight {
addr,
user_resource,
batch,
startup,
closedown,
} => run::fight::fight(&proj_dirs, addr, user_resource, batch, startup, closedown)?,
common,
} => run::fight(&proj_dirs, startup, closedown, common)?,
SubCommand::List => {
let task_dir = proj_dirs.config().join("tasks");
if !task_dir.exists() {
Expand Down Expand Up @@ -589,26 +534,34 @@ mod test {
CLI::parse_from(["maa", "run", "task"]).command,
SubCommand::Run {
task,
addr: None,
user_resource: false,
batch: false,
dry_run: false,
common: run::CommonArgs {
addr: None,
user_resource: false,
batch: false,
dry_run: false,
},
} if task == "task"
));

assert!(matches!(
CLI::parse_from(["maa", "run", "task", "-a", "addr"]).command,
SubCommand::Run {
task,
addr: Some(addr),
common: run::CommonArgs {
addr: Some(addr),
..
},
..
} if task == "task" && addr == "addr"
));
assert!(matches!(
CLI::parse_from(["maa", "run", "task", "--addr", "addr"]).command,
SubCommand::Run {
task,
addr: Some(addr),
common: run::CommonArgs {
addr: Some(addr),
..
},
..
} if task == "task" && addr == "addr"
));
Expand All @@ -617,7 +570,10 @@ mod test {
CLI::parse_from(["maa", "run", "task", "--user-resource"]).command,
SubCommand::Run {
task,
user_resource: true,
common: run::CommonArgs {
user_resource: true,
..
},
..
} if task == "task"
));
Expand All @@ -626,7 +582,10 @@ mod test {
CLI::parse_from(["maa", "run", "task", "--batch"]).command,
SubCommand::Run {
task,
batch: true,
common: run::CommonArgs {
batch: true,
..
},
..
} if task == "task"
));
Expand All @@ -637,11 +596,9 @@ mod test {
assert!(matches!(
CLI::parse_from(["maa", "fight"]).command,
SubCommand::Fight {
addr: None,
user_resource: false,
batch: false,
startup: false,
closedown: false,
..
}
));

Expand Down
19 changes: 7 additions & 12 deletions maa-cli/src/run/fight.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,17 @@
use crate::{
config::task::{
default_variants, task_type::TaskType, value::input::Input, Strategy, Task, TaskConfig,
Value,
default_variants,
task_type::TaskType,
value::input::{BoolInput, Input, Select},
Strategy, Task, TaskConfig, Value,
},
dirs::Dirs,
object,
};

use super::{run, Result};
use super::{run, CommonArgs, Result};

pub fn fight(
dirs: &Dirs,
addr: Option<String>,
user_resource: bool,
batch: bool,
startup: bool,
closedown: bool,
) -> Result<()> {
pub fn fight(dirs: &Dirs, startup: bool, closedown: bool, common: CommonArgs) -> Result<()> {
let mut task_config = TaskConfig::new();

if startup {
Expand Down Expand Up @@ -50,5 +45,5 @@ pub fn fight(
));
}

run(dirs, task_config, addr, user_resource, batch, false)
run(dirs, task_config, common)
}
74 changes: 59 additions & 15 deletions maa-cli/src/run/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
mod message;
use message::callback;

pub mod fight;
mod fight;
pub use fight::fight;

use crate::{
config::{
Expand All @@ -22,6 +23,7 @@ use crate::{
use std::path::PathBuf;

use anyhow::{anyhow, bail, Context, Result};
use clap::Parser;
use maa_sys::Assistant;

pub enum CLITask {
Expand All @@ -41,20 +43,62 @@ impl From<String> for CLITask {
}
}

pub fn run(
dirs: &Dirs,
task: impl Into<CLITask>,
addr: Option<String>,
user_resource: bool,
batch: bool,
dryrun: bool,
) -> Result<()> {
if dryrun {
#[derive(Parser, Default)]
pub struct CommonArgs {
/// ADB serial number of device or MaaTools address set in PlayCover
///
/// By default, MaaCore connects to game with ADB,
/// and this parameter is the serial number of the device
/// (default to `emulator-5554` if not specified here and not set in config file).
/// And if you want to use PlayCover,
/// you need to set the connection type to PlayCover in the config file
/// and then you can specify the address of MaaTools here.
#[arg(short, long, verbatim_doc_comment)]
pub addr: Option<String>,
/// Load resources from the config directory
///
/// By default, MaaCore loads resources from the resource installed with MaaCore.
/// If you want to modify some configuration of MaaCore or you want to use your own resources,
/// you can use this option to load resources from the `resource` directory,
/// which is a subdirectory of the config directory.
///
/// This option can also be enabled by setting the value of the key `user_resource` to true
/// in the asst configure file `$MAA_CONFIG_DIR/asst.toml`.
///
/// Note:
/// CLI will load resources shipped with MaaCore firstly,
/// then some client specific or platform specific when needed,
/// lastly, it will load resources from the config directory.
/// MaaCore will overwrite the resources loaded before,
/// if there are some resources with the same name.
/// Use at your own risk!
#[arg(long, verbatim_doc_comment)]
pub user_resource: bool,
/// Run tasks in batch mode
///
/// If there are some input parameters in the task file,
/// some prompts will be displayed to ask for input.
/// In batch mode, the prompts will be skipped,
/// and parameters will be set to default values.
#[arg(short, long, verbatim_doc_comment)]
pub batch: bool,
/// Parse the your config but do not connect to the game
///
/// This option is useful when you want to check your config file.
/// It will parse your config file and set the log level to debug.
/// If there are some errors in your config file,
/// it will print the error message and exit.
#[arg(long, verbatim_doc_comment)]
pub dry_run: bool,
}

pub fn run(dirs: &Dirs, task: impl Into<CLITask>, args: CommonArgs) -> Result<()> {
if args.dry_run {
unsafe { set_level(LogLevel::Debug) };
debug!("Dryrun mode!");
}

if batch {
if args.batch {
unsafe { enable_batch_mode() }
debug!("Running in batch mode!");
}
Expand Down Expand Up @@ -89,7 +133,7 @@ pub fn run(
device,
config,
} => {
let device = addr.unwrap_or(device);
let device = args.addr.unwrap_or(device);
debug!("Connect to device via ADB");
debug!("adb_path:", &adb_path);
debug!("device:", &device);
Expand All @@ -98,7 +142,7 @@ pub fn run(
}
Connection::PlayTools { address, config } => {
playtools = true;
let address = addr.unwrap_or(address);
let address = args.addr.unwrap_or(address);
debug!("Setting address to", &address);
debug!("Setting config to", &config);
(String::new(), address, config)
Expand Down Expand Up @@ -284,7 +328,7 @@ pub fn run(
}

// User resource in config directory
if user_resource || asst_config.user_resource {
if args.user_resource || asst_config.user_resource {
if let Some(path) = process_resource_dir(config_dir.join("resource")) {
resource_dirs.push(path);
}
Expand Down Expand Up @@ -352,7 +396,7 @@ pub fn run(
.context("Failed to set instance option `kill_adb_on_exit`!")?;
}

if !dryrun {
if !args.dry_run {
if start_app {
app.as_ref().unwrap().open()?;
std::thread::sleep(std::time::Duration::from_secs(5));
Expand Down

0 comments on commit 256df5b

Please sign in to comment.