Skip to content

Commit

Permalink
Merge pull request #29 from trash-pandy/feature/clap-derive
Browse files Browse the repository at this point in the history
Switch all clap usage to derive style
  • Loading branch information
TheAlan404 authored Sep 12, 2023
2 parents 0c77bd1 + bb99cff commit ef76d39
Show file tree
Hide file tree
Showing 27 changed files with 346 additions and 347 deletions.
21 changes: 21 additions & 0 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ opt-level = "s"

[dependencies]
anyhow = "1.0"
clap = "4.3"
clap = { version = "4.3", features = [ "derive" ] }
console = "0.15"
dialoguer = "0.10"
futures = "0.3"
Expand Down
17 changes: 8 additions & 9 deletions src/commands/add/mod.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
use anyhow::Result;
use clap::{ArgMatches, Command};

mod modrinth;

pub fn cli() -> Command {
Command::new("add")
.about("Add a plugin/mod/datapack")
.subcommand(modrinth::cli())
#[derive(clap::Subcommand)]
pub enum Commands {
/// Add from modrinth
#[command(alias = "mr")]
Modrinth(modrinth::Args),
}

pub async fn run(matches: &ArgMatches) -> Result<()> {
match matches.subcommand() {
Some(("modrinth" | "mr", sub_matches)) => modrinth::run(sub_matches).await?,
_ => unreachable!(),
pub async fn run(args: Commands) -> Result<()> {
match args {
Commands::Modrinth(args) => modrinth::run(args).await?,
}
Ok(())
}
74 changes: 47 additions & 27 deletions src/commands/add/modrinth.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,24 @@
use anyhow::{Context, Result, bail};
use clap::{arg, ArgMatches, Command};
use anyhow::{bail, Context, Result};
use console::style;
use dialoguer::{theme::ColorfulTheme, Input, Select};

use crate::{
create_http_client,
model::{Downloadable, Server, SoftwareType}, sources::modrinth, util::SelectItem,
model::{Downloadable, Server, SoftwareType},
sources::modrinth,
util::SelectItem,
};

pub fn cli() -> Command {
Command::new("modrinth")
.about("Add from modrinth")
.visible_alias("mr")
.arg(arg!(<search>...).required(false))
#[derive(clap::Args)]
pub struct Args {
search: Option<String>,
}

pub async fn run(matches: &ArgMatches) -> Result<()> {
pub async fn run(args: Args) -> Result<()> {
let mut server = Server::load().context("Failed to load server.toml")?;
let http_client = create_http_client()?;

let query = if let Some(s) = matches.get_one::<String>("search") {
let query = if let Some(s) = args.search {
s.to_owned()

Check warning on line 22 in src/commands/add/modrinth.rs

View workflow job for this annotation

GitHub Actions / clippy

implicitly cloning a `String` by calling `to_owned` on its dereferenced type

warning: implicitly cloning a `String` by calling `to_owned` on its dereferenced type --> src/commands/add/modrinth.rs:22:9 | 22 | s.to_owned() | ^^^^^^^^^^^^ help: consider using: `s.clone()` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#implicit_clone = note: `#[warn(clippy::implicit_clone)]` implied by `#[warn(clippy::pedantic)]`
} else {
Input::with_theme(&ColorfulTheme::default())
Expand All @@ -36,14 +35,28 @@ pub async fn run(matches: &ArgMatches) -> Result<()> {
bail!("No modrinth projects found for query '{query}'");
}

let items = projects.iter().map(|p| {
SelectItem(p, format!("{} {} [{}]\n{s:w$}{}", match p.project_type.as_str() {
"mod" => "(mod)",
"datapack" => "( dp)",
"modpack" => "(mrp)",
_ => "( ? )",
}, p.title, p.slug, p.description, s = " ", w = 10))
}).collect::<Vec<_>>();
let items = projects
.iter()
.map(|p| {
SelectItem(
p,
format!(
"{} {} [{}]\n{s:w$}{}",
match p.project_type.as_str() {
"mod" => "(mod)",
"datapack" => "( dp)",
"modpack" => "(mrp)",
_ => "( ? )",
},
p.title,
p.slug,
p.description,
s = " ",
w = 10
),
)
})
.collect::<Vec<_>>();

let idx = Select::with_theme(&ColorfulTheme::default())
.with_prompt("Which project?")
Expand Down Expand Up @@ -83,7 +96,8 @@ pub async fn run(matches: &ArgMatches) -> Result<()> {
.with_prompt("Import as...")
.default(0)
.items(&["Datapack", "Mod/Plugin"])
.interact()? {
.interact()?
{
0 => "datapack",
1 => "mod",
_ => unreachable!(),
Expand All @@ -98,7 +112,10 @@ pub async fn run(matches: &ArgMatches) -> Result<()> {
todo!("Modpack importing currently unsupported")
}
"mod" => {
let addon = Downloadable::Modrinth { id: project.slug.clone(), version: version.id.clone() };
let addon = Downloadable::Modrinth {
id: project.slug.clone(),
version: version.id.clone(),
};

let is_plugin = match server.jar.get_software_type() {
SoftwareType::Modded => false,
Expand All @@ -112,28 +129,31 @@ pub async fn run(matches: &ArgMatches) -> Result<()> {
== 0
}
};

if is_plugin {
server.plugins.push(addon);
} else {
server.mods.push(addon);
}

server.save()?;

server.refresh_markdown(&http_client).await?;

println!(" > Added {} from modrinth", project.title);
}
"datapack" => {
let addon = Downloadable::Modrinth { id: project.slug.clone(), version: version.id.clone() };
let addon = Downloadable::Modrinth {
id: project.slug.clone(),
version: version.id.clone(),
};

let world_name = server.add_datapack(addon)?;

server.save()?;

server.refresh_markdown(&http_client).await?;

println!(
" > {} {} {} {world_name}{}",
style("Datapack ").green(),
Expand Down
45 changes: 22 additions & 23 deletions src/commands/build.rs
Original file line number Diff line number Diff line change
@@ -1,40 +1,39 @@
use std::path::PathBuf;

use anyhow::{Context, Result};
use clap::{arg, value_parser, ArgMatches, Command};

use crate::{core::BuildContext, create_http_client, model::{Server, Lockfile, Network}};

pub fn cli() -> Command {
Command::new("build")
.about("Build using server.toml configuration")
.arg(
arg!(-o --output [FILE] "The output directory for the server")
.value_parser(value_parser!(PathBuf)),
)
.arg(arg!(--skip [stages] "Skip some stages").value_delimiter(','))
.arg(arg!(--force "Don't skip downloading already downloaded jars"))

use crate::{
core::BuildContext,
create_http_client,
model::{Lockfile, Network, Server},
};

#[derive(clap::Args)]
pub struct Args {
/// The output directory for the server
#[arg(short, long, value_name = "file")]
output: Option<PathBuf>,
/// Skip some stages
#[arg(long, value_name = "stages")]
skip: Vec<String>,
#[arg(long)]
/// Don't skip downloading already downloaded jars
force: bool,
}

pub async fn run(matches: &ArgMatches) -> Result<BuildContext> {
pub async fn run(args: Args) -> Result<BuildContext> {
let server = Server::load().context("Failed to load server.toml")?;
let network = Network::load()?;
let http_client = create_http_client()?;

let default_output = server.path.join("server");
let output_dir = matches
.get_one::<PathBuf>("output")
.unwrap_or(&default_output)
.clone();
let output_dir = args.output.unwrap_or(default_output);

let lockfile = Lockfile::get_lockfile(&output_dir)?;

let force = matches.get_flag("force");
let force = args.force;

let skip_stages = matches
.get_many::<String>("skip")
.map(|o| o.cloned().collect::<Vec<String>>())
.unwrap_or(vec![]);
let skip_stages = args.skip;

std::fs::create_dir_all(&output_dir).context("Failed to create output directory")?;

Expand Down
7 changes: 0 additions & 7 deletions src/commands/eject.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
use std::fs;

use anyhow::{Context, Result};
use clap::Command;
use console::style;
use dialoguer::{theme::ColorfulTheme, Input};

use crate::model::Server;

pub fn cli() -> Command {
Command::new("eject")
.hide(true)
.about("Eject - remove everything related to mcman")
}

#[allow(unused_must_use)]
pub fn run() -> Result<()> {
let server = Server::load().context("Failed to load server.toml")?;
Expand Down
7 changes: 1 addition & 6 deletions src/commands/env/docker.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
use anyhow::{Context, Result};
use clap::{ArgMatches, Command};
use console::style;

use crate::{
model::Server,
util::env::{write_dockerfile, write_dockerignore},
};

pub fn cli() -> Command {
Command::new("docker").about("Write the default Dockerfile and .dockerignore")
}

pub fn run(_matches: &ArgMatches) -> Result<()> {
pub fn run() -> Result<()> {
let server = Server::load().context("Failed to load server.toml")?;

write_dockerfile(&server.path).context("writing Dockerfile")?;
Expand Down
7 changes: 1 addition & 6 deletions src/commands/env/gitignore.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
use anyhow::Result;
use clap::{ArgMatches, Command};
use console::style;

use crate::util::env::write_gitignore;

pub fn cli() -> Command {
Command::new("gitignore").about("Modify the gitignore")
}

pub fn run(_matches: &ArgMatches) -> Result<()> {
pub fn run() -> Result<()> {
let path = write_gitignore()?;

println!(
Expand Down
24 changes: 10 additions & 14 deletions src/commands/env/mod.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
use anyhow::Result;
use clap::{ArgMatches, Command};

mod docker;
mod gitignore;

pub fn cli() -> Command {
Command::new("env")
.about("Helpers for setting up the environment")
.subcommand_required(true)
.arg_required_else_help(true)
.subcommand(gitignore::cli())
.subcommand(docker::cli())
#[derive(clap::Subcommand)]
pub enum Commands {
/// Modify the gitignore
Gitignore,
/// Write the default Dockerfile and .dockerignore
Docker,
}

pub fn run(matches: &ArgMatches) -> Result<()> {
match matches.subcommand() {
Some(("gitignore", sub_matches)) => gitignore::run(sub_matches)?,
Some(("docker", sub_matches)) => docker::run(sub_matches)?,
_ => unreachable!(),
pub fn run(commands: Commands) -> Result<()> {

Check warning on line 14 in src/commands/env/mod.rs

View workflow job for this annotation

GitHub Actions / clippy

this argument is passed by value, but not consumed in the function body

warning: this argument is passed by value, but not consumed in the function body --> src/commands/env/mod.rs:14:22 | 14 | pub fn run(commands: Commands) -> Result<()> { | ^^^^^^^^ help: consider taking a reference instead: `&Commands` | help: consider marking this type as `Copy` --> src/commands/env/mod.rs:7:1 | 7 | pub enum Commands { | ^^^^^^^^^^^^^^^^^ = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_value = note: `#[warn(clippy::needless_pass_by_value)]` implied by `#[warn(clippy::pedantic)]`
match commands {
Commands::Gitignore => gitignore::run(),
Commands::Docker => docker::run(),
}
Ok(())
}
Loading

0 comments on commit ef76d39

Please sign in to comment.