Compare commits

...

37 Commits

Author SHA1 Message Date
Emma Tebibyte 132d82680b Merge pull request 'Fix error when no facets are specifed' (#16) from BlankParenthesis/hopper:fix-filter into main
Reviewed-on: #16
2022-12-24 04:06:21 +00:00
Emma Tebibyte 5ae5aa668d Merge pull request 'Implement Error parsing for API responses' (#18) from BlankParenthesis/hopper:handle-status-errors into main
fixes #20
2022-12-24 03:56:06 +00:00
Emma Tebibyte 3c87609720 Merge pull request 'Add User-Agent to requests' (#17) from BlankParenthesis/hopper:add-user-agent into main
Reviewed-on: #17
2022-12-24 03:47:48 +00:00
[ ] 552d75cbff Implement Error parsing for API responses 2022-12-09 06:01:37 +00:00
[ ] 9064888265 Add User-Agent to requests
Modrinth strongly encourages (via the following response header) that
access to their services be done with a uniquely identifying user-agent
string.

> "x-user-agent-notice": "!!!!! Hey, you! Yes, **you**! You need to
> change your User-Agent ASAP or you may be blocked from using
> Modrinth's services! For more information see the documentation:
> https://docs.modrinth.com/api-spec/#section/User-Agents !!!!!"

The one added here follows the documentation recommendation for the
"best" example of a user-agent string.
2022-12-09 05:13:43 +00:00
[ ] f7ba63b492 Fix error when no facets are specifed
The Modrinth API seemingly doesn't support an empty list for the facets
parameter. This solution simply skips adding that paremeter if it is
empty.
2022-12-09 04:18:15 +00:00
Emma Tebibyte 74de0d15b3 Merge pull request 'Better README' (#15) from readme into main
Reviewed-on: #15
2022-12-08 20:07:59 +00:00
Emma Tebibyte 36d67a1a61 comma delineated 2022-12-08 15:06:35 -05:00
Emma Tebibyte 015ab836c0 minor changes 2022-12-08 15:03:00 -05:00
Emma Tebibyte b2b4b388e9 add types i was unaware of 2022-11-17 15:36:03 -05:00
Emma Tebibyte 962d11807e add types specification and replace polymc with prismlauncher 2022-11-17 15:31:32 -05:00
Emma Tebibyte 1a120e816e alphabetization 2022-11-17 15:20:48 -05:00
Emma Tebibyte 8cbc28a8c1 formatting for -f option in update subcommand 2022-11-17 15:15:49 -05:00
Emma Tebibyte 9e51aca6d3 OPTIONS headings were more readable before 2022-11-17 15:14:22 -05:00
Emma Tebibyte 4dc5cea89a fixed some problems with the command structure 2022-11-17 15:09:19 -05:00
mars 716579f824 Merge pull request 'Add support for filtering plugins and resource packs' (#14) from PluginResourcePackSupport into main
Reviewed-on: #14
2022-10-25 02:32:30 +00:00
spookdot ace6b25381 Add plugins and modpack distinction 2022-09-16 18:51:55 +02:00
spookdot 6b37d007c7 Added package type filter 2022-09-12 01:05:23 +02:00
mars 6ab97922cb Merge pull request 'Changed out StructOpt for Clap' (#13) from UpgradeToClap into main
Reviewed-on: #13
2022-09-09 10:00:14 +00:00
Emma Tebibyte a5d3ff4231 specified types 2022-09-06 19:00:08 -04:00
spookdot f5887df96d Changed out StructOpt for Clap 2022-09-06 23:12:00 +02:00
Emma Tebibyte 3d3bf22cab Merge pull request 'README definition of specification' (#12) from design into main
Reviewed-on: #12
2022-09-06 07:15:56 +00:00
mars 12cda62da0 Merge pull request 'Move functions into new HopperClient struct' (#10) from HopperClient-rewrite into main
Reviewed-on: #10
2022-09-06 05:12:07 +00:00
Emma Tebibyte 48e0349848 grammar and formatting 2022-09-05 04:25:09 -04:00
Emma Tebibyte e2ae0ee88f fixed indents pt. 3 for i am a fool 2022-09-04 19:42:23 -04:00
Emma Tebibyte 75d3db9f50 fixed indents pt. 2 2022-09-04 19:42:23 -04:00
Emma Tebibyte cf2c8df86b fixed indents 2022-09-04 19:42:23 -04:00
Emma Tebibyte 9b41e09d46 updated README 2022-09-04 19:42:23 -04:00
Spookdot f5b6afd790 Move functions into new HopperClient struct 2022-08-25 11:39:54 +02:00
mars 0d8aaaf2c9 Merge pull request 'ModrinthAPIv2' (#9) from spookdot/hopper:ModrinthAPIv2 into main
Reviewed-on: #9
2022-08-22 20:31:19 +00:00
Spookdot 7d3a1c4a66 Fix Type on nullable types 2022-08-20 00:27:24 +02:00
Spookdot d2325fe31f Update URLs and Structs for Modrinth API v2 2022-08-20 00:17:55 +02:00
mars 44a81cf148 Update Modrinth API objects 2022-08-13 18:01:44 -06:00
mars ea28b0c904 Add logging of all requests 2022-08-13 18:01:25 -06:00
mars 8ea2a7777c Clean up select_from_results and add ranged selection 2022-08-13 17:32:01 -06:00
Marceline Cramer 6160a9a508
Add ASCII art hopper logo + title 2022-01-23 22:41:03 -07:00
Emma Tebibyte be54f355c8
Fixing Discord link 2022-01-21 15:28:00 -05:00
7 changed files with 608 additions and 323 deletions

109
Cargo.lock generated
View File

@ -11,15 +11,6 @@ dependencies = [
"memchr", "memchr",
] ]
[[package]]
name = "ansi_term"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b"
dependencies = [
"winapi",
]
[[package]] [[package]]
name = "anyhow" name = "anyhow"
version = "1.0.47" version = "1.0.47"
@ -87,17 +78,41 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]] [[package]]
name = "clap" name = "clap"
version = "2.33.3" version = "3.2.20"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37e58ac78573c40708d45522f0d80fa2f01cc4f9b4e2bf749807255454312002" checksum = "23b71c3ce99b7611011217b366d923f1d0a7e07a92bb2dbf1e84508c673ca3bd"
dependencies = [ dependencies = [
"ansi_term",
"atty", "atty",
"bitflags", "bitflags",
"clap_derive",
"clap_lex",
"indexmap",
"once_cell",
"strsim", "strsim",
"termcolor",
"textwrap", "textwrap",
"unicode-width", ]
"vec_map",
[[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",
] ]
[[package]] [[package]]
@ -324,12 +339,9 @@ checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"
[[package]] [[package]]
name = "heck" name = "heck"
version = "0.3.3" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9"
dependencies = [
"unicode-segmentation",
]
[[package]] [[package]]
name = "hermit-abi" name = "hermit-abi"
@ -345,6 +357,7 @@ name = "hopper"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"clap",
"confy", "confy",
"console", "console",
"dialoguer", "dialoguer",
@ -355,7 +368,6 @@ dependencies = [
"reqwest", "reqwest",
"serde", "serde",
"serde_json", "serde_json",
"structopt",
"tokio", "tokio",
] ]
@ -614,9 +626,9 @@ checksum = "17b02fc0ff9a9e4b35b3342880f48e896ebf69f2967921fe8646bf5b7125956a"
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.8.0" version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56" checksum = "2f7254b99e31cad77da24b08ebf628882739a608578bb1bcdfc1f9c21260d7c0"
[[package]] [[package]]
name = "openssl" name = "openssl"
@ -651,6 +663,12 @@ dependencies = [
"vcpkg", "vcpkg",
] ]
[[package]]
name = "os_str_bytes"
version = "6.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ff7415e9ae3fff1225851df9e0d9e4e5479f947619774677a63572e55e80eff"
[[package]] [[package]]
name = "parking_lot" name = "parking_lot"
version = "0.11.2" version = "0.11.2"
@ -989,33 +1007,9 @@ dependencies = [
[[package]] [[package]]
name = "strsim" name = "strsim"
version = "0.8.0" version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[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]] [[package]]
name = "syn" name = "syn"
@ -1063,12 +1057,9 @@ dependencies = [
[[package]] [[package]]
name = "textwrap" name = "textwrap"
version = "0.11.0" version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb"
dependencies = [
"unicode-width",
]
[[package]] [[package]]
name = "tinyvec" name = "tinyvec"
@ -1196,12 +1187,6 @@ dependencies = [
"tinyvec", "tinyvec",
] ]
[[package]]
name = "unicode-segmentation"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8895849a949e7845e06bd6dc1aa51731a103c42707010a5b591c0038fb73385b"
[[package]] [[package]]
name = "unicode-width" name = "unicode-width"
version = "0.1.9" version = "0.1.9"
@ -1232,12 +1217,6 @@ version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "vec_map"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
[[package]] [[package]]
name = "version_check" name = "version_check"
version = "0.9.3" version = "0.9.3"

View File

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

331
README.md
View File

@ -1,118 +1,277 @@
```
___---___
___--- | ---___
--- ___---___ ---
|---___--- ---___---|
| ---___ ___--- |
---___ | ___---
|---___|___---|
--__ - __--
|-_-|
-_-
__ __
/ / / /___ ____ ____ ___ _____
/ /_/ / __ \/ __ \/ __ \/ _ \/ ___/
/ __ / /_/ / /_/ / /_/ / __/ /
/_/ /_/\____/ .___/ .___/\___/_/
/_/ /_/
```
# Hopper # Hopper
A Minecraft mod manager for the terminal. A Minecraft package manager for the terminal.
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 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 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. 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).
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. 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.
Inspired by CLI apps like: Inspired by applications like [paru](https://github.com/morganamilo/paru), a
- [paru](https://github.com/morganamilo/paru): Feature packed AUR helper feature-packed AUR helper and [topgrade](https://github.com/r-darwish/topgrade),
- [topgrade](https://github.com/r-darwish/topgrade): Upgrade everything a tool to upgrade everything
### Donate [![Donate using
Liberapay](https://liberapay.com/assets/widgets/donate.svg)](https://liberapay.com/tebibytemedia/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 # High-level Goals
Continuous: ## Continuous
- small binary size - Small binary size
- minimal compile times - 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
Long-term/host-dependent: ### High Priority:
- conflict resolution - Modrinth package searching
- dependency resolution - Modrinth package installation
- shaderpack and resource pack management - Parallel package downloading
- integrate into multimc or theseus - Per-instance package management
- graphical frontend (w/ notifications?) - Package updating
- Listing installed packages
[Modrinth REST API docs](https://github.com/modrinth/labrinth/wiki/API-Documentation) ### Medium Priority
- CurseForge package searching
- CurseForge package installation
- A `man(1)` entry
# File Architecture ### Low Priority:
- Shell autocomplete
- Configurable search result display like [Starship](https://starship.rs)
- Version-control system repository package management & compilation
```bash ### External-Dependent:
- .config/hopper/config.toml # Main config file - Conflict resolution
- .local/share/multimc/instances/*/.minecraft/Hopfile.toml # Multimc - Dependency resolution
- .minecraft/Hopfile.toml # Official launcher - Integration into [Prism Launcher](https://prismlauncher.org/) and/or
- .var/app/com.mojang.Minecraft/.minecraft/Hopfile.toml # Flatpak version [theseus](https://github.com/modrinth/theseus)
- .cache/hopper/ # Mod cache - Integration into `topgrade(1)`
| - hopper.lock # Lock file - Graphical frontend with notifications
| - mod1.jar # Mods
| - mod2.jar
+------------- - ...
```
# Usage (Planned) [Modrinth REST API
docs](https://docs.modrinth.com/api-spec/)
Create `Hopfile.toml` in your instance directory: # File Structure
```
hopper init
```
Add mods:
```
hopper add iris
hopper add sodium
hopper add phosphor
```
Check for mod updates:
```
hopper update
```
# Docs (Planned)
## `hopper init`
``` ```
hopper init < --dir=./path/to/instance > ├── "$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
``` ```
Inits in current directory if `dir` is left out, otherwise inits in given dir. # Hopfile Structure
## `hopper update` 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.
``` ```
hopper update < --mc-version=1.17 > template = "example-template"
mc-version = "1.19.2"
[packages]
fabric-mod = [ "sodium", "lithium" ]
resource = "alacrity"
``` ```
Updates all installed mods of a specific version, or a version set in the config. # Hopper Configuration File Structure
## `hopper add` 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.
``` ```
$ hopper add sodium --mc-version 1.17 hopfiles = [
4 Indium 1.0.0+mc1.17.1 [1.17.1] (21557 downloads) "~/.minecraft/mods/template.hop",
Sodium addon providing support for the Fabric Rendering API, based on Indigo "~/.minecraft/1.91.1/mods/1.19.1.hop"
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) [sources]
Features that shouldn't be in Sodium. modrinth = "https://api.modrinth.com/"
1 Sodium mc1.17.1-0.3.2 [1.17.1] (962361 downloads) curseforge = "https://api.curseforge.com/"
Modern rendering engine and client-side optimization mod for Minecraft git = [
:: Select a mod "git+https://github.com/IrisShaders/Iris.git"
:: ... "git+https://github.com/CaffeineMC/sodium-fabric.git"
]
``` ```
## `hopper get` # Docs
Just like `hopper add` but simply downloads a mod jar to the current directory. ## Types
There are multiple types of packages hopper can manage.
### Mods
- `fabric-mod`
- `forge-mod`
- `quilt-mod`
### Plugins
- `bukkit-plugin`
- `paper-plugin`
- `purpur-plugin`
- `spigot-plugin`
- `sponge-plugin`
### Other
- `data-pack`
- `fabric-pack`
- `forge-pack`
- `resource-pack`
- `quilt-pack`
These types are specified in various hopper subcommands and in its configuration.
## Usage
`hopper [options...] [subcommand...]`
## OPTIONS
`-v`, `--verbose`
&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.

View File

@ -1,6 +1,6 @@
use console::style; use console::style;
use serde::Deserialize; use serde::Deserialize;
use std::collections::HashMap; use std::{collections::HashMap, fmt};
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
pub struct SearchResponse { pub struct SearchResponse {
@ -12,24 +12,25 @@ pub struct SearchResponse {
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
pub struct ModResult { pub struct ModResult {
pub mod_id: String, // TODO parse to `local-xxxxx` with regex pub slug: String,
pub project_type: Option<String>, // NOTE this isn't in all search results?
pub author: String,
pub title: String, pub title: String,
pub description: String, pub description: String,
pub categories: Vec<String>, pub categories: Vec<String>,
pub versions: 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 downloads: isize,
pub page_url: String,
pub icon_url: String, pub icon_url: String,
pub author_url: String, pub project_id: String, // TODO parse to 'local-xxxx' with reegex
pub author: String,
pub versions: Vec<String>,
pub follows: isize,
pub date_created: String, pub date_created: String,
pub date_modified: String, pub date_modified: String,
pub latest_version: String, pub latest_version: String,
pub license: String, pub license: String,
pub client_side: String, pub gallery: Vec<String>,
pub server_side: String,
pub host: String,
} }
impl ModResult { impl ModResult {
@ -59,28 +60,43 @@ impl ModResult {
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
pub struct ModInfo { pub struct ModInfo {
pub id: String, // TODO serialize mod id?
pub slug: String, pub slug: String,
pub team: String, // TODO serialize team id?
pub title: String, pub title: String,
pub description: String, pub description: String,
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 categories: Vec<String>,
pub versions: Vec<String>, pub additional_categories: Vec<String>, // NOTE not listed in OpenAPI docs
pub icon_url: Option<String>, pub client_side: String, // TODO serialize as enum
pub server_side: String, // TODO serialize as enum
pub body: String,
pub issues_url: Option<String>, pub issues_url: Option<String>,
pub source_url: Option<String>, pub source_url: Option<String>,
pub wiki_url: Option<String>, pub wiki_url: Option<String>,
pub discord_url: Option<String>, pub discord_url: Option<String>,
pub donation_urls: Vec<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,
} }
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
@ -90,24 +106,30 @@ pub struct License {
pub url: String, pub url: String,
} }
#[derive(Deserialize, Debug)]
pub struct DonationLink {
pub id: String,
pub platform: String,
pub url: String,
}
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
pub struct ModVersion { 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 name: String,
pub version_number: String, pub version_number: String,
pub changelog: Option<String>, pub changelog: Option<String>,
pub changelog_url: 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 date_published: String, // TODO serialize datetime pub date_published: String, // TODO serialize datetime
pub downloads: isize, pub downloads: isize,
pub version_type: String, // TODO {alpha | beta | release} pub changelog_url: Option<String>, // NOTE deprecated
pub files: Vec<ModVersionFile>, 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)] #[derive(Deserialize, Debug)]
@ -115,4 +137,20 @@ pub struct ModVersionFile {
pub hashes: HashMap<String, String>, pub hashes: HashMap<String, String>,
pub url: String, pub url: String,
pub filename: 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 {}

166
src/client.rs Normal file
View File

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

View File

@ -1,35 +1,12 @@
use futures_util::StreamExt;
use log::*;
use std::cmp::min;
use std::io::Write;
use structopt::StructOpt;
mod api; mod api;
mod client;
mod config; mod config;
use api::*; use api::*;
use clap::Parser;
use client::*;
use config::*; use config::*;
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!("GET {}", url);
let response = client
.get(url)
.send()
.await?
.json::<SearchResponse>()
.await?;
Ok(response)
}
fn display_search_results(ctx: &AppContext, response: &SearchResponse) { fn display_search_results(ctx: &AppContext, response: &SearchResponse) {
let iter = response.hits.iter().enumerate(); let iter = response.hits.iter().enumerate();
if ctx.config.options.reverse_search { if ctx.config.options.reverse_search {
@ -44,111 +21,59 @@ fn display_search_results(ctx: &AppContext, response: &SearchResponse) {
} }
// TODO implement enum for more graceful exiting // TODO implement enum for more graceful exiting
async fn select_from_results<'a>( async fn select_from_results(
_ctx: &AppContext, _ctx: &AppContext,
response: &'a SearchResponse, response: &SearchResponse,
) -> anyhow::Result<Vec<&'a ModResult>> { ) -> anyhow::Result<Vec<usize>> {
let input: String = dialoguer::Input::new() let input: String = dialoguer::Input::new()
.with_prompt("Mods to install (eg: 1 2 3)") .with_prompt("Mods to install (eg: 1 2 3-5)")
.interact_text()?; .interact_text()?;
let mut selected: Vec<usize> = Vec::new(); let mut selected: Vec<usize> = Vec::new();
for token in input.split(" ") { for token in input.split(" ") {
// TODO range input (eg: 1-3) let terms: Vec<&str> = token.split("-").collect();
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);
}
// input is indexed from 1, but results are indexed from 0 match terms.len() {
let index = index - 1; 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];
if !selected.contains(&index) { for index in from..=to {
selected.push(index); selected.push(index);
} else { }
// TODO make this a proper warning log message }
println!("warning: repeated index {}", index); _ => panic!("Invalid selection token {}", token),
} }
} }
Ok(selected.iter().map(|i| &response.hits[*i]).collect()) selected.dedup();
}
async fn fetch_mod_info(ctx: &AppContext, mod_result: &ModResult) -> anyhow::Result<ModInfo> { let selected = selected
let client = reqwest::Client::new(); .iter()
let mod_id = &mod_result.mod_id; .map(|index| {
let mod_id = mod_id[6..].to_owned(); // Remove "local-" prefix if *index < 1 || *index > response.hits.len() {
let url = format!( // TODO return useful error instead of panicking
"https://{}/api/v1/mod/{}", panic!("Index {} is out of bounds", index);
ctx.config.upstream.server_address, mod_id }
);
let response = client.get(url).send().await?;
let response = response.json::<ModInfo>().await?;
Ok(response)
}
async fn fetch_mod_version(ctx: &AppContext, version_id: &String) -> anyhow::Result<ModVersion> { // input is indexed from 1, but results are indexed from 0
let client = reqwest::Client::new(); let index = index - 1;
let url = format!(
"https://{}/api/v1/version/{}",
ctx.config.upstream.server_address, version_id
);
let response = client.get(url).send().await?;
let response = response.json::<ModVersion>().await?;
Ok(response)
}
async fn download_version_file(ctx: &AppContext, file: &ModVersionFile) -> anyhow::Result<()> { index
// TODO replace all uses of .unwrap() with proper error codes })
let filename = &file.filename; .collect();
// TODO make confirmation skippable with flag argument Ok(selected)
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 client = reqwest::Client::new();
let url = &file.url;
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 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(())
} }
async fn cmd_get(ctx: &AppContext, search_args: SearchArgs) -> anyhow::Result<()> { async fn cmd_get(ctx: &AppContext, search_args: SearchArgs) -> anyhow::Result<()> {
let response = search_mods(ctx, &search_args).await?; let client = HopperClient::new(ctx.config.clone());
let response = client.search_mods(&search_args).await?;
if response.hits.is_empty() { if response.hits.is_empty() {
// TODO formatting // TODO formatting
@ -165,16 +90,17 @@ async fn cmd_get(ctx: &AppContext, search_args: SearchArgs) -> anyhow::Result<()
return Ok(()); return Ok(());
} }
for to_get in selected.iter() { for selection in selected.iter() {
let mod_info = fetch_mod_info(ctx, to_get).await?; let to_get = &response.hits[*selection];
let mod_info = client.fetch_mod_info(to_get).await?;
// TODO allow the user to select multiple versions // TODO allow the user to select multiple versions
if let Some(version_id) = mod_info.versions.first() { if let Some(version_id) = mod_info.versions.first() {
println!("fetching version {}", version_id); println!("fetching version {}", version_id);
let version = fetch_mod_version(ctx, version_id).await?; let version = client.fetch_mod_version(version_id).await?;
for file in version.files.iter() { for file in version.files.iter() {
download_version_file(ctx, file).await?; client.download_version_file(&ctx.args, file).await?;
} }
} }
} }
@ -185,7 +111,7 @@ async fn cmd_get(ctx: &AppContext, search_args: SearchArgs) -> anyhow::Result<()
#[tokio::main] #[tokio::main]
async fn main() -> anyhow::Result<()> { async fn main() -> anyhow::Result<()> {
env_logger::init(); env_logger::init();
let args = Args::from_args(); let args = Args::parse();
let config = args.load_config()?; let config = args.load_config()?;
let ctx = AppContext { args, config }; let ctx = AppContext { args, config };
match ctx.args.to_owned().command { match ctx.args.to_owned().command {