Compare commits

..

6 Commits

10 changed files with 476 additions and 619 deletions

1
.gitignore vendored
View File

@ -1 +1,2 @@
/instance-example
/target

110
Cargo.lock generated
View File

@ -11,6 +11,15 @@ dependencies = [
"memchr",
]
[[package]]
name = "ansi_term"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b"
dependencies = [
"winapi",
]
[[package]]
name = "anyhow"
version = "1.0.47"
@ -78,41 +87,17 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "clap"
version = "3.2.20"
version = "2.33.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b71c3ce99b7611011217b366d923f1d0a7e07a92bb2dbf1e84508c673ca3bd"
checksum = "37e58ac78573c40708d45522f0d80fa2f01cc4f9b4e2bf749807255454312002"
dependencies = [
"ansi_term",
"atty",
"bitflags",
"clap_derive",
"clap_lex",
"indexmap",
"once_cell",
"strsim",
"termcolor",
"textwrap",
]
[[package]]
name = "clap_derive"
version = "3.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea0c8bce528c4be4da13ea6fead8965e95b6073585a2f05204bd8f4119f82a65"
dependencies = [
"heck",
"proc-macro-error",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2850f2f5a82cbf437dd5af4d49848fbdfc27c157c3d010345776f952765261c5"
dependencies = [
"os_str_bytes",
"unicode-width",
"vec_map",
]
[[package]]
@ -339,9 +324,12 @@ checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"
[[package]]
name = "heck"
version = "0.4.0"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9"
checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c"
dependencies = [
"unicode-segmentation",
]
[[package]]
name = "hermit-abi"
@ -357,7 +345,6 @@ name = "hopper"
version = "0.1.0"
dependencies = [
"anyhow",
"clap",
"confy",
"console",
"dialoguer",
@ -368,7 +355,9 @@ dependencies = [
"reqwest",
"serde",
"serde_json",
"structopt",
"tokio",
"toml",
]
[[package]]
@ -626,9 +615,9 @@ checksum = "17b02fc0ff9a9e4b35b3342880f48e896ebf69f2967921fe8646bf5b7125956a"
[[package]]
name = "once_cell"
version = "1.14.0"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f7254b99e31cad77da24b08ebf628882739a608578bb1bcdfc1f9c21260d7c0"
checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56"
[[package]]
name = "openssl"
@ -663,12 +652,6 @@ dependencies = [
"vcpkg",
]
[[package]]
name = "os_str_bytes"
version = "6.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ff7415e9ae3fff1225851df9e0d9e4e5479f947619774677a63572e55e80eff"
[[package]]
name = "parking_lot"
version = "0.11.2"
@ -1007,9 +990,33 @@ dependencies = [
[[package]]
name = "strsim"
version = "0.10.0"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"
[[package]]
name = "structopt"
version = "0.3.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40b9788f4202aa75c240ecc9c15c65185e6a39ccdeb0fd5d008b98825464c87c"
dependencies = [
"clap",
"lazy_static",
"structopt-derive",
]
[[package]]
name = "structopt-derive"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcb5ae327f9cc13b68763b5749770cb9e048a99bd9dfdfa58d0cf05d5f64afe0"
dependencies = [
"heck",
"proc-macro-error",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "syn"
@ -1057,9 +1064,12 @@ dependencies = [
[[package]]
name = "textwrap"
version = "0.15.0"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb"
checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"
dependencies = [
"unicode-width",
]
[[package]]
name = "tinyvec"
@ -1187,6 +1197,12 @@ dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-segmentation"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8895849a949e7845e06bd6dc1aa51731a103c42707010a5b591c0038fb73385b"
[[package]]
name = "unicode-width"
version = "0.1.9"
@ -1217,6 +1233,12 @@ version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "vec_map"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
[[package]]
name = "version_check"
version = "0.9.3"

View File

@ -16,5 +16,6 @@ log = "0.4.14"
reqwest = { version = "0.11", features = ["json", "stream"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
clap = { version = "3.2.20", features = ["derive"] }
structopt = "0.3"
tokio = { version = "1", features = ["full"] }
toml = "0.5"

3
Hopfile-example.toml Normal file
View File

@ -0,0 +1,3 @@
version = "1.16.5"
[mods.sodium]

325
README.md
View File

@ -1,277 +1,118 @@
```
___---___
___--- | ---___
--- ___---___ ---
|---___--- ---___---|
| ---___ ___--- |
---___ | ___---
|---___|___---|
--__ - __--
|-_-|
-_-
__ __
/ / / /___ ____ ____ ___ _____
/ /_/ / __ \/ __ \/ __ \/ _ \/ ___/
/ __ / /_/ / /_/ / /_/ / __/ /
/_/ /_/\____/ .___/ .___/\___/_/
/_/ /_/
```
# Hopper
A Minecraft package manager for the terminal.
A Minecraft mod manager for the terminal.
Hopper can automatically search, download, and update Minecraft mods, modpacks,
resource packs, and plugins from [Modrinth](https://modrinth.com/) so that
keeping your mods up-to-date and compatible with each other is easy. With
Hopper, you won't have to manually visit [CurseForge](https://curseforge.com/)
and download each mod one-by-one every time you set up a new instance, or deal
with the hassle of swapping out different mod versions for hours while trying to
get Minecraft to accept them all at once.
Hopper can automatically search, download, and update Minecraft mods from https://modrinth.com/ so that keeping your mods up-to-date and compatible with each other is easy. With Hopper, you won't have to manually visit CurseForge and download each mod one-by-one every time you set up a new instance, or deal with the hassle of swapping out different mod versions for hours while trying to get Minecraft to accept them all at once.
Hopper is still very early in development, but important features are coming
along smoothly, and we'll have lots of progress to show off in the coming weeks.
It's written in [Rust](https://www.rust-lang.org/) and released under the
[AGPLv3](LICENSE).
Hopper is still very early in development, but important features are coming along smoothly, and we'll have lots of progress to show off in the coming weeks. It's written in Rust and released under the AGPLv3.
We're looking for people to help contribute code and write documentation. Please
reach out to us in [our Discord "server"](https://discord.gg/jJutHQjsh9) if
you're interested in helping out. If you have a taste in CLI apps like Hopper,
your input is especially appreciated.
We're looking for people to help contribute code, design the terminal interface, write documentation, and design a logo. Please reach out to us in [our Discord server](https://discord.gg/JWRFAbve9M) if you're interested in helping out. If you have a taste in CLI-based apps like Hopper, your input is especially appreciated.
Inspired by applications like [paru](https://github.com/morganamilo/paru), a
feature-packed AUR helper and [topgrade](https://github.com/r-darwish/topgrade),
a tool to upgrade everything
Inspired by CLI apps like:
- [paru](https://github.com/morganamilo/paru): Feature packed AUR helper
- [topgrade](https://github.com/r-darwish/topgrade): Upgrade everything
[![Donate using
Liberapay](https://liberapay.com/assets/widgets/donate.svg)](https://liberapay.com/tebibytemedia/donate)
### Donate
<noscript><a href="https://liberapay.com/tebibytemedia/donate"><img alt="Donate using Liberapay" src="https://liberapay.com/assets/widgets/donate.svg"></a></noscript>
# High-level Goals
## Continuous
- Small binary size
- Minimal compile times
Continuous:
- small binary size
- minimal compile times
## Features
Features:
- modrinth mod searching
- modrinth mod installation
- curseforge api too?
- per-instance mod management
- mod updating
- fish autocomplete
- bash autocomplete
- zsh autocomplete
- nushell autocomplete
- manpage
- configurable mod search result display like [Starship](https://starship.rs)
- `display` command or something that displays (cached?) mod info
- parallel mod downloading
### High Priority:
- Modrinth package searching
- Modrinth package installation
- Parallel package downloading
- Per-instance package management
- Package updating
- Listing installed packages
Long-term/host-dependent:
- conflict resolution
- dependency resolution
- shaderpack and resource pack management
- integrate into multimc or theseus
- graphical frontend (w/ notifications?)
### Medium Priority
- CurseForge package searching
- CurseForge package installation
- A `man(1)` entry
[Modrinth REST API docs](https://github.com/modrinth/labrinth/wiki/API-Documentation)
### Low Priority:
- Shell autocomplete
- Configurable search result display like [Starship](https://starship.rs)
- Version-control system repository package management & compilation
# File Architecture
### External-Dependent:
- Conflict resolution
- Dependency resolution
- Integration into [Prism Launcher](https://prismlauncher.org/) and/or
[theseus](https://github.com/modrinth/theseus)
- Integration into `topgrade(1)`
- Graphical frontend with notifications
[Modrinth REST API
docs](https://docs.modrinth.com/api-spec/)
# File Structure
```
├── "$XDG_CONFIG_HOME"/hopper.toml
├── "$XDG_CACHE_HOME"/hopper/
│ ├── 1.19.1/
│ │ └── fabric/
│ └── 1.18.2/
│ ├── forge/
│ └── plugin/
└── "XDG_DATA_HOME"/templates/
└── example-template.hop -> ~/.minecraft/mods/example-template.hop
```bash
- .config/hopper/config.toml # Main config file
- .local/share/multimc/instances/*/.minecraft/Hopfile.toml # Multimc
- .minecraft/Hopfile.toml # Official launcher
- .var/app/com.mojang.Minecraft/.minecraft/Hopfile.toml # Flatpak version
- .cache/hopper/ # Mod cache
| - hopper.lock # Lock file
| - mod1.jar # Mods
| - mod2.jar
+------------- - ...
```
# Hopfile Structure
Hopfiles will contain a Minecraft version number, a list of packages, and any
references to other hopfiles on which it's based, or "templates". If a hopfile
is based on other template hopfiles, it inherits the packages from them. A
hopfile does not inherit the package or Minecraft version from a template.
# Usage (Planned)
Create `Hopfile.toml` in your instance directory:
```
template = "example-template"
mc-version = "1.19.2"
[packages]
fabric-mod = [ "sodium", "lithium" ]
resource = "alacrity"
hopper init
```
# Hopper Configuration File Structure
Hopper's configuration will be maintained with a list of all hopfiles known to
hopper. Its config file will also contain a list of mod hosting sites like
Modrinth and CurseForge and a list of (remote or local) version-control
repositories from which to compile mods. The latter will use a (potentially
custom) build file format to be defined at a later date.
Add mods:
```
hopfiles = [
"~/.minecraft/mods/template.hop",
"~/.minecraft/1.91.1/mods/1.19.1.hop"
]
[sources]
modrinth = "https://api.modrinth.com/"
curseforge = "https://api.curseforge.com/"
git = [
"git+https://github.com/IrisShaders/Iris.git"
"git+https://github.com/CaffeineMC/sodium-fabric.git"
]
hopper add iris
hopper add sodium
hopper add phosphor
```
# Docs
Check for mod updates:
```
hopper update
```
## Types
# Docs (Planned)
There are multiple types of packages hopper can manage.
## `hopper init`
### Mods
- `fabric-mod`
- `forge-mod`
- `quilt-mod`
```
hopper init < --dir=./path/to/instance >
```
### Plugins
- `bukkit-plugin`
- `paper-plugin`
- `purpur-plugin`
- `spigot-plugin`
- `sponge-plugin`
Inits in current directory if `dir` is left out, otherwise inits in given dir.
### Other
- `data-pack`
- `fabric-pack`
- `forge-pack`
- `resource-pack`
- `quilt-pack`
## `hopper update`
These types are specified in various hopper subcommands and in its configuration.
```
hopper update < --mc-version=1.17 >
```
## Usage
Updates all installed mods of a specific version, or a version set in the config.
`hopper [options...] [subcommand...]`
## `hopper add`
## OPTIONS
```
$ hopper add sodium --mc-version 1.17
4 Indium 1.0.0+mc1.17.1 [1.17.1] (21557 downloads)
Sodium addon providing support for the Fabric Rendering API, based on Indigo
3 Reese's Sodium Options 1.2.1 [1.16.5] (548 downloads)
Alternative Options Menu for Sodium
2 Sodium Extra mc1.17.1-0.3.6 [1.17.1] (16387 downloads)
Features that shouldn't be in Sodium.
1 Sodium mc1.17.1-0.3.2 [1.17.1] (962361 downloads)
Modern rendering engine and client-side optimization mod for Minecraft
:: Select a mod
:: ...
```
`-v`, `--verbose`
## `hopper get`
&emsp;Includes debug information in the output of `hopper` subcommands.
## SUBCOMMANDS
`get [options...] [targets...]`
&emsp;Searches for packages, displays the results, and downloads any selected
packages to the local cache. If multiple targets are specified, results are
displayed in order of specification.
OPTIONS
&emsp;`-d`, `--dir [directory...]`
&emsp;&emsp;Specifies the directory to download to (default is
"$XDG_CACHE_HOME"/hopper/).
&emsp;`-m`, `--mc-version [version...]`
&emsp;&emsp;Specifies for what version of Minecraft packages are being
retrieved.
&emsp;`-n`, `--no-confirm`
&emsp;&emsp;Does not display search results and downloads exact matches to the
cache. Requires `--mc-version` and `--type` be specified.
&emsp;`-t`, `--type [types...]`
&emsp;&emsp;Specifies what types of packages are being queried.
`init [options...]`
&emsp;Creates a hopfile in the current directory and adds it to the global known
hopfiles list.
OPTIONS
&emsp;`-d`, `--dir [directory...]`
&emsp;&emsp;Specifies the directory in which the hopfile is being created.
&emsp;`-f`, `--hopfile [hopfiles...]`
&emsp;&emsp;Specifies templates upon which to base the new hopfile.
&emsp;`-m`, `--mc-version [version]`
&emsp;&emsp;Specifies for what version of Minecraft packages are being managed.
&emsp;`-t`, `--type [type...]`
&emsp;&emsp;Specifies what type of packages will be listed in this hopfile.
`install [options...] [packages...]`
&emsp;Adds packages to the current hopfile, symlinking them to its directory. If
the package cannot be found in the package cache, `hopper get` is run first.
OPTIONS
&emsp; `-f`, `--hopfile [hopfiles...]`
&emsp;&emsp;Specifies hopfiles to which mods will be added.
`list [options...]`
&emsp;Lists all installed packages.
OPTIONS
&emsp; `-f` `--hopfile [hopfiles...]`
&emsp;&emsp;Lists packages installed in a specified hopfile.
&emsp;`-m`, `--mc-version [version]`
&emsp;&emsp;Specifies for what version of Minecraft packages are being managed.
&emsp;`-t`, `--type [types...]`
&emsp;&emsp;List all packages of a specified type.
`update [options...]`
&emsp;Updates installed packages and adds mods if they're missing to directories
with known hopfiles.
OPTIONS
&emsp;`-f`, `--hopfile [hopfiles...]`
&emsp;&emsp;Updates only packages in the specified hopfile. Note that this
option creates a new file and symlink as it does not update the packages for
other hopfiles.
&emsp;`-m`, `--mc-version [version]`
&emsp;&emsp;Specifies for what version of Minecraft packages are being updated.
&emsp;`-t`, `--type [types...] [packages...]`
&emsp;&emsp;Updates only packages of a specified type. Optionally takes a list
of packages as an argument.
Just like `hopper add` but simply downloads a mod jar to the current directory.

View File

@ -1,6 +1,6 @@
use console::style;
use serde::Deserialize;
use std::{collections::HashMap, fmt};
use std::collections::HashMap;
#[derive(Deserialize, Debug)]
pub struct SearchResponse {
@ -10,27 +10,27 @@ pub struct SearchResponse {
pub total_hits: isize,
}
#[derive(Deserialize, Debug)]
#[derive(Clone, Deserialize, Debug)]
pub struct ModResult {
pub slug: String,
pub mod_id: String, // TODO parse to `local-xxxxx` with regex
pub slug: String, // not in the API docs, but shows up in queries anyways
pub project_type: Option<String>, // NOTE this isn't in all search results?
pub author: String,
pub title: String,
pub description: String,
pub categories: Vec<String>,
pub display_categories: Vec<String>, // NOTE this is not in the OpenAPI docs
pub client_side: String,
pub server_side: String,
pub project_type: String, // NOTE this isn't in all search results?
pub downloads: isize,
pub icon_url: String,
pub project_id: String, // TODO parse to 'local-xxxx' with reegex
pub author: String,
pub versions: Vec<String>,
pub follows: isize,
pub downloads: isize,
pub page_url: String,
pub icon_url: String,
pub author_url: String,
pub date_created: String,
pub date_modified: String,
pub latest_version: String,
pub license: String,
pub gallery: Vec<String>,
pub client_side: String,
pub server_side: String,
pub host: String,
}
impl ModResult {
@ -60,76 +60,55 @@ impl ModResult {
#[derive(Deserialize, Debug)]
pub struct ModInfo {
pub id: String, // TODO serialize mod id?
pub slug: String,
pub team: String, // TODO serialize team id?
pub title: String,
pub description: String,
pub categories: Vec<String>,
pub additional_categories: Vec<String>, // NOTE not listed in OpenAPI docs
pub client_side: String, // TODO serialize as enum
pub server_side: String, // TODO serialize as enum
pub body: String,
pub published: String, // TODO serialize datetime
pub updated: String, // TODO serialize datetime
pub status: String,
pub license: License,
pub client_side: String, // TODO serialize as enum
pub server_side: String, // TODO serialize as enum
pub downloads: isize,
pub followers: isize,
pub categories: Vec<String>,
pub versions: Vec<String>,
pub icon_url: Option<String>,
pub issues_url: Option<String>,
pub source_url: Option<String>,
pub wiki_url: Option<String>,
pub discord_url: Option<String>,
pub donation_urls: Option<Vec<DonationLink>>,
pub project_type: String,
pub downloads: isize,
pub icon_url: Option<String>,
pub id: String, // TODO serialize mod id?
pub team: String, // TODO serialize team id?
pub body_url: Option<String>, // NOTE deprecated
pub moderator_message: Option<String>,
pub published: String, // TODO serialize as datetime
pub updated: String, // TODO serialize as datetime
pub approved: Option<String>, // NOTE not listed in OpenAPI docs, TODO serialize as datetime
pub followers: isize,
pub status: String,
pub license: License,
pub versions: Vec<String>,
pub gallery: Option<Vec<GalleryEntry>>,
}
#[derive(Deserialize, Debug)]
pub struct GalleryEntry {
pub url: String,
pub featured: bool,
pub title: String,
pub description: String,
pub created: String,
pub donation_urls: Vec<String>,
}
#[derive(Deserialize, Debug)]
pub struct License {
pub id: String,
pub name: String,
pub url: String,
}
#[derive(Deserialize, Debug)]
pub struct DonationLink {
pub id: String,
pub platform: String,
pub url: String,
pub url: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct ModVersion {
pub id: String, // version id
pub mod_id: String, // mod id
pub author_id: String, // user id
// NOTE modrinth docs list this as a String, but is actually a bool?
// featured: String, // user id
pub name: String,
pub version_number: String,
pub changelog: Option<String>,
// pub dependencies: Option<Vec<String>>, // TODO dependency wrangling, thank you modrinth, very cool
pub game_versions: Vec<String>,
pub version_type: String, // TODO {alpha | beta | release}
pub loaders: Vec<String>,
pub featured: bool,
pub id: String, // version id
pub project_id: String, // mod id
pub author_id: String, // user id
pub changelog_url: Option<String>,
pub date_published: String, // TODO serialize datetime
pub downloads: isize,
pub changelog_url: Option<String>, // NOTE deprecated
pub version_type: String, // TODO {alpha | beta | release}
pub files: Vec<ModVersionFile>,
pub dependencies: Vec<String>, // TODO dependency wrangling, thank you modrinth, very cool
pub game_versions: Vec<String>,
pub loaders: Vec<String>,
}
#[derive(Deserialize, Debug)]
@ -137,20 +116,4 @@ pub struct ModVersionFile {
pub hashes: HashMap<String, String>,
pub url: String,
pub filename: String,
pub primary: bool,
pub size: isize,
}
#[derive(Deserialize, Debug)]
pub struct Error {
pub error: String,
pub description: String,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.error, self.description)
}
}
impl std::error::Error for Error {}

View File

@ -1,166 +0,0 @@
use crate::api::{ModInfo, ModResult, ModVersion, ModVersionFile, SearchResponse, Error as APIError};
use crate::config::{Args, Config, PackageType, SearchArgs};
use futures_util::StreamExt;
use log::*;
use std::cmp::min;
use std::io::Write;
pub struct HopperClient {
config: Config,
client: reqwest::Client,
}
impl HopperClient {
pub fn new(config: Config) -> Self {
Self {
config: config,
client: reqwest::ClientBuilder::new()
.user_agent(format!("tebibytemedia/hopper/{} (tebibyte.media)", env!("CARGO_PKG_VERSION")))
.build()
.unwrap(),
}
}
pub async fn search_mods(&self, search_args: &SearchArgs) -> anyhow::Result<SearchResponse> {
println!("Searching with query \"{}\"...", search_args.package_name);
let url = format!("https://{}/v2/search", self.config.upstream.server_address);
let mut params = vec![("query", search_args.package_name.to_owned())];
let mut facets: Vec<String> = Vec::new();
if let Some(versions) = &search_args.version {
let versions_facets = versions
.iter()
.map(|e| format!("[\"versions:{}\"]", e))
.collect::<Vec<String>>()
.join(",");
facets.push(format!("{}", versions_facets));
}
if let Some(package_type) = &search_args.package_type {
let package_type_facet = match package_type {
PackageType::Fabric => "[\"categories:fabric\"],[\"project_type:mod\"]",
PackageType::Forge => "[\"categories:forge\"],[\"project_type:mod\"]",
PackageType::Quilt => "[\"categories:quilt\"],[\"project_type:mod\"]",
PackageType::Resource => "[\"project_type:resourcepack\"]",
PackageType::FabricPack => "[\"project_type:modpack\"],[\"categories:fabric\"]",
PackageType::ForgePack => "[\"project_type:modpack\"],[\"categories:forge\"]",
PackageType::QuiltPack => "[\"project_type:modpack\"],[\"categories:quilt\"]",
PackageType::BukkitPlugin => "[\"project_type:mod\"],[\"categories:bukkit\"]",
PackageType::PaperPlugin => "[\"project_type:mod\"],[\"categories:paper\"]",
PackageType::PurpurPlugin => "[\"project_type:mod\"],[\"categories:purpur\"]",
PackageType::SpigotPlugin => "[\"project_type:mod\"],[\"categories:spigot\"]",
PackageType::SpongePlugin => "[\"project_type:mod\"],[\"categories:sponge\"]",
}
.to_string();
facets.push(package_type_facet);
}
if !facets.is_empty() {
params.push(("facets", format!("[{}]", facets.join(","))));
}
let url = reqwest::Url::parse_with_params(url.as_str(), &params)?;
info!("GET {}", url);
let response = self.client.get(url).send().await?;
if response.status().is_success() {
Ok(response.json::<SearchResponse>().await?)
} else {
Err(response.json::<APIError>().await?.into())
}
}
pub async fn fetch_mod_info(&self, mod_result: &ModResult) -> anyhow::Result<ModInfo> {
let mod_id = &mod_result.project_id;
println!(
"Fetching mod info for {} (ID: {})...",
mod_result.title, mod_id
);
let url = format!(
"https://{}/v2/project/{}",
self.config.upstream.server_address, mod_id
);
info!("GET {}", url);
let response = self.client.get(url).send().await?;
if response.status().is_success() {
Ok(response.json::<ModInfo>().await?)
} else {
Err(response.json::<APIError>().await?.into())
}
}
pub async fn fetch_mod_version(&self, version_id: &String) -> anyhow::Result<ModVersion> {
println!("Fetching mod version {}...", version_id);
let url = format!(
"https://{}/v2/version/{}",
self.config.upstream.server_address, version_id
);
info!("GET {}", url);
let response = self.client.get(url).send().await?;
if response.status().is_success() {
Ok(response.json::<ModVersion>().await?)
} else {
Err(response.json::<APIError>().await?.into())
}
}
pub async fn download_version_file(
&self,
args: &Args,
file: &ModVersionFile,
) -> anyhow::Result<()> {
// TODO replace all uses of .unwrap() with proper error codes
let filename = &file.filename;
// TODO make confirmation skippable with flag argument
if !args.auto_accept {
use dialoguer::Confirm;
let prompt = format!("Download to {}?", filename);
let confirm = Confirm::new()
.with_prompt(prompt)
.default(true)
.interact()?;
if !confirm {
println!("Skipping downloading {}...", filename);
return Ok(());
}
}
let url = &file.url;
info!("GET {}", url);
let response = self.client.get(url).send().await?;
if !response.status().is_success() {
return Err(response.json::<APIError>().await?.into())
}
let total_size = response.content_length().unwrap();
// TODO better colors and styling!
// TODO square colored creeper face progress indicator (from top-left clockwise spiral in)
use indicatif::{ProgressBar, ProgressStyle};
let pb = ProgressBar::new(total_size);
pb.set_style(ProgressStyle::default_bar().template("{msg}\n{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({bytes_per_sec}, {eta})").progress_chars("#>-"));
pb.set_message(&format!("Downloading {}", url));
let filename = &file.filename;
let mut file = std::fs::File::create(filename)?;
let mut downloaded: u64 = 0;
let mut stream = response.bytes_stream();
// TODO check hashes while streaming
while let Some(item) = stream.next().await {
let chunk = &item.unwrap();
file.write(&chunk)?;
let new = min(downloaded + (chunk.len() as u64), total_size);
downloaded = new;
pb.set_position(new);
}
pb.finish_with_message(&format!("Downloaded {} to {}", url, filename));
Ok(())
}
}

View File

@ -1,68 +1,51 @@
use clap::{Parser, Subcommand, ValueEnum};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use structopt::StructOpt;
// TODO parameter to restrict target Minecraft version
#[derive(clap::Args, Clone, Debug)]
#[derive(StructOpt, Clone, Debug)]
pub struct SearchArgs {
pub package_name: String,
/// Type of package to use
#[clap(short, long, value_enum)]
pub package_type: Option<PackageType>,
/// Restricts the target Minecraft version
#[clap(short, long)]
#[structopt(short, long)]
pub version: Option<Vec<String>>,
}
// TODO use ColoredHelp by default?
#[derive(Subcommand, Clone, Debug)]
#[derive(StructOpt, Clone, Debug)]
pub enum Command {
/// Adds a mod to the current instance
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
Add(SearchArgs),
/// Removes a mod
Remove {
package_name: String,
},
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
Remove { package_name: String },
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
Get(SearchArgs),
Update,
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
Update { instance_dir: Option<PathBuf> },
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
Clean,
}
#[derive(ValueEnum, Clone, Debug)]
pub enum PackageType {
Fabric,
Forge,
Quilt,
Resource,
FabricPack,
ForgePack,
QuiltPack,
BukkitPlugin,
PaperPlugin,
PurpurPlugin,
SpigotPlugin,
SpongePlugin,
}
// TODO move main body argument fields to substruct for ease of moving?
#[derive(Parser, Clone, Debug)]
#[clap(name = "hopper")]
#[derive(StructOpt, Clone, Debug)]
#[structopt(name = "hopper", setting = structopt::clap::AppSettings::ColoredHelp)]
pub struct Args {
/// Path to configuration file
#[clap(short, long, value_parser)]
#[structopt(short, long, parse(from_os_str))]
pub config: Option<PathBuf>,
/// Path to mod lockfile
#[clap(short, long, value_parser)]
#[structopt(short, long, parse(from_os_str))]
pub lockfile: Option<PathBuf>,
/// Auto-accept confirmation dialogues
#[clap(short = 'y', long = "yes")]
#[structopt(short = "y", long = "yes")]
pub auto_accept: bool,
#[clap(subcommand)]
#[structopt(subcommand)]
pub command: Command,
}
@ -76,7 +59,7 @@ impl Args {
}
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[derive(Deserialize, Serialize, Debug)]
pub struct Upstream {
/// Modrinth main server address
pub server_address: String,
@ -90,7 +73,7 @@ impl Default for Upstream {
}
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[derive(Deserialize, Serialize, Debug)]
pub struct Options {
/// Whether to reverse search results
pub reverse_search: bool,
@ -104,7 +87,7 @@ impl Default for Options {
}
}
#[derive(Deserialize, Serialize, Debug, Default, Clone)]
#[derive(Deserialize, Serialize, Debug, Default)]
pub struct Config {
/// General settings
pub options: Options,

11
src/hopfile.rs Normal file
View File

@ -0,0 +1,11 @@
use serde::Deserialize;
use std::collections::HashMap;
#[derive(Debug, Deserialize)]
pub struct ModEntry {}
#[derive(Debug, Deserialize)]
pub struct Hopfile {
pub version: String,
pub mods: HashMap<String, ModEntry>,
}

View File

@ -1,11 +1,37 @@
use futures_util::StreamExt;
use log::*;
use std::cmp::min;
use std::io::Write;
use std::path::{Path, PathBuf};
use structopt::StructOpt;
mod api;
mod client;
mod config;
mod hopfile;
use api::*;
use clap::Parser;
use client::*;
use config::*;
use hopfile::*;
async fn search_mods(ctx: &AppContext, search_args: &SearchArgs) -> anyhow::Result<SearchResponse> {
let client = reqwest::Client::new();
let url = format!("https://{}/api/v1/mod", ctx.config.upstream.server_address);
let mut params = vec![("query", search_args.package_name.to_owned())];
if let Some(versions) = &search_args.version {
params.push(("versions", versions.join(",")));
}
let url = reqwest::Url::parse_with_params(url.as_str(), &params)?;
info!("Searching for mods: {}", url);
let response = client
.get(url)
.send()
.await?;
info!("Search results: {:#?}", response);
let response = response.json::<SearchResponse>().await?;
Ok(response)
}
fn display_search_results(ctx: &AppContext, response: &SearchResponse) {
let iter = response.hits.iter().enumerate();
@ -24,85 +50,256 @@ fn display_search_results(ctx: &AppContext, response: &SearchResponse) {
async fn select_from_results(
_ctx: &AppContext,
response: &SearchResponse,
) -> anyhow::Result<Vec<usize>> {
) -> anyhow::Result<Vec<ModResult>> {
let input: String = dialoguer::Input::new()
.with_prompt("Mods to install (eg: 1 2 3-5)")
.with_prompt("Mods to install (eg: 1 2 3)")
.interact_text()?;
let mut selected: Vec<usize> = Vec::new();
for token in input.split(" ") {
let terms: Vec<&str> = token.split("-").collect();
// TODO range input (eg: 1-3)
let index: usize = token.parse().expect("Token must be an integer");
if index < 1 || index > response.hits.len() {
// TODO return useful error instead of panicking
panic!("Index {} is out of bounds", index);
}
match terms.len() {
1 => selected.push(terms[0].parse().expect("Token must be an integer")),
2 => {
let terms: Vec<usize> = terms
.iter()
.map(|term| term.parse().expect("Term must be an integer"))
.collect();
let from = terms[0];
let to = terms[1];
// input is indexed from 1, but results are indexed from 0
let index = index - 1;
for index in from..=to {
selected.push(index);
}
}
_ => panic!("Invalid selection token {}", token),
if !selected.contains(&index) {
selected.push(index);
} else {
// TODO make this a proper warning log message
println!("warning: repeated index {}", index);
}
}
selected.dedup();
let selected = selected
Ok(selected
.iter()
.map(|index| {
if *index < 1 || *index > response.hits.len() {
// TODO return useful error instead of panicking
panic!("Index {} is out of bounds", index);
}
// input is indexed from 1, but results are indexed from 0
let index = index - 1;
index
})
.collect();
Ok(selected)
.map(|i| response.hits[*i].to_owned())
.collect())
}
async fn cmd_get(ctx: &AppContext, search_args: SearchArgs) -> anyhow::Result<()> {
let client = HopperClient::new(ctx.config.clone());
let response = client.search_mods(&search_args).await?;
async fn fetch_mod_info(ctx: &AppContext, mod_result: &ModResult) -> anyhow::Result<ModInfo> {
let client = reqwest::Client::new();
let mod_id = &mod_result.mod_id;
let mod_id = mod_id[6..].to_owned(); // Remove "local-" prefix
let url = format!(
"https://{}/api/v1/mod/{}",
ctx.config.upstream.server_address, mod_id
);
info!("Fetching mod info: {}", url);
let response = client.get(url).send().await?;
info!("Mod info: {:#?}", response);
let response = response.json::<ModInfo>().await?;
Ok(response)
}
async fn fetch_mod_version(ctx: &AppContext, version_id: &String) -> anyhow::Result<ModVersion> {
let client = reqwest::Client::new();
let url = format!(
"https://{}/api/v1/version/{}",
ctx.config.upstream.server_address, version_id
);
info!("Fetching mod version: {}", url);
let response = client.get(url).send().await?;
info!("Mod version: {:#?}", response);
let response = response.json::<ModVersion>().await?;
Ok(response)
}
async fn download_version_file(
ctx: &AppContext,
target_dir: &Path,
file: &ModVersionFile,
) -> anyhow::Result<()> {
// TODO replace all uses of .unwrap() with proper error codes
let filename = &file.filename;
// TODO make confirmation skippable with flag argument
if !ctx.args.auto_accept {
use dialoguer::Confirm;
let prompt = format!("Download to {}?", filename);
let confirm = Confirm::new()
.with_prompt(prompt)
.default(true)
.interact()?;
if !confirm {
println!("Skipping downloading {}...", filename);
return Ok(());
}
}
let url = &file.url;
let filename = target_dir.join(&file.filename);
info!("Downloading {} to {:?}", url, filename);
let client = reqwest::Client::new();
let response = client.get(url).send().await?;
let total_size = response.content_length().unwrap();
// TODO better colors and styling!
// TODO square colored creeper face progress indicator (from top-left clockwise spiral in)
use indicatif::{ProgressBar, ProgressStyle};
let pb = ProgressBar::new(total_size);
pb.set_style(ProgressStyle::default_bar().template("{msg}\n{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({bytes_per_sec}, {eta})").progress_chars("#>-"));
pb.set_message(&format!("Downloading {}", url));
let mut file = std::fs::File::create(&filename)?;
let mut downloaded: u64 = 0;
let mut stream = response.bytes_stream();
// TODO check hashes while streaming
while let Some(item) = stream.next().await {
let chunk = &item.unwrap();
file.write(&chunk)?;
let new = min(downloaded + (chunk.len() as u64), total_size);
downloaded = new;
pb.set_position(new);
}
pb.finish_with_message(&format!("Downloaded {} to {:#?}", url, filename));
Ok(())
}
async fn search_and_select(
ctx: &AppContext,
search_args: &SearchArgs,
) -> anyhow::Result<Vec<ModResult>> {
let response = search_mods(ctx, &search_args).await?;
if response.hits.is_empty() {
// TODO formatting
println!("No results; nothing to do...");
return Ok(());
return Ok(vec![]);
}
// TODO add a config file option to disable this
if let Some(first_result) = response.hits.first() {
if response.hits.len() == 1 {
println!("autoselecting only mod result");
return Ok(vec![first_result.to_owned()]);
}
}
// TODO add a config file option to disable this
for mod_info in response.hits.iter() {
if mod_info.slug == search_args.package_name {
println!("autoselecting mod result slug with exact match");
return Ok(vec![mod_info.to_owned()]);
}
}
display_search_results(ctx, &response);
let selected = select_from_results(ctx, &response).await?;
let selected = loop {
let selected = select_from_results(ctx, &response).await?;
if selected.is_empty() {
use dialoguer::Confirm;
let mod_name = &search_args.package_name;
let prompt = format!("Really skip downloading {}?", mod_name);
let confirm = Confirm::new().with_prompt(prompt).interact()?;
if !confirm {
println!("Skipping updating {}...", mod_name);
} else {
continue;
}
}
break selected;
};
Ok(selected)
}
async fn pick_mod_version(
ctx: &AppContext,
mod_info: &ModInfo,
target_versions: &Option<Vec<String>>,
) -> anyhow::Result<Option<ModVersion>> {
// TODO allow the user to select multiple versions?
match target_versions {
Some(target_versions) => {
for version_id in mod_info.versions.iter() {
let version = fetch_mod_version(ctx, version_id).await?;
for supported_version in version.game_versions.iter() {
if target_versions.contains(supported_version) {
return Ok(Some(version));
}
}
}
Ok(None)
}
None => {
if let Some(version_id) = mod_info.versions.first() {
Ok(Some(fetch_mod_version(ctx, version_id).await?))
} else {
Ok(None)
}
}
}
}
async fn download_mods(
ctx: &AppContext,
target_dir: Option<&Path>,
target_versions: &Option<Vec<String>>,
mods: &Vec<ModResult>,
) -> anyhow::Result<()> {
let current_dir = std::env::current_dir()?;
let target_dir = target_dir.unwrap_or(&current_dir);
for to_get in mods.iter() {
let mod_info = fetch_mod_info(ctx, to_get).await?;
let version = pick_mod_version(ctx, &mod_info, target_versions).await?;
if let Some(version) = version {
for file in version.files.iter() {
download_version_file(ctx, &target_dir, file).await?;
}
} else {
// TODO message formatting
println!("No versions to download for mod {}", mod_info.title);
}
}
Ok(())
}
async fn cmd_get(ctx: &AppContext, search_args: SearchArgs) -> anyhow::Result<()> {
let selected = search_and_select(ctx, &search_args).await?;
if selected.is_empty() {
// TODO formatting
println!("No packages selected; nothing to do...");
return Ok(());
}
for selection in selected.iter() {
let to_get = &response.hits[*selection];
let mod_info = client.fetch_mod_info(to_get).await?;
// TODO arg for target directory?
download_mods(ctx, None, &search_args.version, &selected).await?;
// TODO allow the user to select multiple versions
if let Some(version_id) = mod_info.versions.first() {
println!("fetching version {}", version_id);
Ok(())
}
let version = client.fetch_mod_version(version_id).await?;
for file in version.files.iter() {
client.download_version_file(&ctx.args, file).await?;
}
}
async fn cmd_update(ctx: &AppContext, instance_dir: Option<PathBuf>) -> anyhow::Result<()> {
let instance_dir = instance_dir.unwrap_or(std::env::current_dir()?);
let hopfile_path = instance_dir.join("Hopfile.toml");
let hopfile = std::fs::read_to_string(hopfile_path)?;
let hopfile: Hopfile = toml::from_str(&hopfile)?;
println!("hopfile: {:#?}", hopfile);
// TODO cover range of Minecraft versions? (e.g. 1.18 = 1.18.1, 1.18.2, etc.)
let target_versions = Some(vec![hopfile.version.to_owned()]);
for (name, entry) in hopfile.mods.iter() {
let search_args = SearchArgs {
package_name: name.to_string(),
version: Some(vec![hopfile.version.to_owned()]),
};
let selected = search_and_select(ctx, &search_args).await?;
// TODO update Hopfile.toml with specific versions using toml_edit crate
download_mods(ctx, Some(&instance_dir), &target_versions, &selected).await?;
}
Ok(())
@ -111,11 +308,12 @@ async fn cmd_get(ctx: &AppContext, search_args: SearchArgs) -> anyhow::Result<()
#[tokio::main]
async fn main() -> anyhow::Result<()> {
env_logger::init();
let args = Args::parse();
let args = Args::from_args();
let config = args.load_config()?;
let ctx = AppContext { args, config };
match ctx.args.to_owned().command {
Command::Get(search_args) => cmd_get(&ctx, search_args).await,
Command::Update { instance_dir } => cmd_update(&ctx, instance_dir).await,
_ => unimplemented!("unimplemented subcommand"),
}
}