feat(search): search feature via modrinth api for current project

This commit is contained in:
RafayAhmad7548 2026-09-01 19:46:24 +05:00
parent 1092071968
commit 10e3ca2efb
Signed by: RafayAhmad
SSH key fingerprint: SHA256:WURX8viobA1uawb4dWM3LqYrY+XPcZcXhAXAlrYdhtE
8 changed files with 226 additions and 32 deletions

View file

@ -43,7 +43,7 @@ impl Create {
std::env::set_current_dir(&project_name)?;
let config_file = tokio::fs::File::create("mcsm.toml").await?;
Ok(Create {
/*project_name,*/
/*project_name,*/
config_file,
version,
loader,
@ -101,21 +101,22 @@ impl LoaderDownloader for VanillaDownloader {
.await?;
if let Some(version) = create.version.clone() {
let version_exists = res
.versions
.iter()
.any(|v| v.id == version);
if !version_exists { return Err("Invalid minecraft version specified".into()) }
}
else {
let version_exists = res.versions.iter().any(|v| v.id == version);
if !version_exists {
return Err("Invalid minecraft version specified".into());
}
} else {
let versions = res
.versions
.iter()
.filter(|version| {
version.version_type == VanillaVersionType::Release ||
(create.show_snapshots && version.version_type == VanillaVersionType::Snapshot) ||
(create.show_betas && version.version_type == VanillaVersionType::OldBeta) ||
(create.show_alphas && version.version_type == VanillaVersionType::OldAlpha)
version.version_type == VanillaVersionType::Release
|| (create.show_snapshots
&& version.version_type == VanillaVersionType::Snapshot)
|| (create.show_betas
&& version.version_type == VanillaVersionType::OldBeta)
|| (create.show_alphas
&& version.version_type == VanillaVersionType::OldAlpha)
})
.collect::<Vec<_>>();
let version_names = versions
@ -140,10 +141,7 @@ impl LoaderDownloader for VanillaDownloader {
let version_detail: VanillaVersionDetail = with_spinner("", "", || async {
let version_detail: VanillaVersionDetail =
reqwest::get(version.url.clone())
.await?
.json()
.await?;
reqwest::get(version.url.clone()).await?.json().await?;
Ok(version_detail)
})
.await?;
@ -215,13 +213,11 @@ impl LoaderDownloader for FabricDownloader {
.await?;
if let Some(version) = create.version.clone() {
let exists = res
.game
.iter()
.any(|game| game.version == version);
if !exists { return Err("Invalid minecraft version specified".into()) }
}
else {
let exists = res.game.iter().any(|game| game.version == version);
if !exists {
return Err("Invalid minecraft version specified".into());
}
} else {
let game_version_names = res
.game
.iter()
@ -243,9 +239,10 @@ impl LoaderDownloader for FabricDownloader {
.loader
.iter()
.any(|loader| loader.version == loader_version);
if !exists { return Err(format!("Invalid {} loader version specified", Self::name()).into()) }
}
else {
if !exists {
return Err(format!("Invalid {} loader version specified", Self::name()).into());
}
} else {
let loader_version_names = res
.loader
.iter()
@ -283,7 +280,10 @@ impl LoaderDownloader for FabricDownloader {
with_spinner(&start_msg, "download finished", || async {
let download_url = format!(
"{}/loader/{}/{}/{}/server/jar",
URL, create.version.as_ref().unwrap(), create.loader_version.as_ref().unwrap(), installer_version
URL,
create.version.as_ref().unwrap(),
create.loader_version.as_ref().unwrap(),
installer_version
);
let res = reqwest::get(download_url).await?;
let mut file = tokio::fs::File::create("server.jar").await?;

View file

@ -1 +1,2 @@
pub mod create;
pub mod search;

97
src/commands/search.rs Normal file
View file

@ -0,0 +1,97 @@
use std::error::Error;
use colored::Colorize;
use serde::Serialize;
use terminal_size;
use textwrap::{Options, fill};
use terminal_size::{terminal_size as get_terminal_size, Width};
use crate::models::{config::Config, search::SearchResult};
#[derive(Serialize)]
struct SearchQueryParams {
query: String,
facets: String,
offset: Option<u32>,
limit: Option<u32>,
}
pub struct Search {
query: String,
}
impl Search {
const BASE_URL: &str = "https://api.modrinth.com/v2";
pub fn new(query: String) -> Self {
Search { query }
}
pub async fn run(&self) -> Result<(), Box<dyn Error>> {
let file_res = tokio::fs::read_to_string("mcsm.toml").await;
if file_res.is_err() {
return Err("current directory is not a mcsm project".into());
}
let config: Config = toml::from_str(&file_res.unwrap())?;
if config.server.loader == "Vanilla" {
return Err("cannot search for mods on Vanilla server".into());
}
let client = reqwest::Client::new();
let search = format!("{}/search", Self::BASE_URL);
let facets = format!(
r#"[["project_type:mod"],["environment!=client_only"],["environment!=singleplayer_only"],["environment!=unknown"],["categories:{}"],["versions:{}"]]"#,
config.server.loader.to_lowercase(),
config.server.version,
);
let params = SearchQueryParams {
query: self.query.clone(),
facets: facets.into(),
offset: None,
limit: None,
};
let res: SearchResult = client
.get(search)
.query(&params)
.send()
.await?
.json()
.await?;
self.print_results(&res);
Ok(())
}
fn print_results(&self, res: &SearchResult) {
println!(
"{}\n",
format!("Found {} result{}", res.total_hits, if res.total_hits == 1 { "" } else { "s" })
.green()
.bold()
);
let width = get_terminal_size().map(|(Width(w), _)| w as usize).unwrap_or(80);
for (i, hit) in res.hits.iter().enumerate() {
let wrapped = fill(
&hit.description,
Options::new(width.saturating_sub(3))
.initial_indent(" ")
.subsequent_indent(" "),
);
println!(
"{} {} {}\n by {}\n{}\n",
format!("{}.", i + 1).bold(),
hit.title.bold(),
format!("({})", hit.slug).cyan(),
hit.author.yellow(),
wrapped,
);
}
}
}