Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b2dcf0c997 | ||
|
|
214902ac60 | ||
|
|
538c37f853 | ||
|
|
1bc73258e2 | ||
|
|
eb6400a49d | ||
|
|
f28dbf4272 | ||
|
|
ebbadeb53b | ||
|
|
697f3f3e85 | ||
|
|
2d77d5b57d | ||
|
|
8de8654d64 | ||
|
|
59becfd7c9 | ||
|
|
a2d337397c | ||
|
|
e58da16cdc | ||
|
|
eabe74dba8 | ||
|
|
acfab673a3 | ||
|
|
25a4b90f1f | ||
|
|
464b279570 | ||
|
|
913d2c9254 | ||
|
|
874c38d7f8 | ||
|
|
51ec22ad67 | ||
|
|
894a0d6cf8 | ||
|
|
526db91665 | ||
|
|
017f7e4d17 | ||
|
|
c2e039e412 | ||
|
|
ad039cab05 | ||
|
|
41707c8a09 | ||
|
|
b5c680ed55 | ||
|
|
8adadf75a8 | ||
|
|
9c54e8f321 | ||
|
|
65edd0b31b | ||
|
|
ce0bb34401 | ||
|
|
f5068d09d2 | ||
|
|
7cbfe9cd0d | ||
|
|
3479a05e63 | ||
|
|
8998139934 | ||
|
|
7ead3706a2 | ||
|
|
9cd454cee2 | ||
|
|
eb53c7164e | ||
|
|
00ba2faffe | ||
|
|
dc351df546 | ||
|
|
eb436c2ab8 | ||
|
|
7362354109 | ||
|
|
615d3fb8fc | ||
|
|
cf9007fa06 | ||
|
|
7ea4860202 | ||
|
|
260ad39c03 | ||
|
|
500d72a473 | ||
|
|
2114cdc72a | ||
|
|
4de886fcd0 | ||
|
|
75c74333c5 | ||
|
|
0d1cafcb10 | ||
|
|
3149b96971 | ||
|
|
2b6750a971 | ||
|
|
22a3eebe78 | ||
|
|
7e7e5c0c31 | ||
|
|
783fb76f06 | ||
|
|
04c92f17bf | ||
|
|
3525c7b69c | ||
|
|
6167cc8f2a | ||
|
|
9d76f852aa | ||
|
|
68bbf6fc1c | ||
|
|
df4feaa5a1 | ||
|
|
495f31778b | ||
|
|
69a1010d4a | ||
|
|
cef09e32ad | ||
|
|
28c0731478 | ||
|
|
9d480f8bfb | ||
|
|
978fd3e971 | ||
|
|
bdc78c54e7 | ||
|
|
3259608c3b | ||
|
|
1747e64278 | ||
|
|
a529a4cb35 | ||
|
|
9932de1c73 | ||
|
|
88dfef51ad | ||
|
|
644afd430a | ||
|
|
884a0b6df3 | ||
|
|
38cd978f29 | ||
|
|
de61fb747f | ||
|
|
38d240ba7b | ||
|
|
a78bcff171 | ||
|
|
d38b0b74b5 | ||
|
|
902b0e9347 | ||
|
|
af6d0b003b | ||
|
|
a7ace33ae1 | ||
|
|
dcefb3b7ba | ||
|
|
8c7bbb9a79 | ||
|
|
53a95c6022 | ||
|
|
2b900253d0 | ||
|
|
e77ae06bea | ||
|
|
3f2f514097 | ||
|
|
297a52aed8 |
No files matched your search
@@ -0,0 +1 @@
|
||||
github: objz
|
||||
@@ -18,7 +18,7 @@ body:
|
||||
paste relevant log output here. you can find logs at:
|
||||
|
||||
- **rmcl logs**: `~/.cache/rmcl/` (per-session files like `rmcl_2026-04-20_12-34-56.log`)
|
||||
- **launch logs**: `~/.local/share/rmcl/instances/{instance}/.minecraft/logs/launches/`
|
||||
- **launch logs**: `~/.local/share/rmcl/instances/{instance}/minecraft/logs/launches/`
|
||||
|
||||
you can also view logs in the TUI via the log overlay or use `rmcl log` from the CLI.
|
||||
render: text
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# cargo-dist artifact building and publishing, called by release.yml.
|
||||
# Based on cargo-dist's generated GitHub workflow.
|
||||
|
||||
name: build release
|
||||
@@ -13,7 +12,6 @@ on:
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
# Run 'dist plan' (or host) to determine what tasks we need to do
|
||||
plan:
|
||||
runs-on: "ubuntu-22.04"
|
||||
outputs:
|
||||
@@ -39,11 +37,6 @@ jobs:
|
||||
with:
|
||||
name: cargo-dist-cache
|
||||
path: ~/.cargo/bin/dist
|
||||
# sure would be cool if github gave us proper conditionals...
|
||||
# so here's a doubly-nested ternary-via-truthiness to try to provide the best possible
|
||||
# functionality based on whether this is a pull_request, and whether it's from a fork.
|
||||
# (PRs run on the *source* but secrets are usually on the *target* -- that's *good*
|
||||
# but also really annoying to build CI around when it needs secrets to work right.)
|
||||
- id: plan
|
||||
run: |
|
||||
dist host --steps=create --tag=${{ inputs.tag }} --output-format=json > plan-dist-manifest.json
|
||||
@@ -56,25 +49,13 @@ jobs:
|
||||
name: artifacts-plan-dist-manifest
|
||||
path: plan-dist-manifest.json
|
||||
|
||||
# Build and packages all the platform-specific things
|
||||
build-local-artifacts:
|
||||
name: build-local-artifacts (${{ join(matrix.targets, ', ') }})
|
||||
# Let the initial task tell us to not run (currently very blunt)
|
||||
needs:
|
||||
- plan
|
||||
if: ${{ fromJson(needs.plan.outputs.val).ci.github.artifacts_matrix.include != null && (needs.plan.outputs.publishing == 'true' || fromJson(needs.plan.outputs.val).ci.github.pr_run_mode == 'upload') }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
# Target platforms/runners are computed by dist in create-release.
|
||||
# Each member of the matrix has the following arguments:
|
||||
#
|
||||
# - runner: the github runner
|
||||
# - dist-args: cli flags to pass to dist
|
||||
# - install-dist: expression to run to install dist on the runner
|
||||
#
|
||||
# Typically there will be:
|
||||
# - 1 "global" task that builds universal installers
|
||||
# - N "local" tasks that build each platform's binaries and platform-specific installers
|
||||
matrix: ${{ fromJson(needs.plan.outputs.val || '{"ci":{"github":{"artifacts_matrix":{"include":[]}}}}').ci.github.artifacts_matrix }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
container: ${{ matrix.container && matrix.container.image || null }}
|
||||
@@ -108,7 +89,6 @@ jobs:
|
||||
run: sudo apt-get update && sudo apt-get install --yes libxcb1-dev
|
||||
- name: Install dist
|
||||
run: ${{ matrix.install_dist.run }}
|
||||
# Get the dist-manifest
|
||||
- name: Fetch local artifacts
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
@@ -120,7 +100,6 @@ jobs:
|
||||
${{ matrix.packages_install }}
|
||||
- name: Build artifacts
|
||||
run: |
|
||||
# Actually do builds and make zips and whatnot
|
||||
dist build ${{ needs.plan.outputs.tag-flag }} --print=linkage --output-format=json ${{ matrix.dist_args }} > dist-manifest.json
|
||||
echo "dist ran successfully"
|
||||
- id: cargo-dist
|
||||
@@ -130,7 +109,6 @@ jobs:
|
||||
# inconsistent syntax between shell and powershell.
|
||||
shell: bash
|
||||
run: |
|
||||
# Parse out what we just built and upload it to scratch storage
|
||||
echo "paths<<EOF" >> "$GITHUB_OUTPUT"
|
||||
dist print-upload-files-from-manifest --manifest dist-manifest.json >> "$GITHUB_OUTPUT"
|
||||
echo "EOF" >> "$GITHUB_OUTPUT"
|
||||
@@ -144,7 +122,6 @@ jobs:
|
||||
${{ steps.cargo-dist.outputs.paths }}
|
||||
${{ env.BUILD_MANIFEST_NAME }}
|
||||
|
||||
# Build and package all the platform-agnostic(ish) things
|
||||
build-global-artifacts:
|
||||
needs:
|
||||
- plan
|
||||
@@ -165,7 +142,6 @@ jobs:
|
||||
name: cargo-dist-cache
|
||||
path: ~/.cargo/bin/
|
||||
- run: chmod +x ~/.cargo/bin/dist
|
||||
# Get all the local artifacts for the global tasks to use (for e.g. checksums)
|
||||
- name: Fetch local artifacts
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
@@ -178,7 +154,6 @@ jobs:
|
||||
dist build ${{ needs.plan.outputs.tag-flag }} --output-format=json "--artifacts=global" > dist-manifest.json
|
||||
echo "dist ran successfully"
|
||||
|
||||
# Parse out what we just built and upload it to scratch storage
|
||||
echo "paths<<EOF" >> "$GITHUB_OUTPUT"
|
||||
jq --raw-output ".upload_files[]" dist-manifest.json >> "$GITHUB_OUTPUT"
|
||||
echo "EOF" >> "$GITHUB_OUTPUT"
|
||||
@@ -191,13 +166,11 @@ jobs:
|
||||
path: |
|
||||
${{ steps.cargo-dist.outputs.paths }}
|
||||
${{ env.BUILD_MANIFEST_NAME }}
|
||||
# Determines if we should publish/announce
|
||||
host:
|
||||
needs:
|
||||
- plan
|
||||
- build-local-artifacts
|
||||
- build-global-artifacts
|
||||
# Only run if we're "publishing", and only if plan, local and global didn't fail (skipped is fine)
|
||||
if: ${{ always() && needs.plan.result == 'success' && needs.plan.outputs.publishing == 'true' && (needs.build-global-artifacts.result == 'skipped' || needs.build-global-artifacts.result == 'success') && (needs.build-local-artifacts.result == 'skipped' || needs.build-local-artifacts.result == 'success') }}
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -218,7 +191,6 @@ jobs:
|
||||
name: cargo-dist-cache
|
||||
path: ~/.cargo/bin/
|
||||
- run: chmod +x ~/.cargo/bin/dist
|
||||
# Fetch artifacts from scratch-storage
|
||||
- name: Fetch artifacts
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
@@ -235,10 +207,8 @@ jobs:
|
||||
- name: "Upload dist-manifest.json"
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
# Overwrite the previous copy
|
||||
name: artifacts-dist-manifest
|
||||
path: dist-manifest.json
|
||||
# Create a GitHub Release while uploading all files to it
|
||||
- name: "Download GitHub Artifacts"
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
@@ -260,12 +230,17 @@ jobs:
|
||||
env:
|
||||
PRERELEASE_FLAG: "${{ fromJson(steps.host.outputs.manifest).announcement_is_prerelease && '--prerelease' || '' }}"
|
||||
ANNOUNCEMENT_TITLE: "${{ fromJson(steps.host.outputs.manifest).announcement_title }}"
|
||||
RELEASE_COMMIT: "${{ github.sha }}"
|
||||
CHANGELOG: "${{ steps.changelog.outputs.content }}"
|
||||
RELEASE_TAG: "${{ needs.plan.outputs.tag }}"
|
||||
APP_VERSION: "${{ fromJson(steps.host.outputs.manifest).releases[0].app_version }}"
|
||||
PUBLISH_WINGET: "${{ !fromJson(needs.plan.outputs.val).announcement_is_prerelease || fromJson(needs.plan.outputs.val).publish_prereleases }}"
|
||||
run: |
|
||||
RELEASE_COMMIT="$(git rev-parse HEAD)"
|
||||
echo "$CHANGELOG" > $RUNNER_TEMP/notes.txt
|
||||
WINGET_MANIFEST_NOTE=""
|
||||
if [[ "$PUBLISH_WINGET" == true ]]; then
|
||||
WINGET_MANIFEST_NOTE="The generated WinGet manifest is attached as \`winget-manifest-${APP_VERSION}.zip\` for local validation."
|
||||
fi
|
||||
cat >> $RUNNER_TEMP/notes.txt <<EOF
|
||||
|
||||
## downloads
|
||||
@@ -301,7 +276,7 @@ jobs:
|
||||
winget install Objz.Rmcl
|
||||
\`\`\`
|
||||
|
||||
The generated WinGet manifest is attached as \`winget-manifest-${APP_VERSION}.zip\` for local validation.
|
||||
$WINGET_MANIFEST_NOTE
|
||||
|
||||
### AUR
|
||||
|
||||
@@ -330,7 +305,6 @@ jobs:
|
||||
persist-credentials: true
|
||||
repository: ${{ env.HOMEBREW_TAP_REPOSITORY }}
|
||||
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
# So we have access to the formula
|
||||
- name: Fetch homebrew formulae
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
@@ -379,7 +353,6 @@ jobs:
|
||||
plan: ${{ needs.plan.outputs.val }}
|
||||
dry_run: false
|
||||
secrets: inherit
|
||||
# publish jobs get escalated permissions
|
||||
permissions:
|
||||
"contents": "read"
|
||||
|
||||
@@ -392,7 +365,6 @@ jobs:
|
||||
with:
|
||||
plan: ${{ needs.plan.outputs.val }}
|
||||
secrets: inherit
|
||||
# publish jobs get escalated permissions
|
||||
permissions:
|
||||
"contents": "read"
|
||||
|
||||
@@ -405,27 +377,5 @@ jobs:
|
||||
with:
|
||||
plan: ${{ needs.plan.outputs.val }}
|
||||
secrets: inherit
|
||||
# publish jobs get escalated permissions
|
||||
permissions:
|
||||
"contents": "write"
|
||||
|
||||
announce:
|
||||
needs:
|
||||
- plan
|
||||
- host
|
||||
- publish-homebrew-formula
|
||||
- custom-publish-crates
|
||||
- custom-publish-aur
|
||||
- custom-publish-winget
|
||||
# use "always() && ..." to allow us to wait for all publish jobs while
|
||||
# still allowing individual publish jobs to skip themselves (for prereleases).
|
||||
# "host" however must run to completion, no skipping allowed!
|
||||
if: ${{ always() && needs.host.result == 'success' && (needs.publish-homebrew-formula.result == 'skipped' || needs.publish-homebrew-formula.result == 'success') && (needs.custom-publish-crates.result == 'skipped' || needs.custom-publish-crates.result == 'success') && (needs.custom-publish-aur.result == 'skipped' || needs.custom-publish-aur.result == 'success') && (needs.custom-publish-winget.result == 'skipped' || needs.custom-publish-winget.result == 'success') }}
|
||||
runs-on: "ubuntu-22.04"
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
persist-credentials: false
|
||||
submodules: recursive
|
||||
@@ -32,22 +32,6 @@ jobs:
|
||||
components: rustfmt
|
||||
- run: cargo fmt --all -- --check
|
||||
|
||||
clippy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ inputs.ref || github.sha }}
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: clippy
|
||||
- uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "21"
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- run: cargo clippy --all-targets --locked -- -D warnings
|
||||
|
||||
build-and-test:
|
||||
name: build and test (${{ matrix.os }})
|
||||
runs-on: ${{ matrix.os }}
|
||||
@@ -61,6 +45,8 @@ jobs:
|
||||
with:
|
||||
ref: ${{ inputs.ref || github.sha }}
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: clippy
|
||||
- uses: actions/setup-java@v5
|
||||
with:
|
||||
distribution: temurin
|
||||
@@ -72,6 +58,7 @@ jobs:
|
||||
if: runner.os == 'Linux'
|
||||
run: sudo apt-get update && sudo apt-get install --yes libxcb1-dev
|
||||
- run: cargo build --locked
|
||||
- run: cargo clippy --all-targets --locked -- -D warnings
|
||||
- run: cargo test --locked --all-targets
|
||||
|
||||
network-tests:
|
||||
|
||||
@@ -35,6 +35,9 @@ jobs:
|
||||
- name: install Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: install Linux build dependencies
|
||||
run: sudo apt-get update && sudo apt-get install --yes libxcb1-dev
|
||||
|
||||
- name: publish to crates.io
|
||||
run: |
|
||||
if [ "${{ inputs.dry_run }}" = "true" ]; then
|
||||
|
||||
@@ -11,16 +11,27 @@ concurrency:
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
resolve:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
sha: ${{ steps.checkout.outputs.commit }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
id: checkout
|
||||
with:
|
||||
ref: master
|
||||
|
||||
checks:
|
||||
needs: resolve
|
||||
uses: ./.github/workflows/checks.yml
|
||||
with:
|
||||
network-tests: true
|
||||
ref: master
|
||||
ref: ${{ needs.resolve.outputs.sha }}
|
||||
secrets:
|
||||
curseforge-api-key: ${{ secrets.CURSEFORGE_API_KEY }}
|
||||
|
||||
prepare:
|
||||
needs: checks
|
||||
needs: [resolve, checks]
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
release: ${{ steps.version.outputs.release }}
|
||||
@@ -28,7 +39,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
ref: master
|
||||
ref: ${{ needs.resolve.outputs.sha }}
|
||||
fetch-depth: 0
|
||||
fetch-tags: true
|
||||
|
||||
@@ -39,23 +50,8 @@ jobs:
|
||||
set -euo pipefail
|
||||
|
||||
version=$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[] | select(.name == "rmcl") | .version')
|
||||
mapfile -t versions < <(git tag --list 'v*' --sort=-v:refname | sed -nE 's/^v([0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?)$/\1/p')
|
||||
latest=${versions[0]:-}
|
||||
tag="v${version}"
|
||||
release=false
|
||||
|
||||
if [[ -z "$latest" ]] || [[ "$version" != "$latest" && "$(printf '%s\n%s\n' "$latest" "$version" | sort -V | tail -n1)" == "$version" ]]; then
|
||||
release=true
|
||||
fi
|
||||
|
||||
echo "release=$release" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=$tag" >> "$GITHUB_OUTPUT"
|
||||
|
||||
if [[ "$release" == true ]]; then
|
||||
echo "releasing $tag (latest release: ${latest:-none})"
|
||||
else
|
||||
echo "Cargo.toml version $version is not newer than latest release v$latest; nothing to release"
|
||||
fi
|
||||
python3 scripts/release-version.py --check
|
||||
python3 scripts/release-version.py "$version"
|
||||
|
||||
- name: create tag
|
||||
if: steps.version.outputs.release == 'true'
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
/target
|
||||
/scripts
|
||||
*.log
|
||||
result
|
||||
result-*
|
||||
.direnv
|
||||
+76
-32
@@ -1,55 +1,99 @@
|
||||
# contributing
|
||||
# Contributing to rmcl
|
||||
|
||||
thanks for wanting to contribute. here's how we/I do things around here.
|
||||
Bug reports, fixes, documentation, and themes are welcome. For a larger feature or
|
||||
architectural change, open an issue first so we can agree on the approach before
|
||||
you spend time implementing it.
|
||||
|
||||
## code style
|
||||
## Reporting bugs
|
||||
|
||||
### comments
|
||||
Search the [existing issues](https://github.com/objz/rmcl/issues) before opening a
|
||||
new one. Include your rmcl version, operating system, steps to reproduce, and what
|
||||
you expected to happen. For game-launch problems, include the Minecraft version
|
||||
and mod loader; for TUI problems, include your terminal and a screenshot if useful.
|
||||
|
||||
preferred are `//` comments with a lowercase, casual tone. try to explain **why** something is done rather than restating what the code does. file-level comments are nice for describing what a file is responsible for, and function-level comments help when the behavior isn't obvious. enum variants and struct fields usually don't need comments if the names are clear enough. basically just look at how existing comments are written and match that vibe.
|
||||
Relevant logs help, but remove tokens, account details, and other private
|
||||
information before posting them. See the [README](README.md#logs) for log locations.
|
||||
|
||||
### visibility and naming
|
||||
## Development setup
|
||||
|
||||
try to keep visibility as narrow as makes sense. `pub` when something is actually used outside the crate, `pub(crate)` across modules, `pub(super)` within a module. don't leave things `pub` just because they might be useful someday. function names should ideally be clear enough that you don't need a comment to explain what they do.
|
||||
You need a stable Rust toolchain and a JDK with `javac` and `jar` on `PATH`.
|
||||
CI uses JDK 21. On Linux, install the libxcb development package (`libxcb1-dev` on
|
||||
Debian/Ubuntu, `libxcb` on Arch).
|
||||
|
||||
### modules and file organization
|
||||
Fork the repository and create a branch for your change. The
|
||||
[source build instructions](README.md#from-source) cover cloning and building.
|
||||
Run the development version with `cargo run --locked`, or use
|
||||
`cargo run --locked -- --help` to see the CLI commands.
|
||||
|
||||
each file should have one clear responsibility. if a file starts doing two unrelated things, split it up. when a module gets big enough, convert `foo.rs` into `foo/mod.rs` with submodules. keep format-specific or protocol-specific code in its own file (e.g. `mrpack.rs` for modrinth, `mmc.rs` for multimc) and put shared types and dispatching in `mod.rs`. the general idea is that you shouldn't find multimc logic in the modrinth file or vice versa.
|
||||
The main parts of the codebase are:
|
||||
|
||||
### tests
|
||||
- `src/cli/`: command-line commands and output.
|
||||
- `src/config/`: settings, paths, and themes.
|
||||
- `src/instance/`: instance management, content, modpack imports, loaders, and launches.
|
||||
- `src/net/`: HTTP requests, downloads, and service API clients.
|
||||
- `src/tui/`: the terminal interface.
|
||||
- `tests/`: integration tests; unit tests are under `src/`.
|
||||
|
||||
every test should cover a distinct code path. don't test the same branch twice with just different inputs. test names should describe the scenario, not just the function name. no need to test trivially correct code.
|
||||
## Making changes
|
||||
|
||||
### general advice
|
||||
Keep each pull request focused on one fix or feature. Follow the style of nearby
|
||||
code and reuse existing helpers where they fit. Keep public APIs and new
|
||||
dependencies limited to what the change needs.
|
||||
|
||||
- avoid "obvious" comments like `// save the profile` right above `save_profile()`
|
||||
- avoid unnecessary abstractions or wrappers for things that only happen once
|
||||
- avoid speculative features or "just in case" parameters
|
||||
- prefer iterating directly over collecting into a vec when you only need one pass
|
||||
- match existing error handling patterns, usually `map_err` with `format!`
|
||||
Comments should explain a decision, constraint, or non-obvious behavior. There is
|
||||
no need to describe what a clearly named function already does. Keep modules
|
||||
organized by responsibility without splitting files just to meet a size target.
|
||||
|
||||
## architecture
|
||||
For a bug fix, add a regression test that fails without the fix. For new behavior,
|
||||
cover the cases that could break. Use test names that describe the scenario and
|
||||
avoid repeating coverage unless the inputs exercise different behavior.
|
||||
|
||||
the codebase is split roughly like this:
|
||||
## Testing
|
||||
|
||||
- `src/cli/` handles command line interface
|
||||
- `src/config/` has settings, paths, theme config
|
||||
- `src/instance/` is the core. `content/` scans mods, resource packs, shaders, worlds. `import/` handles modpack importing with `mod.rs` dispatching to format-specific modules like `mrpack.rs` and `mmc.rs`. `loader/` installs mod loaders (fabric, forge, neoforge, quilt). `launch/` builds the java command and spawns minecraft, with `patches.rs` handling lwjgl3ify classpath patches. `manager.rs` does instance CRUD
|
||||
- `src/net/` is the networking layer. http client, file downloads, and API clients per service
|
||||
- `src/tui/` is the terminal UI built with ratatui
|
||||
Run the same checks as CI before submitting code changes:
|
||||
|
||||
### adding a new import format
|
||||
```sh
|
||||
cargo fmt --all -- --check
|
||||
cargo build --locked
|
||||
cargo clippy --all-targets --locked -- -D warnings
|
||||
cargo test --locked --all-targets
|
||||
```
|
||||
|
||||
create a new file in `src/instance/import/`, add the variant to `PackFormat` in `mod.rs`, add detection logic in `detect_format()`, and add the dispatch arms in `build_summary()` and `execute_import()`.
|
||||
Live-service tests are ignored by default. If you run them, note that in the PR,
|
||||
along with any failures caused by network access or provider credentials.
|
||||
|
||||
### adding a new mod loader
|
||||
Check visual and input changes in a real terminal as well as the automated TUI
|
||||
tests. CI covers Linux, macOS, and Windows; say which platforms you tested locally
|
||||
and mention anything you could not verify.
|
||||
|
||||
create a new file in `src/instance/loader/` implementing `ModLoaderInstaller`, add the variant to `ModLoader` in `models.rs`, and register it in `get_installer()`.
|
||||
## Pull requests
|
||||
|
||||
## commits
|
||||
Open your PR against `master`. Explain the problem, summarize the change, link any
|
||||
related issue, and list the checks you ran. Screenshots or a short recording are
|
||||
useful for visible TUI changes. Use descriptive commit messages and keep unrelated
|
||||
changes in separate commits or PRs.
|
||||
|
||||
start with what you did: `added`, `fixed`, `refactored`, etc. lowercase. separate logical changes into separate commits. don't bundle unrelated things into one commit.
|
||||
Be available to answer review questions and make follow-up changes. Passing CI
|
||||
is required before merging, but maintainers may still request changes to the
|
||||
implementation or scope.
|
||||
|
||||
## before submitting
|
||||
## AI and LLM assistance
|
||||
|
||||
make sure `cargo build`, `cargo clippy`, and `cargo test` all pass. you'll need a JDK (`javac` and `jar` on PATH) for the build script that compiles the java shim.
|
||||
AI-assisted contributions are welcome. You are responsible for the code, tests,
|
||||
and documentation you submit, including anything generated by a tool. Review the
|
||||
changes yourself, verify the behavior, and be prepared to explain the implementation.
|
||||
|
||||
If an LLM helped produce your contribution, disclose it in the PR description.
|
||||
Name the tool or model, describe which parts it helped with, and say how you
|
||||
reviewed and tested the result. A short note is enough, for example:
|
||||
|
||||
> AI assistance: ChatGPT helped draft the tests. I reviewed the assertions and ran
|
||||
> the relevant tests locally.
|
||||
|
||||
Use your own words in issue reports, PR summaries, and review replies. Maintainers
|
||||
may close contributions that have not been reviewed or that the author cannot explain.
|
||||
|
||||
## License
|
||||
|
||||
Contributions are covered by the project's [GPL-3.0-only license](LICENSE).
|
||||
Only submit code and assets you have the right to contribute under those terms.
|
||||
Generated
+13
-35
@@ -1001,16 +1001,6 @@ dependencies = [
|
||||
"dirs-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dirs-next"
|
||||
version = "2.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b98cf8ebf19c3d1b223e151f99a4f9f0690dca41414773390fc824184ac833e1"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"dirs-sys-next",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dirs-sys"
|
||||
version = "0.5.0"
|
||||
@@ -1019,21 +1009,10 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"option-ext",
|
||||
"redox_users 0.5.2",
|
||||
"redox_users",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dirs-sys-next"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"redox_users 0.4.6",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dispatch2"
|
||||
version = "0.3.1"
|
||||
@@ -1100,6 +1079,12 @@ version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
|
||||
|
||||
[[package]]
|
||||
name = "dunce"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.15.0"
|
||||
@@ -2879,6 +2864,7 @@ version = "5.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f3bab717c29a857abf75fcef718d441ec7cb2725f937343c734740a985d37fd"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"is-wsl",
|
||||
"libc",
|
||||
"pathdiff",
|
||||
@@ -3721,17 +3707,6 @@ dependencies = [
|
||||
"bitflags 2.13.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_users"
|
||||
version = "0.4.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43"
|
||||
dependencies = [
|
||||
"getrandom 0.2.17",
|
||||
"libredox",
|
||||
"thiserror 1.0.69",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_users"
|
||||
version = "0.5.2"
|
||||
@@ -3881,16 +3856,16 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rmcl"
|
||||
version = "0.5.0"
|
||||
version = "0.6.3"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64",
|
||||
"chrono",
|
||||
"clap",
|
||||
"color-eyre",
|
||||
"config",
|
||||
"crossterm 0.29.0",
|
||||
"dirs",
|
||||
"dirs-next",
|
||||
"display-info",
|
||||
"fast-strip-ansi",
|
||||
"fastnbt",
|
||||
@@ -3899,6 +3874,7 @@ dependencies = [
|
||||
"html-to-markdown-rs",
|
||||
"image",
|
||||
"insta",
|
||||
"libc",
|
||||
"libcasr",
|
||||
"log",
|
||||
"minecraft-msa-auth",
|
||||
@@ -3918,6 +3894,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha1 0.10.7",
|
||||
"sha2",
|
||||
"shlex",
|
||||
"tachyonfx",
|
||||
"tempfile",
|
||||
"thiserror 2.0.18",
|
||||
@@ -3936,6 +3913,7 @@ dependencies = [
|
||||
"tui-widget-list",
|
||||
"unicode-segmentation",
|
||||
"which",
|
||||
"windows-sys 0.61.2",
|
||||
"wiremock",
|
||||
"zip",
|
||||
]
|
||||
|
||||
+10
-5
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "rmcl"
|
||||
version = "0.5.0"
|
||||
version = "0.6.3"
|
||||
authors = ["objz"]
|
||||
edition = "2024"
|
||||
description = "A fully featured Minecraft TUI launcher"
|
||||
@@ -24,13 +24,13 @@ path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
async-trait = "0.1"
|
||||
base64 = "0.22"
|
||||
chrono = { version = "0.4.39", features = ["serde"] }
|
||||
clap = "4.5.27"
|
||||
color-eyre = "0.6.3"
|
||||
config = "0.15.6"
|
||||
crossterm = "0.29.0"
|
||||
display-info = "0.5.9"
|
||||
dirs-next = "2.0.0"
|
||||
log = "0.4"
|
||||
ratatui = { version = "0.30.0", features = ["serde", "unstable-rendered-line-info"] }
|
||||
ratatui-themekit = { version = "0.6", features = ["serde"] }
|
||||
@@ -64,7 +64,7 @@ image = { version = "0.25", default-features = false, features = ["gif", "jpeg",
|
||||
zip = "8.5.1"
|
||||
minecraft-msa-auth = "0.4.0"
|
||||
oauth2 = "5.0.0"
|
||||
open = "5"
|
||||
open = { version = "5", features = ["shellexecute-on-windows"] }
|
||||
which = "8.0.2"
|
||||
dirs = "6.0.0"
|
||||
notify = "8"
|
||||
@@ -74,7 +74,14 @@ libcasr = "2.13"
|
||||
fs2 = "0.4"
|
||||
fastnbt = "2.6.2"
|
||||
flate2 = "1.1.9"
|
||||
tempfile = "3"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
shlex = "1.3"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_System_Diagnostics_ToolHelp", "Win32_UI_Shell"] }
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
@@ -87,8 +94,6 @@ inherits = "release"
|
||||
lto = "thin"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
insta = "1"
|
||||
wiremock = "0.6"
|
||||
rstest = "0.23"
|
||||
image = { version = "0.25", default-features = false, features = ["png", "webp"] }
|
||||
@@ -43,16 +43,10 @@ it does everything you'd expect from a launcher.
|
||||
|
||||
### modpacks and accounts
|
||||
|
||||
Browse Modrinth and CurseForge modpacks or import Modrinth, CurseForge, MultiMC, Prism, and GTNH packs directly. Direct imports accept a file, Modrinth URL, or project slug. Source builds enable CurseForge when `CURSEFORGE_API_KEY` is set at compile time. Able to use multiple Microsoft accounts and offline accounts aswell.
|
||||
Browse Modrinth and CurseForge modpacks or import Modrinth, CurseForge, and MultiMC/Prism archives (including GTNH packs in that format). Direct imports accept a local archive, Modrinth URL, or Modrinth project slug. CurseForge requires a build-time [API key](#curseforge-api). Multiple Microsoft accounts and offline accounts are supported.
|
||||
|
||||
---
|
||||
|
||||
## authentication
|
||||
|
||||
rmcl uses its own Microsoft client ID for Minecraft account authentication.
|
||||
|
||||
Authentication is performed through Microsoft’s official services.
|
||||
|
||||
## installation
|
||||
|
||||
[](https://github.com/objz/rmcl/releases)
|
||||
@@ -68,12 +62,19 @@ prebuilt archives are attached to each GitHub release.
|
||||
brew install objz/tap/rmcl
|
||||
```
|
||||
|
||||
Linux archives and Homebrew installations require the system `libxcb` runtime
|
||||
package (`libxcb1` on Debian/Ubuntu, `libxcb` on Arch).
|
||||
|
||||
An ARM64 launcher build still needs Minecraft natives for that platform. For
|
||||
example, Minecraft 1.20.1 supplies macOS ARM64 natives but no Linux ARM64 natives;
|
||||
using a custom GLFW library alone does not provide the other required libraries.
|
||||
|
||||
### Windows
|
||||
|
||||
release builds include a `.zip` archive and an `.msi`. WinGet packages are
|
||||
submitted from release CI and become available after review.
|
||||
|
||||
[](https://winstall.app/apps/Objz.Rmcl)
|
||||
[](https://winstall.app/apps/Objz.Rmcl)
|
||||
```powershell
|
||||
# WinGet
|
||||
winget install Objz.Rmcl
|
||||
@@ -96,6 +97,25 @@ paru -S rmcl-bin
|
||||
paru -S rmcl-git
|
||||
```
|
||||
|
||||
### Nix
|
||||
|
||||
[](https://github.com/objz/rmcl)
|
||||
|
||||
```sh
|
||||
nix run github:objz/rmcl
|
||||
nix profile install github:objz/rmcl
|
||||
```
|
||||
|
||||
the flake builds rmcl from source. To use your own key instead, override it
|
||||
at build time:
|
||||
|
||||
```sh
|
||||
CURSEFORGE_API_KEY=your-key nix build --impure .#
|
||||
```
|
||||
|
||||
Minecraft 1.12 and older currently fail to launch because rmcl doesn't pass
|
||||
`-Djava.library.path` for legacy version profiles.
|
||||
|
||||
### Cargo
|
||||
|
||||
[](https://crates.io/crates/rmcl)
|
||||
@@ -106,6 +126,7 @@ cargo install rmcl
|
||||
### from source
|
||||
|
||||
requires a Rust toolchain and a JDK (`javac` and `jar` on `PATH`).
|
||||
Linux builds also require the libxcb development package (`libxcb1-dev` on Debian/Ubuntu, `libxcb` on Arch).
|
||||
|
||||
```sh
|
||||
git clone https://github.com/objz/rmcl.git
|
||||
@@ -115,6 +136,50 @@ cargo build --release
|
||||
|
||||
---
|
||||
|
||||
## navigation
|
||||
|
||||
Use `Ctrl` + arrow keys to move between the Instances, Content, Accounts,
|
||||
Settings, and Overview panels. In Content, use plain `Left` / `Right` or `h` / `l`
|
||||
to switch tabs, and `Tab` to switch between installed content and discovery.
|
||||
|
||||
Content can be installed, updated, removed, or enabled/disabled while a game is
|
||||
running. Mods normally apply on the next launch; packs and configs may reload
|
||||
live, and the operating system can still reject changes to open files. Instance
|
||||
deletion, renaming, world deletion/renaming, runtime changes, and whole-modpack replacement require stopping it.
|
||||
|
||||
## exporting modpacks
|
||||
|
||||
Export modpacks from the TUI or CLI as CurseForge (`curseforge`, the default),
|
||||
Modrinth (`mrpack`) or MultiMC/Prism (`mmc`) archives.
|
||||
|
||||
```sh
|
||||
rmcl export "My Instance" --format curseforge --output pack.zip
|
||||
```
|
||||
|
||||
Worlds, logs and personal settings are excluded by default. Add files with
|
||||
repeatable `--include` options. CurseForge and Modrinth reference matching downloads;
|
||||
`--bundle-unmatched` allows copying unmatched content after you check redistribution
|
||||
permissions. MultiMC/Prism bundles files and works offline.
|
||||
|
||||
Choose a new output path outside the game folder. For standalone folders, use
|
||||
`--directory` instead of an instance name; see `rmcl export --help` for options.
|
||||
|
||||
## authentication
|
||||
|
||||
rmcl uses its own Microsoft client ID for Minecraft account authentication.
|
||||
|
||||
Authentication is performed through Microsoft’s official services.
|
||||
|
||||
## CurseForge API
|
||||
|
||||
Git, source, and Cargo builds use rmcl's dedicated API key unless `CURSEFORGE_API_KEY` is set at compile time. An empty or whitespace-only override disables CurseForge.
|
||||
Use of the API is subject to the [CurseForge 3rd Party API Terms and Conditions](https://support.curseforge.com/en/support/solutions/articles/9000207405-curse-forge-3rd-party-api-terms-and-conditions).
|
||||
Keys supplied for rmcl are for rmcl builds only. Forks, rebranded applications,
|
||||
and unrelated projects must use their own key. Keys included in source or compiled
|
||||
binaries are extractable; do not publish a private key.
|
||||
|
||||
---
|
||||
|
||||
## where things live
|
||||
|
||||
### config & data
|
||||
@@ -124,17 +189,22 @@ settings, accounts, instances, and cached game metadata.
|
||||
| what | Linux | macOS | Windows |
|
||||
|---|---|---|---|
|
||||
| config (`config.toml`, `theme.toml`, `accounts.json`) | `~/.config/rmcl/` | `~/Library/Application Support/rmcl/` | `%APPDATA%\rmcl\` |
|
||||
| instances | `~/.local/share/rmcl/instances/` | `~/Library/Application Support/rmcl/instances/` | `%LOCALAPPDATA%\rmcl\instances\` |
|
||||
| metadata (versions, libraries, assets, loader profiles) | `~/.local/share/rmcl/meta/` | `~/Library/Application Support/rmcl/meta/` | `%LOCALAPPDATA%\rmcl\meta\` |
|
||||
| instances | `~/.local/share/rmcl/instances/` | `~/Library/Application Support/rmcl/instances/` | `%APPDATA%\rmcl\instances\` |
|
||||
| metadata (versions, libraries, assets, loader profiles) | `~/.local/share/rmcl/meta/` | `~/Library/Application Support/rmcl/meta/` | `%APPDATA%\rmcl\meta\` |
|
||||
|
||||
each instance has an `instance.json` for its config and a `.minecraft/` directory with the actual game files.
|
||||
These are default locations. On Linux, `XDG_CONFIG_HOME`, `XDG_DATA_HOME`, and
|
||||
`XDG_CACHE_HOME` override the corresponding base directories. Instance and metadata
|
||||
paths can also be changed in `config.toml`.
|
||||
|
||||
Launcher settings can be edited from the TUI or in `config.toml`. Changes to
|
||||
`instances_dir`, `meta_dir`, and `image_protocol` apply after restarting rmcl;
|
||||
other launcher settings apply immediately. Omitting `java_path` enables automatic
|
||||
Java selection. Global JVM arguments and environment variables are applied before
|
||||
per-instance values. Instances can explicitly inherit the launcher window mode
|
||||
and resolution defaults.
|
||||
each instance has an `instance.json` for its config and a `minecraft/` directory with the actual game files.
|
||||
|
||||
Launcher settings saved through the TUI apply immediately, except changes to
|
||||
`instances_dir`, `meta_dir`, and `image_protocol`, which require a restart.
|
||||
Settings files opened through rmcl's editor shortcut are reloaded after saves;
|
||||
otherwise, restart rmcl after editing `config.toml` externally. When neither global nor instance
|
||||
`java_path` is set, rmcl selects Java automatically. Global JVM arguments and
|
||||
environment variables are applied before per-instance values. Instances can
|
||||
explicitly inherit the launcher window mode and resolution defaults.
|
||||
|
||||
```toml
|
||||
[general]
|
||||
@@ -169,7 +239,7 @@ launcher logs are per-session and contain rmcl's own output. instance launch log
|
||||
| what | Linux | macOS | Windows |
|
||||
|---|---|---|---|
|
||||
| launcher logs | `~/.cache/rmcl/` | `~/Library/Caches/rmcl/` | `%LOCALAPPDATA%\rmcl\` |
|
||||
| instance launch logs | `<instances>/<name>/.minecraft/logs/launches/` | same | same |
|
||||
| instance launch logs | `<instances>/<name>/minecraft/logs/launches/` | same | same |
|
||||
|
||||
---
|
||||
|
||||
@@ -236,7 +306,7 @@ then set `theme = "my-theme"` in `theme.toml`.
|
||||
|
||||
colors accept `"#f97316"`, ANSI names (`"Red"`, `"LightBlue"`), `{ Rgb = [r, g, b] }` or `{ Indexed = n }`.
|
||||
|
||||
note that `[custom]` in `theme.toml` is only for overriding single values of a builtin, it doesn't define a new theme. same for `border_style`, that one lives in `theme.toml`, not in a theme file.
|
||||
note that `[custom]` in `theme.toml` overrides colors of the selected theme, whether built-in or loaded from a file; it doesn't define a standalone theme. `border_style` belongs at the top level of `theme.toml`, not in a custom theme file.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generator: Adobe Illustrator 26.2.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
||||
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
||||
viewBox="0 0 133.2 144.10001" style="enable-background:new 0 0 133.2 144.10001;" xml:space="preserve">
|
||||
<style type="text/css">
|
||||
|
||||
|
Before Width: | Height: | Size: 149 KiB After Width: | Height: | Size: 149 KiB |
@@ -11,7 +11,6 @@ fn main() {
|
||||
let out_dir = env::var("OUT_DIR").unwrap();
|
||||
let out = Path::new(&out_dir);
|
||||
|
||||
// compile RmclShim.java into a jar that gets embedded via include_bytes!
|
||||
let status = Command::new("javac")
|
||||
.arg("-source")
|
||||
.arg("8")
|
||||
@@ -25,7 +24,6 @@ fn main() {
|
||||
|
||||
assert!(status.success(), "javac failed to compile RmclShim.java");
|
||||
|
||||
// package into a jar
|
||||
let jar_path = out.join("rmcl-shim.jar");
|
||||
let status = Command::new("jar")
|
||||
.arg("cfe")
|
||||
|
||||
+1
-38
@@ -1,14 +1,8 @@
|
||||
# git-cliff ~ configuration file
|
||||
# https://git-cliff.org/docs/configuration
|
||||
|
||||
|
||||
[remote.github]
|
||||
owner = "objz"
|
||||
repo = "rmcl"
|
||||
|
||||
[changelog]
|
||||
# A Tera template to be rendered for each release in the changelog.
|
||||
# See https://keats.github.io/tera/docs/#introduction
|
||||
body = """
|
||||
{% if version %}\
|
||||
## {{ version | trim_start_matches(pat="v") }} - {{ timestamp | date(format="%Y-%m-%d") }}
|
||||
@@ -32,41 +26,19 @@ body = """
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
"""
|
||||
# Remove leading and trailing whitespaces from the changelog's body.
|
||||
trim = true
|
||||
# Render body even when there are no releases to process.
|
||||
render_always = true
|
||||
# An array of regex based postprocessors to modify the changelog.
|
||||
postprocessors = [
|
||||
# Replace the placeholder <REPO> with a URL.
|
||||
#{ pattern = '<REPO>', replace = "https://github.com/orhun/git-cliff" },
|
||||
]
|
||||
# render body even when there are no releases to process
|
||||
# render_always = true
|
||||
# output file path
|
||||
# output = "test.md"
|
||||
postprocessors = []
|
||||
|
||||
[git]
|
||||
# Parse commits according to the conventional commits specification.
|
||||
# See https://www.conventionalcommits.org
|
||||
conventional_commits = true
|
||||
# Exclude commits that do not match the conventional commits specification.
|
||||
filter_unconventional = false
|
||||
# Require all commits to be conventional.
|
||||
# Takes precedence over filter_unconventional.
|
||||
require_conventional = false
|
||||
# Split commits on newlines, treating each line as an individual commit.
|
||||
split_commits = false
|
||||
# An array of regex based parsers to modify commit messages prior to further processing.
|
||||
commit_preprocessors = [
|
||||
# Replace issue numbers in commit messages with links.
|
||||
{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](https://github.com/objz/rmcl/issues/${2}))" },
|
||||
]
|
||||
# Prevent commits that are breaking from being excluded by commit parsers.
|
||||
protect_breaking_commits = false
|
||||
# An array of regex based parsers for extracting data from the commit message.
|
||||
# Assigns commits to groups.
|
||||
# Optionally sets the commit's scope and can decide to exclude commits from further processing.
|
||||
commit_parsers = [
|
||||
{ message = "^feat", group = "<!-- 0 -->features" },
|
||||
{ message = "^fix", group = "<!-- 1 -->bug fixes" },
|
||||
@@ -84,20 +56,11 @@ commit_parsers = [
|
||||
{ message = "^revert", group = "<!-- 9 -->reverts" },
|
||||
{ message = ".*", group = "<!-- 10 -->other changes" },
|
||||
]
|
||||
# Exclude commits that are not matched by any commit parser.
|
||||
filter_commits = false
|
||||
# Fail on a commit that is not matched by any commit parser.
|
||||
fail_on_unmatched_commit = false
|
||||
# An array of link parsers for extracting external references, and turning them into URLs, using regex.
|
||||
link_parsers = []
|
||||
# Include only the tags that belong to the current branch.
|
||||
use_branch_tags = false
|
||||
# Order releases topologically instead of chronologically.
|
||||
topo_order = false
|
||||
# Order commits topologically instead of chronologically.
|
||||
topo_order_commits = true
|
||||
# Order of commits in each group/release within the changelog.
|
||||
# Allowed values: newest, oldest
|
||||
sort_commits = "oldest"
|
||||
# Process submodules commits
|
||||
recurse_submodules = false
|
||||
+1
-14
@@ -1,29 +1,16 @@
|
||||
[workspace]
|
||||
members = ["cargo:."]
|
||||
|
||||
# Config for 'dist'
|
||||
[dist]
|
||||
# The preferred dist version to use in CI (Cargo.toml SemVer syntax)
|
||||
cargo-dist-version = "0.31.0"
|
||||
# CI backends to support
|
||||
ci = "github"
|
||||
# The installers to generate for each app
|
||||
installers = ["homebrew", "msi"]
|
||||
# A GitHub repo to push Homebrew formulas to
|
||||
tap = "objz/homebrew-tap"
|
||||
# Target platforms to build apps for (Rust target-triple syntax)
|
||||
targets = ["aarch64-apple-darwin", "aarch64-unknown-linux-gnu", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu", "x86_64-pc-windows-msvc"]
|
||||
# Path that installers should place binaries in
|
||||
install-path = "CARGO_HOME"
|
||||
# Publish jobs to run in CI
|
||||
publish-jobs = ["homebrew", "./publish-crates", "./publish-aur", "./publish-winget"]
|
||||
# Custom permissions for publish jobs
|
||||
github-custom-job-permissions = { publish-crates = { contents = "read" }, publish-aur = { contents = "read" }, publish-winget = { contents = "read" } }
|
||||
# Extra setup steps for release artifact builders
|
||||
github-custom-job-permissions = { publish-crates = { contents = "read" }, publish-aur = { contents = "read" }, publish-winget = { contents = "write" } }
|
||||
github-build-setup = "../dist-build-setup.yml"
|
||||
# Where to host releases
|
||||
hosting = "github"
|
||||
# Whether to install an updater program
|
||||
install-updater = false
|
||||
# Allow custom edits to the generated CI file
|
||||
allow-dirty = ["ci", "msi"]
|
||||
Generated
+61
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"nodes": {
|
||||
"flake-utils": {
|
||||
"inputs": {
|
||||
"systems": "systems"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1731533236,
|
||||
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1790570722,
|
||||
"narHash": "sha256-Avcz96Q+8OkfUIUXipBBVsQn19L622BtKP7mk6M+uls=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "419fe0f449b3fbe3bdd53d9840288db4509ec32e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nixos",
|
||||
"ref": "nixpkgs-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"flake-utils": "flake-utils",
|
||||
"nixpkgs": "nixpkgs"
|
||||
}
|
||||
},
|
||||
"systems": {
|
||||
"locked": {
|
||||
"lastModified": 1681028828,
|
||||
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"type": "github"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
{
|
||||
description = "rmcl: A fully featured Minecraft TUI launcher";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-unstable";
|
||||
flake-utils.url = "github:numtide/flake-utils";
|
||||
};
|
||||
|
||||
outputs = {
|
||||
nixpkgs,
|
||||
flake-utils,
|
||||
...
|
||||
}:
|
||||
flake-utils.lib.eachDefaultSystem (system: let
|
||||
pkgs = nixpkgs.legacyPackages.${system};
|
||||
curseforgeApiKey = builtins.getEnv "CURSEFORGE_API_KEY";
|
||||
# minecraft's lwjgl/sdl natives dlopen the host's x11, opengl, vulkan,
|
||||
# input and audio stack, which isn't on the default loader path on nixos.
|
||||
# java is spawned as a child of rmcl, so a wrapper LD_LIBRARY_PATH
|
||||
# propagates all the way down. /run/opengl-driver/lib holds the mesa
|
||||
# drivers that libglvnd dispatches to.
|
||||
runtimeLibs =
|
||||
pkgs.lib.makeLibraryPath (with pkgs; [
|
||||
libX11
|
||||
libXext
|
||||
libXcursor
|
||||
libXrandr
|
||||
libXxf86vm
|
||||
libXi
|
||||
libXinerama
|
||||
libGL
|
||||
vulkan-loader
|
||||
libxkbcommon
|
||||
udev
|
||||
alsa-lib
|
||||
libpulseaudio
|
||||
])
|
||||
+ ":/run/opengl-driver/lib";
|
||||
in {
|
||||
packages.default = pkgs.rustPlatform.buildRustPackage {
|
||||
pname = "rmcl";
|
||||
version = (builtins.fromTOML (builtins.readFile ./Cargo.toml)).package.version;
|
||||
src = pkgs.lib.cleanSource ./.;
|
||||
cargoLock.lockFile = ./Cargo.lock;
|
||||
nativeBuildInputs = [pkgs.jdk pkgs.makeWrapper];
|
||||
buildInputs = [pkgs.libxcb];
|
||||
|
||||
env = pkgs.lib.optionalAttrs (curseforgeApiKey != "") {
|
||||
CURSEFORGE_API_KEY = curseforgeApiKey;
|
||||
};
|
||||
|
||||
postFixup = ''
|
||||
wrapProgram $out/bin/rmcl --prefix LD_LIBRARY_PATH : ${runtimeLibs}
|
||||
'';
|
||||
|
||||
meta = with pkgs.lib; {
|
||||
description = "A fully featured Minecraft TUI launcher";
|
||||
homepage = "https://github.com/objz/rmcl";
|
||||
license = licenses.gpl3Only;
|
||||
mainProgram = "rmcl";
|
||||
};
|
||||
};
|
||||
|
||||
# `nix develop` + `cargo run --release` spawns java directly, bypassing
|
||||
# the wrapper above, so expose the same runtime libs in the dev shell.
|
||||
devShells.default = pkgs.mkShell {
|
||||
packages = with pkgs; [cargo rustc rustfmt clippy jdk pkg-config];
|
||||
buildInputs = [pkgs.libxcb];
|
||||
shellHook = ''
|
||||
export LD_LIBRARY_PATH="${runtimeLibs}:$LD_LIBRARY_PATH"
|
||||
'';
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -6,7 +6,7 @@ pkgdesc="Minecraft launcher TUI"
|
||||
arch=('x86_64' 'aarch64')
|
||||
url="https://github.com/objz/rmcl"
|
||||
license=('GPL-3.0-only')
|
||||
depends=()
|
||||
depends=('libxcb')
|
||||
provides=('rmcl')
|
||||
conflicts=('rmcl' 'rmcl-git' 'mcl-launcher' 'mcl-launcher-bin' 'mcl-launcher-git')
|
||||
replaces=('mcl-launcher' 'mcl-launcher-bin' 'mcl-launcher-git')
|
||||
|
||||
@@ -6,7 +6,7 @@ pkgdesc="Minecraft launcher TUI"
|
||||
arch=('x86_64' 'aarch64')
|
||||
url="https://github.com/objz/rmcl"
|
||||
license=('GPL-3.0-only')
|
||||
depends=()
|
||||
depends=('libxcb')
|
||||
makedepends=('git' 'rust' 'cargo' 'jdk-openjdk')
|
||||
provides=('rmcl')
|
||||
conflicts=('rmcl' 'rmcl-bin' 'mcl-launcher' 'mcl-launcher-bin' 'mcl-launcher-git')
|
||||
@@ -36,7 +36,7 @@ check() {
|
||||
|
||||
package() {
|
||||
cd "$srcdir/rmcl"
|
||||
install -Dm755 "target/release/rmcl" "$pkgdir/usr/bin/rmcl"
|
||||
install -Dm755 "$srcdir/target/release/rmcl" "$pkgdir/usr/bin/rmcl"
|
||||
install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
||||
install -Dm644 README.md "$pkgdir/usr/share/doc/$pkgname/README.md"
|
||||
}
|
||||
+2
-2
@@ -6,7 +6,7 @@ pkgdesc="Minecraft launcher TUI"
|
||||
arch=('x86_64' 'aarch64')
|
||||
url="https://github.com/objz/rmcl"
|
||||
license=('GPL-3.0-only')
|
||||
depends=()
|
||||
depends=('libxcb')
|
||||
makedepends=('rust' 'cargo' 'jdk-openjdk')
|
||||
provides=('rmcl')
|
||||
conflicts=('rmcl-bin' 'rmcl-git' 'mcl-launcher' 'mcl-launcher-bin' 'mcl-launcher-git')
|
||||
@@ -31,7 +31,7 @@ check() {
|
||||
|
||||
package() {
|
||||
cd "$srcdir/rmcl-${pkgver}"
|
||||
install -Dm755 "target/release/rmcl" "$pkgdir/usr/bin/rmcl"
|
||||
install -Dm755 "$srcdir/target/release/rmcl" "$pkgdir/usr/bin/rmcl"
|
||||
install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
||||
install -Dm644 README.md "$pkgdir/usr/share/doc/$pkgname/README.md"
|
||||
}
|
||||
@@ -89,26 +89,6 @@
|
||||
<Directory Id='$(var.PlatformProgramFilesFolder)' Name='PFiles'>
|
||||
<Directory Id='APPLICATIONFOLDER' Name='rmcl'>
|
||||
|
||||
<!--
|
||||
Enabling the license sidecar file in the installer is a four step process:
|
||||
|
||||
1. Uncomment the `Component` tag and its contents.
|
||||
2. Change the value for the `Source` attribute in the `File` tag to a path
|
||||
to the file that should be included as the license sidecar file. The path
|
||||
can, and probably should be, relative to this file.
|
||||
3. Change the value for the `Name` attribute in the `File` tag to the
|
||||
desired name for the file when it is installed alongside the `bin` folder
|
||||
in the installation directory. This can be omitted if the desired name is
|
||||
the same as the file name.
|
||||
4. Uncomment the `ComponentRef` tag with the Id attribute value of "License"
|
||||
further down in this file.
|
||||
-->
|
||||
<!--
|
||||
<Component Id='License' Guid='*'>
|
||||
<File Id='LicenseFile' Name='ChangeMe' DiskId='1' Source='C:\Path\To\File' KeyPath='yes'/>
|
||||
</Component>
|
||||
-->
|
||||
|
||||
<Directory Id='Bin' Name='bin'>
|
||||
<Component Id='Path' Guid='E5863AC2-13FC-45C8-B79D-55338F371A8A' KeyPath='yes'>
|
||||
<Environment
|
||||
@@ -143,12 +123,6 @@
|
||||
Display='expand'
|
||||
Absent='disallow'>
|
||||
|
||||
<!--
|
||||
Uncomment the following `ComponentRef` tag to add the license
|
||||
sidecar file to the installer.
|
||||
-->
|
||||
<!--<ComponentRef Id='License'/>-->
|
||||
|
||||
<ComponentRef Id='binary0'/>
|
||||
|
||||
<Feature
|
||||
@@ -164,65 +138,19 @@
|
||||
<SetProperty Id='ARPINSTALLLOCATION' Value='[APPLICATIONFOLDER]' After='CostFinalize'/>
|
||||
|
||||
|
||||
<!--
|
||||
Uncomment the following `Icon` and `Property` tags to change the product icon.
|
||||
|
||||
The product icon is the graphic that appears in the Add/Remove
|
||||
Programs control panel for the application.
|
||||
-->
|
||||
<!--<Icon Id='ProductICO' SourceFile='pkg\wix\Product.ico'/>-->
|
||||
<!--<Property Id='ARPPRODUCTICON' Value='ProductICO' />-->
|
||||
|
||||
<Property Id='ARPHELPLINK' Value='https://github.com/objz/rmcl'/>
|
||||
|
||||
<UI>
|
||||
<UIRef Id='WixUI_FeatureTree'/>
|
||||
|
||||
<!--
|
||||
Enabling the EULA dialog in the installer is a three step process:
|
||||
|
||||
1. Comment out or remove the two `Publish` tags that follow the
|
||||
`WixVariable` tag.
|
||||
2. Uncomment the `<WixVariable Id='WixUILicenseRtf' Value='Path\to\Eula.rft'>` tag further down
|
||||
3. Replace the `Value` attribute of the `WixVariable` tag with
|
||||
the path to a RTF file that will be used as the EULA and
|
||||
displayed in the license agreement dialog.
|
||||
-->
|
||||
<Publish Dialog='WelcomeDlg' Control='Next' Event='NewDialog' Value='CustomizeDlg' Order='99'>1</Publish>
|
||||
<Publish Dialog='CustomizeDlg' Control='Back' Event='NewDialog' Value='WelcomeDlg' Order='99'>1</Publish>
|
||||
|
||||
</UI>
|
||||
|
||||
|
||||
<!--
|
||||
Enabling the EULA dialog in the installer requires uncommenting
|
||||
the following `WixUILicenseRTF` tag and changing the `Value`
|
||||
attribute.
|
||||
-->
|
||||
<!-- <WixVariable Id='WixUILicenseRtf' Value='Relative\Path\to\Eula.rtf'/> -->
|
||||
|
||||
|
||||
<!--
|
||||
Uncomment the next `WixVariable` tag to customize the installer's
|
||||
Graphical User Interface (GUI) and add a custom banner image across
|
||||
the top of each screen. See the WiX Toolset documentation for details
|
||||
about customization.
|
||||
|
||||
The banner BMP dimensions are 493 x 58 pixels.
|
||||
-->
|
||||
<!--<WixVariable Id='WixUIBannerBmp' Value='pkg\wix\Banner.bmp'/>-->
|
||||
|
||||
|
||||
<!--
|
||||
Uncomment the next `WixVariable` tag to customize the installer's
|
||||
Graphical User Interface (GUI) and add a custom image to the first
|
||||
dialog, or screen. See the WiX Toolset documentation for details about
|
||||
customization.
|
||||
|
||||
The dialog BMP dimensions are 493 x 312 pixels.
|
||||
-->
|
||||
<!--<WixVariable Id='WixUIDialogBmp' Value='pkg\wix\Dialog.bmp'/>-->
|
||||
|
||||
</Product>
|
||||
|
||||
</Wix>
|
||||
@@ -0,0 +1,54 @@
|
||||
# SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
# SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def version_key(value):
|
||||
match = re.fullmatch(
|
||||
r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)"
|
||||
r"(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?"
|
||||
r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?",
|
||||
value,
|
||||
)
|
||||
if match is None:
|
||||
return None
|
||||
pre = match[4].split(".") if match[4] is not None else []
|
||||
if any(part.isdigit() and len(part) > 1 and part.startswith("0") for part in pre):
|
||||
return None
|
||||
return tuple(map(int, match.groups()[:3])) + (
|
||||
match[4] is None,
|
||||
tuple((0, int(part)) if part.isdigit() else (1, part) for part in pre),
|
||||
)
|
||||
|
||||
|
||||
def check():
|
||||
chain = "1.0.0-alpha 1.0.0-alpha.1 1.0.0-alpha.beta 1.0.0-beta 1.0.0-beta.2 1.0.0-beta.11 1.0.0-rc.1 1.0.0".split()
|
||||
assert all(version_key(a) < version_key(b) for a, b in zip(chain, chain[1:]))
|
||||
assert version_key("1.0.0+build2") == version_key("1.0.0+build1")
|
||||
assert all(version_key(v) is None for v in ["01.0.0", "1.0.0-01", "1.0.0-alpha..1"])
|
||||
assert version_key("0.5.1") > version_key("0.5.1-rc.1")
|
||||
assert version_key("0.5.1-rc.10") > version_key("0.5.1-rc.9")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if sys.argv[1:] == ["--check"]:
|
||||
check()
|
||||
else:
|
||||
version = sys.argv[1]
|
||||
candidate = version_key(version)
|
||||
if candidate is None:
|
||||
sys.exit(f"Invalid package version: {version}")
|
||||
versions = [
|
||||
(key, tag[1:])
|
||||
for tag in subprocess.check_output(["git", "tag", "--list", "v*"], text=True).splitlines()
|
||||
if (key := version_key(tag[1:])) is not None
|
||||
]
|
||||
latest_key, latest = max(versions, default=(None, ""))
|
||||
release = latest_key is None or candidate > latest_key
|
||||
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output:
|
||||
output.write(f"release={str(release).lower()}\ntag=v{version}\n")
|
||||
print(f"v{version}: release={str(release).lower()}, latest={latest or 'none'}")
|
||||
+126
-84
@@ -1,8 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// account management: persistence, switching active accounts, and offline uuid generation
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -36,26 +34,36 @@ pub enum AuthResult {
|
||||
pub struct AccountStore {
|
||||
pub accounts: Vec<Account>,
|
||||
path: PathBuf,
|
||||
load_error: Option<String>,
|
||||
}
|
||||
|
||||
impl AccountStore {
|
||||
pub fn load() -> Self {
|
||||
let path = account_store_path();
|
||||
let accounts = match std::fs::read_to_string(&path) {
|
||||
Self::load_from(account_store_path())
|
||||
}
|
||||
|
||||
fn load_from(path: PathBuf) -> Self {
|
||||
let (accounts, load_error) = match std::fs::read_to_string(&path) {
|
||||
Ok(content) => match serde_json::from_str(&content) {
|
||||
Ok(accounts) => accounts,
|
||||
Ok(accounts) => (accounts, None),
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to parse accounts file {}: {}", path.display(), e);
|
||||
Vec::new()
|
||||
(
|
||||
Vec::new(),
|
||||
Some(format!("Invalid accounts file {}: {e}", path.display())),
|
||||
)
|
||||
}
|
||||
},
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
tracing::debug!("No accounts file at {}", path.display());
|
||||
Vec::new()
|
||||
(Vec::new(), None)
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to read accounts file {}: {}", path.display(), e);
|
||||
Vec::new()
|
||||
(
|
||||
Vec::new(),
|
||||
Some(format!("Cannot read accounts file {}: {e}", path.display())),
|
||||
)
|
||||
}
|
||||
};
|
||||
tracing::debug!(
|
||||
@@ -63,36 +71,30 @@ impl AccountStore {
|
||||
accounts.len(),
|
||||
path.display()
|
||||
);
|
||||
Self { accounts, path }
|
||||
Self {
|
||||
accounts,
|
||||
path,
|
||||
load_error,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save(&self) {
|
||||
if let Some(parent) = self.path.parent()
|
||||
&& let Err(e) = std::fs::create_dir_all(parent)
|
||||
{
|
||||
tracing::error!("Failed to create accounts directory: {}", e);
|
||||
return;
|
||||
}
|
||||
match serde_json::to_string_pretty(&self.accounts) {
|
||||
Ok(json) => {
|
||||
// this file holds microsoft refresh tokens: a torn write on
|
||||
// crash would permanently lock the user out, so write atomically.
|
||||
if let Err(e) = crate::storage::write_atomic(&self.path, json.as_bytes()) {
|
||||
tracing::error!(
|
||||
"Failed to write accounts file {}: {}",
|
||||
self.path.display(),
|
||||
e
|
||||
);
|
||||
} else {
|
||||
tracing::debug!(
|
||||
"Saved {} account(s) to {}",
|
||||
self.accounts.len(),
|
||||
self.path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::error!("Failed to serialize accounts: {}", e),
|
||||
pub fn check_loaded(&self) -> std::io::Result<()> {
|
||||
if let Some(error) = &self.load_error {
|
||||
return Err(std::io::Error::other(error.clone()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn save(&self) -> std::io::Result<()> {
|
||||
self.check_loaded()?;
|
||||
let json = serde_json::to_vec_pretty(&self.accounts).map_err(std::io::Error::other)?;
|
||||
crate::storage::write_atomic_private(&self.path, &json)?;
|
||||
tracing::debug!(
|
||||
"Saved {} account(s) to {}",
|
||||
self.accounts.len(),
|
||||
self.path.display()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn active_account(&self) -> Option<&Account> {
|
||||
@@ -105,63 +107,105 @@ impl AccountStore {
|
||||
.any(|account| account.account_type == AccountType::Microsoft)
|
||||
}
|
||||
|
||||
pub fn set_active(&mut self, index: usize) {
|
||||
pub fn set_active(&mut self, index: usize) -> std::io::Result<()> {
|
||||
let Some(account) = self.accounts.get(index) else {
|
||||
// out-of-range: leave the current selection untouched. marking
|
||||
// every account inactive here would break the single-active
|
||||
// invariant and orphan the store with no usable account.
|
||||
// Invalid selection must leave the active account intact.
|
||||
tracing::warn!("Tried to select missing account index {}", index);
|
||||
return;
|
||||
return Ok(());
|
||||
};
|
||||
let username = account.username.clone();
|
||||
for (i, acc) in self.accounts.iter_mut().enumerate() {
|
||||
acc.active = i == index;
|
||||
}
|
||||
tracing::info!("Selected account '{}'", username);
|
||||
self.save();
|
||||
let uuid = account.uuid.clone();
|
||||
self.update(|accounts| {
|
||||
if !accounts.iter().any(|account| account.uuid == uuid) {
|
||||
return Err(std::io::Error::other("Selected account no longer exists"));
|
||||
}
|
||||
for account in accounts {
|
||||
account.active = account.uuid == uuid;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
// if an account with the same uuid already exists, replace it.
|
||||
// first account added auto-becomes active so there's always a selection.
|
||||
pub fn add(&mut self, account: Account) {
|
||||
let uuid = &account.uuid;
|
||||
let replaced = self.accounts.iter().any(|a| a.uuid == *uuid);
|
||||
// re-adding the currently active account must not drop the selection:
|
||||
// the replacement takes over the old account's active flag.
|
||||
let replaced_active = self.accounts.iter().any(|a| a.uuid == *uuid && a.active);
|
||||
let account_type = account.account_type.clone();
|
||||
let username = account.username.clone();
|
||||
self.accounts.retain(|a| a.uuid != *uuid);
|
||||
let mut account = account;
|
||||
if self.accounts.is_empty() || replaced_active {
|
||||
account.active = true;
|
||||
}
|
||||
self.accounts.push(account);
|
||||
tracing::info!(
|
||||
"{} {:?} account '{}'",
|
||||
if replaced { "Updated" } else { "Added" },
|
||||
account_type,
|
||||
username
|
||||
);
|
||||
self.save();
|
||||
pub fn add(&mut self, account: Account) -> std::io::Result<()> {
|
||||
self.update(|accounts| {
|
||||
let replaced_active = accounts
|
||||
.iter()
|
||||
.any(|old| old.uuid == account.uuid && old.active);
|
||||
accounts.retain(|old| old.uuid != account.uuid);
|
||||
let mut account = account;
|
||||
account.active = accounts.is_empty() || replaced_active;
|
||||
accounts.push(account);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, index: usize) {
|
||||
pub fn remove(&mut self, index: usize) -> std::io::Result<()> {
|
||||
if index >= self.accounts.len() {
|
||||
tracing::warn!("Tried to remove missing account index {}", index);
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
let account = self.accounts.remove(index);
|
||||
tracing::info!(
|
||||
"Removed {:?} account '{}'",
|
||||
account.account_type,
|
||||
account.username
|
||||
);
|
||||
if account.active && !self.accounts.is_empty() {
|
||||
self.accounts[0].active = true;
|
||||
tracing::debug!("Activated fallback account '{}'", self.accounts[0].username);
|
||||
let uuid = self.accounts[index].uuid.clone();
|
||||
self.update(|accounts| {
|
||||
let index = accounts
|
||||
.iter()
|
||||
.position(|account| account.uuid == uuid)
|
||||
.ok_or_else(|| std::io::Error::other("Selected account no longer exists"))?;
|
||||
let account = accounts.remove(index);
|
||||
if account.active
|
||||
&& let Some(first) = accounts.first_mut()
|
||||
{
|
||||
first.active = true;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
pub fn update_credentials(
|
||||
&mut self,
|
||||
uuid: &str,
|
||||
refresh: Option<String>,
|
||||
token: &str,
|
||||
expires: Option<i64>,
|
||||
) -> std::io::Result<()> {
|
||||
if refresh.is_none() && expires.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
self.save();
|
||||
self.update(|accounts| {
|
||||
let account = accounts
|
||||
.iter_mut()
|
||||
.find(|account| account.uuid == uuid)
|
||||
.ok_or_else(|| std::io::Error::other("Authenticated account no longer exists"))?;
|
||||
if let Some(refresh) = refresh {
|
||||
account.refresh_token = Some(refresh);
|
||||
}
|
||||
if let Some(expires) = expires {
|
||||
account.cached_mc_token = Some(token.to_owned());
|
||||
account.cached_mc_token_expires_at = Some(expires);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
update: impl FnOnce(&mut Vec<Account>) -> std::io::Result<()>,
|
||||
) -> std::io::Result<()> {
|
||||
use fs2::FileExt;
|
||||
self.check_loaded()?;
|
||||
if let Some(parent) = self.path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let lock = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.write(true)
|
||||
.open(self.path.with_extension("lock"))?;
|
||||
lock.lock_exclusive()?;
|
||||
let mut current = Self::load_from(self.path.clone());
|
||||
current.check_loaded()?;
|
||||
update(&mut current.accounts)?;
|
||||
current.save()?;
|
||||
self.accounts = current.accounts;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,9 +213,7 @@ pub fn account_store_path() -> PathBuf {
|
||||
crate::config::get_config_path().join("accounts.json")
|
||||
}
|
||||
|
||||
// deterministic fake uuid from a username, formatted as uuid v3 with the proper
|
||||
// version and variant bits set. not cryptographically meaningful, just needs to
|
||||
// be consistent so the same offline name always maps to the same uuid.
|
||||
// Keep the existing mapping so saved offline player data retains its identifier.
|
||||
pub fn offline_uuid(username: &str) -> String {
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
let mut hasher = DefaultHasher::new();
|
||||
|
||||
+1
-2
@@ -1,7 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// auth module: account storage (offline + microsoft) and the oauth device code flow
|
||||
mod accounts;
|
||||
mod oauth;
|
||||
|
||||
@@ -9,4 +8,4 @@ pub use accounts::{
|
||||
Account, AccountStore, AccountType, AuthResult, account_store_path, create_offline_account,
|
||||
offline_uuid,
|
||||
};
|
||||
pub use oauth::{DEVICE_CODE_DISPLAY, DeviceCodeInfo, refresh_and_get_token, start_microsoft_auth};
|
||||
pub use oauth::{DeviceCodeInfo, MicrosoftAuth, refresh_and_get_token, start_microsoft_auth};
|
||||
+78
-55
@@ -1,11 +1,9 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// microsoft oauth device code flow for minecraft authentication.
|
||||
// the flow goes: MSA device code -> MSA token -> xbox/mc token exchange -> mc profile fetch.
|
||||
// device code auth is used because it works without a redirect URI, which is nice for a TUI.
|
||||
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use minecraft_msa_auth::MinecraftAuthorizationFlow;
|
||||
use oauth2::basic::BasicClient;
|
||||
@@ -22,7 +20,6 @@ const DEVICE_CODE_URL: &str = "https://login.microsoftonline.com/consumers/oauth
|
||||
const MSA_AUTHORIZE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize";
|
||||
const MSA_TOKEN_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token";
|
||||
const MC_PROFILE_URL: &str = "https://api.minecraftservices.com/minecraft/profile";
|
||||
const MC_TOKEN_CACHE_TTL_SECS: i64 = 20 * 60 * 60;
|
||||
const MC_TOKEN_CACHE_REFRESH_MARGIN_SECS: i64 = 5 * 60;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
@@ -50,11 +47,16 @@ fn normalize_profile_uuid(id: &str) -> Option<String> {
|
||||
})
|
||||
}
|
||||
|
||||
// shared slot so the TUI can poll for the device code to show the user
|
||||
pub static DEVICE_CODE_DISPLAY: LazyLock<Arc<Mutex<Option<DeviceCodeInfo>>>> =
|
||||
LazyLock::new(|| Arc::new(Mutex::new(None)));
|
||||
#[derive(Default)]
|
||||
pub struct MicrosoftAuth {
|
||||
pub result: Arc<Mutex<Option<AuthResult>>>,
|
||||
pub device_code: Arc<Mutex<Option<DeviceCodeInfo>>>,
|
||||
}
|
||||
|
||||
async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
|
||||
async fn run_full_oauth_flow(
|
||||
http_client: &reqwest::Client,
|
||||
display: &Mutex<Option<DeviceCodeInfo>>,
|
||||
) -> Result<(String, Option<String>), String> {
|
||||
let oauth_client = BasicClient::new(ClientId::new(CLIENT_ID.to_owned()))
|
||||
.set_auth_uri(AuthUrl::new(MSA_AUTHORIZE_URL.to_owned()).map_err(|e| e.to_string())?)
|
||||
.set_token_uri(TokenUrl::new(MSA_TOKEN_URL.to_owned()).map_err(|e| e.to_string())?)
|
||||
@@ -62,17 +64,15 @@ async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
|
||||
DeviceAuthorizationUrl::new(DEVICE_CODE_URL.to_owned()).map_err(|e| e.to_string())?,
|
||||
);
|
||||
|
||||
let http_client = reqwest::Client::new();
|
||||
|
||||
let details: StandardDeviceAuthorizationResponse = oauth_client
|
||||
.exchange_device_code()
|
||||
.add_scope(Scope::new("XboxLive.signin".to_owned()))
|
||||
.add_scope(Scope::new("offline_access".to_owned()))
|
||||
.request_async(&http_client)
|
||||
.request_async(http_client)
|
||||
.await
|
||||
.map_err(|e| format!("Device code request failed: {e}"))?;
|
||||
|
||||
if let Ok(mut slot) = DEVICE_CODE_DISPLAY.lock() {
|
||||
if let Ok(mut slot) = display.lock() {
|
||||
*slot = Some(DeviceCodeInfo {
|
||||
user_code: details.user_code().secret().to_owned(),
|
||||
verification_uri: details.verification_uri().to_string(),
|
||||
@@ -82,7 +82,7 @@ async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
|
||||
|
||||
let token = oauth_client
|
||||
.exchange_device_access_token(&details)
|
||||
.request_async(&http_client, tokio::time::sleep, None)
|
||||
.request_async(http_client, tokio::time::sleep, None)
|
||||
.await
|
||||
.map_err(|e| format!("Authentication failed: {e}"))?;
|
||||
|
||||
@@ -92,64 +92,65 @@ async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
|
||||
Ok((ms_access_token, ms_refresh_token))
|
||||
}
|
||||
|
||||
// kicks off auth on a background task, returns a mutex the caller can poll for the result.
|
||||
// the TUI checks DEVICE_CODE_DISPLAY for the code to show, and this mutex for completion.
|
||||
pub fn start_microsoft_auth() -> Arc<Mutex<Option<AuthResult>>> {
|
||||
let result: Arc<Mutex<Option<AuthResult>>> = Arc::new(Mutex::new(None));
|
||||
let result_clone = result.clone();
|
||||
pub fn start_microsoft_auth() -> MicrosoftAuth {
|
||||
let auth = MicrosoftAuth::default();
|
||||
let result_clone = auth.result.clone();
|
||||
let device_code = auth.device_code.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let outcome = run_full_auth_flow().await;
|
||||
let outcome = run_full_auth_flow(&device_code).await;
|
||||
if let Ok(mut slot) = result_clone.lock() {
|
||||
*slot = Some(outcome);
|
||||
crate::feedback::request_redraw();
|
||||
}
|
||||
});
|
||||
|
||||
result
|
||||
auth
|
||||
}
|
||||
|
||||
async fn run_full_auth_flow() -> AuthResult {
|
||||
let (ms_access_token, ms_refresh_token) = match run_full_oauth_flow().await {
|
||||
async fn run_full_auth_flow(display: &Mutex<Option<DeviceCodeInfo>>) -> AuthResult {
|
||||
let http_client = match auth_http_client() {
|
||||
Ok(client) => client,
|
||||
Err(error) => return AuthResult::Error(error),
|
||||
};
|
||||
let (ms_access_token, ms_refresh_token) = match run_full_oauth_flow(&http_client, display).await
|
||||
{
|
||||
Ok(pair) => pair,
|
||||
Err(e) => return AuthResult::Error(e),
|
||||
};
|
||||
|
||||
exchange_and_build_account(&ms_access_token, ms_refresh_token.as_deref()).await
|
||||
let Some(refresh_token) = ms_refresh_token.as_deref() else {
|
||||
return AuthResult::Error(
|
||||
"Microsoft did not return a refresh token; try signing in again".to_owned(),
|
||||
);
|
||||
};
|
||||
exchange_and_build_account(&http_client, &ms_access_token, Some(refresh_token)).await
|
||||
}
|
||||
|
||||
fn auth_http_client() -> Result<reqwest::Client, String> {
|
||||
reqwest::Client::builder()
|
||||
.connect_timeout(std::time::Duration::from_secs(30))
|
||||
.timeout(std::time::Duration::from_secs(30))
|
||||
.build()
|
||||
.map_err(|error| format!("Could not create authentication HTTP client: {error}"))
|
||||
}
|
||||
|
||||
async fn exchange_and_build_account(
|
||||
client: &reqwest::Client,
|
||||
ms_access_token: &str,
|
||||
ms_refresh_token: Option<&str>,
|
||||
) -> AuthResult {
|
||||
let mc_flow = MinecraftAuthorizationFlow::new(reqwest::Client::new());
|
||||
let mc_flow = MinecraftAuthorizationFlow::new(client.clone());
|
||||
let mc_token = match mc_flow.exchange_microsoft_token(ms_access_token).await {
|
||||
Ok(t) => t,
|
||||
Err(e) => return AuthResult::Error(format!("Minecraft auth failed: {e}")),
|
||||
};
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
let profile_resp = match client
|
||||
.get(MC_PROFILE_URL)
|
||||
.header(
|
||||
"Authorization",
|
||||
format!("Bearer {}", mc_token.access_token().as_ref()),
|
||||
)
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
Ok(r) => r,
|
||||
Err(e) => return AuthResult::Error(format!("Profile fetch failed: {e}")),
|
||||
};
|
||||
|
||||
if !profile_resp.status().is_success() {
|
||||
return AuthResult::Error("Account does not own Minecraft".to_owned());
|
||||
}
|
||||
|
||||
let profile: McProfile = match profile_resp.json().await {
|
||||
Ok(p) => p,
|
||||
Err(e) => return AuthResult::Error(format!("Profile parse failed: {e}")),
|
||||
};
|
||||
let profile =
|
||||
match fetch_profile(client, MC_PROFILE_URL, mc_token.access_token().as_ref()).await {
|
||||
Ok(p) => p,
|
||||
Err(e) => return AuthResult::Error(e),
|
||||
};
|
||||
|
||||
// mojang returns uuids without dashes
|
||||
let uuid = match normalize_profile_uuid(&profile.id) {
|
||||
@@ -163,11 +164,36 @@ async fn exchange_and_build_account(
|
||||
account_type: AccountType::Microsoft,
|
||||
active: false,
|
||||
refresh_token: ms_refresh_token.map(|s| s.to_owned()),
|
||||
cached_mc_token: None,
|
||||
cached_mc_token_expires_at: None,
|
||||
cached_mc_token: Some(mc_token.access_token().as_ref().to_owned()),
|
||||
cached_mc_token_expires_at: Some(
|
||||
chrono::Utc::now().timestamp() + i64::from(mc_token.expires_in()),
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
async fn fetch_profile(
|
||||
client: &reqwest::Client,
|
||||
url: &str,
|
||||
token: &str,
|
||||
) -> Result<McProfile, String> {
|
||||
let response = client
|
||||
.get(url)
|
||||
.bearer_auth(token)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Profile fetch failed: {e}"))?;
|
||||
if response.status() == reqwest::StatusCode::NOT_FOUND {
|
||||
return Err("Account does not own Minecraft".to_owned());
|
||||
}
|
||||
let response = response
|
||||
.error_for_status()
|
||||
.map_err(|e| format!("Profile fetch failed: {e}"))?;
|
||||
response
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| format!("Profile parse failed: {e}"))
|
||||
}
|
||||
|
||||
fn valid_cached_mc_token(account: &Account, now: i64) -> Option<&str> {
|
||||
let (Some(cached), Some(expires_at)) = (
|
||||
account.cached_mc_token.as_deref(),
|
||||
@@ -176,14 +202,13 @@ fn valid_cached_mc_token(account: &Account, now: i64) -> Option<&str> {
|
||||
return None;
|
||||
};
|
||||
|
||||
if now < expires_at - MC_TOKEN_CACHE_REFRESH_MARGIN_SECS {
|
||||
if now < expires_at.saturating_sub(MC_TOKEN_CACHE_REFRESH_MARGIN_SECS) {
|
||||
Some(cached)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
// returns (mc_access_token, new_refresh_token, new_mc_token_expires_at).
|
||||
// cached tokens return no expiry so callers don't rewrite the account store.
|
||||
pub async fn refresh_and_get_token(
|
||||
account: &Account,
|
||||
@@ -212,7 +237,7 @@ pub async fn refresh_and_get_token(
|
||||
)
|
||||
.set_token_uri(TokenUrl::new(MSA_TOKEN_URL.to_owned()).map_err(|e| e.to_string())?);
|
||||
|
||||
let http_client = reqwest::Client::new();
|
||||
let http_client = auth_http_client()?;
|
||||
|
||||
let token = oauth_client
|
||||
.exchange_refresh_token(&RefreshToken::new(refresh.to_owned()))
|
||||
@@ -225,15 +250,13 @@ pub async fn refresh_and_get_token(
|
||||
let ms_access_token = token.access_token().secret().to_owned();
|
||||
let new_refresh = token.refresh_token().map(|r| r.secret().to_owned());
|
||||
|
||||
let mc_flow = MinecraftAuthorizationFlow::new(reqwest::Client::new());
|
||||
let mc_flow = MinecraftAuthorizationFlow::new(http_client);
|
||||
let mc_token = mc_flow
|
||||
.exchange_microsoft_token(&ms_access_token)
|
||||
.await
|
||||
.map_err(|e| format!("Minecraft auth failed: {e}"))?;
|
||||
|
||||
// minecraft-msa-auth does not expose this expiry here, so cache
|
||||
// conservatively and refresh before the token gets close.
|
||||
let expires_at = chrono::Utc::now().timestamp() + MC_TOKEN_CACHE_TTL_SECS;
|
||||
let expires_at = chrono::Utc::now().timestamp() + i64::from(mc_token.expires_in());
|
||||
|
||||
Ok((
|
||||
mc_token.access_token().as_ref().to_owned(),
|
||||
|
||||
+97
-29
@@ -8,6 +8,7 @@ impl AccountStore {
|
||||
Self {
|
||||
accounts: Vec::new(),
|
||||
path,
|
||||
load_error: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,9 +49,6 @@ fn create_offline_account_fields() {
|
||||
assert_eq!(acc.account_type, AccountType::Offline);
|
||||
assert!(!acc.active);
|
||||
assert!(acc.refresh_token.is_none());
|
||||
// pin the uuid to the deterministic offline_uuid output so a regression
|
||||
// in the uuid derivation (e.g. salt change) would fail this test, not
|
||||
// just a non-empty-string check that any garbage would pass.
|
||||
assert_eq!(acc.uuid, offline_uuid("TestPlayer"));
|
||||
}
|
||||
|
||||
@@ -58,6 +56,7 @@ fn make_store(dir: &std::path::Path) -> AccountStore {
|
||||
AccountStore {
|
||||
accounts: Vec::new(),
|
||||
path: dir.join("accounts.json"),
|
||||
load_error: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,7 +76,7 @@ fn microsoft_account(name: &str) -> Account {
|
||||
fn store_add_first_becomes_active() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
assert_eq!(store.accounts.len(), 1);
|
||||
assert!(store.accounts[0].active);
|
||||
}
|
||||
@@ -86,8 +85,8 @@ fn store_add_first_becomes_active() {
|
||||
fn store_add_second_stays_inactive() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.add(create_offline_account("Bob"));
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
store.add(create_offline_account("Bob")).unwrap();
|
||||
assert_eq!(store.accounts.len(), 2);
|
||||
assert!(store.accounts[0].active);
|
||||
assert!(!store.accounts[1].active);
|
||||
@@ -97,11 +96,11 @@ fn store_add_second_stays_inactive() {
|
||||
fn store_add_duplicate_uuid_replaces() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
let mut dup = create_offline_account("Alice");
|
||||
dup.username = "AliceRenamed".to_owned();
|
||||
dup.uuid = store.accounts[0].uuid.clone();
|
||||
store.add(dup);
|
||||
store.add(dup).unwrap();
|
||||
assert_eq!(store.accounts.len(), 1);
|
||||
assert_eq!(store.accounts[0].username, "AliceRenamed");
|
||||
}
|
||||
@@ -117,10 +116,10 @@ fn store_active_account_none_when_empty() {
|
||||
fn store_has_microsoft_account_when_one_exists() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Offline"));
|
||||
store.add(create_offline_account("Offline")).unwrap();
|
||||
assert!(!store.has_microsoft_account());
|
||||
|
||||
store.add(microsoft_account("Owner"));
|
||||
store.add(microsoft_account("Owner")).unwrap();
|
||||
assert!(store.has_microsoft_account());
|
||||
}
|
||||
|
||||
@@ -128,8 +127,8 @@ fn store_has_microsoft_account_when_one_exists() {
|
||||
fn store_active_account_returns_active() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.add(create_offline_account("Bob"));
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
store.add(create_offline_account("Bob")).unwrap();
|
||||
let active = store.active_account().unwrap();
|
||||
assert_eq!(active.username, "Alice");
|
||||
}
|
||||
@@ -138,9 +137,9 @@ fn store_active_account_returns_active() {
|
||||
fn store_set_active_changes_active() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.add(create_offline_account("Bob"));
|
||||
store.set_active(1);
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
store.add(create_offline_account("Bob")).unwrap();
|
||||
store.set_active(1).unwrap();
|
||||
assert!(!store.accounts[0].active);
|
||||
assert!(store.accounts[1].active);
|
||||
}
|
||||
@@ -149,9 +148,9 @@ fn store_set_active_changes_active() {
|
||||
fn store_set_active_out_of_bounds_keeps_selection() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.add(create_offline_account("Bob"));
|
||||
store.set_active(99);
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
store.add(create_offline_account("Bob")).unwrap();
|
||||
store.set_active(99).unwrap();
|
||||
assert!(
|
||||
store.accounts[0].active,
|
||||
"existing selection must survive a bad index"
|
||||
@@ -163,11 +162,11 @@ fn store_set_active_out_of_bounds_keeps_selection() {
|
||||
fn store_add_replacing_active_keeps_active() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.add(create_offline_account("Bob"));
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
store.add(create_offline_account("Bob")).unwrap();
|
||||
let mut dup = create_offline_account("Alice");
|
||||
dup.username = "AliceRenamed".to_owned();
|
||||
store.add(dup);
|
||||
store.add(dup).unwrap();
|
||||
assert!(
|
||||
store.accounts.iter().any(|a| a.active),
|
||||
"re-adding the active account must not orphan the selection"
|
||||
@@ -180,9 +179,9 @@ fn store_add_replacing_active_keeps_active() {
|
||||
fn store_remove_activates_first_remaining() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.add(create_offline_account("Bob"));
|
||||
store.remove(0);
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
store.add(create_offline_account("Bob")).unwrap();
|
||||
store.remove(0).unwrap();
|
||||
assert_eq!(store.accounts.len(), 1);
|
||||
assert_eq!(store.accounts[0].username, "Bob");
|
||||
assert!(store.accounts[0].active);
|
||||
@@ -192,8 +191,8 @@ fn store_remove_activates_first_remaining() {
|
||||
fn store_remove_out_of_bounds_noop() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.remove(5);
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
store.remove(5).unwrap();
|
||||
assert_eq!(store.accounts.len(), 1);
|
||||
}
|
||||
|
||||
@@ -201,9 +200,9 @@ fn store_remove_out_of_bounds_noop() {
|
||||
fn store_save_and_reload() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.add(create_offline_account("Bob"));
|
||||
store.save();
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
store.add(create_offline_account("Bob")).unwrap();
|
||||
store.save().unwrap();
|
||||
|
||||
let reloaded = AccountStore {
|
||||
accounts: serde_json::from_str(
|
||||
@@ -211,8 +210,77 @@ fn store_save_and_reload() {
|
||||
)
|
||||
.unwrap(),
|
||||
path: tmp.path().join("accounts.json"),
|
||||
load_error: None,
|
||||
};
|
||||
assert_eq!(reloaded.accounts.len(), 2);
|
||||
assert_eq!(reloaded.accounts[0].username, "Alice");
|
||||
assert!(reloaded.accounts[0].active);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn account_file_remains_owner_only_after_replacement() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(microsoft_account("Owner")).unwrap();
|
||||
let path = tmp.path().join("accounts.json");
|
||||
assert_eq!(
|
||||
std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
|
||||
0o600
|
||||
);
|
||||
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
|
||||
store.add(create_offline_account("Player")).unwrap();
|
||||
assert_eq!(
|
||||
std::fs::metadata(path).unwrap().permissions().mode() & 0o777,
|
||||
0o600
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_account_file_cannot_be_overwritten_by_a_new_account() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("accounts.json");
|
||||
std::fs::write(&path, b"{broken credentials").unwrap();
|
||||
let mut store = AccountStore::load_from(path.clone());
|
||||
assert!(store.check_loaded().is_err());
|
||||
|
||||
assert!(store.add(microsoft_account("Owner")).is_err());
|
||||
assert!(store.accounts.is_empty());
|
||||
assert_eq!(std::fs::read(path).unwrap(), b"{broken credentials");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_account_mutations_preserve_new_credentials_and_selection() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut first = make_store(tmp.path());
|
||||
first.add(microsoft_account("Owner")).unwrap();
|
||||
first.add(create_offline_account("Player")).unwrap();
|
||||
let mut stale = AccountStore::load_from(first.path.clone());
|
||||
let uuid = first.accounts[0].uuid.clone();
|
||||
first
|
||||
.update_credentials(
|
||||
&uuid,
|
||||
Some("new-refresh".to_owned()),
|
||||
"new-token",
|
||||
Some(12345),
|
||||
)
|
||||
.unwrap();
|
||||
first.add(create_offline_account("New")).unwrap();
|
||||
stale.set_active(1).unwrap();
|
||||
assert_eq!(stale.accounts.len(), 3);
|
||||
assert_eq!(
|
||||
stale.accounts[0].refresh_token.as_deref(),
|
||||
Some("new-refresh")
|
||||
);
|
||||
first
|
||||
.update_credentials(&uuid, None, "newer-token", Some(23456))
|
||||
.unwrap();
|
||||
assert_eq!(first.active_account().unwrap().username, "Player");
|
||||
assert_eq!(
|
||||
first.accounts[0].cached_mc_token.as_deref(),
|
||||
Some("newer-token")
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,42 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn profile_status_errors_and_stalls_are_reported_accurately() {
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate, matchers::path};
|
||||
let server = MockServer::start().await;
|
||||
let client = reqwest::Client::builder()
|
||||
.read_timeout(std::time::Duration::from_millis(30))
|
||||
.build()
|
||||
.unwrap();
|
||||
for status in [404, 401, 429, 503] {
|
||||
let route = format!("/{status}");
|
||||
Mock::given(path(&route))
|
||||
.respond_with(ResponseTemplate::new(status))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let error = fetch_profile(&client, &format!("{}{route}", server.uri()), "test")
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
if status == 404 {
|
||||
assert!(error.contains("does not own"));
|
||||
} else {
|
||||
assert!(error.contains(&status.to_string()));
|
||||
assert!(!error.contains("does not own"));
|
||||
}
|
||||
}
|
||||
Mock::given(path("/stall"))
|
||||
.respond_with(ResponseTemplate::new(200).set_delay(std::time::Duration::from_secs(1)))
|
||||
.mount(&server)
|
||||
.await;
|
||||
assert!(
|
||||
fetch_profile(&client, &format!("{}/stall", server.uri()), "test")
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
fn microsoft_account(cached_mc_token_expires_at: Option<i64>) -> Account {
|
||||
Account {
|
||||
uuid: "00000000-0000-0000-0000-000000000000".to_owned(),
|
||||
@@ -29,6 +65,7 @@ fn cached_mc_token_expires_inside_refresh_margin() {
|
||||
let account = microsoft_account(Some(now + MC_TOKEN_CACHE_REFRESH_MARGIN_SECS));
|
||||
|
||||
assert!(valid_cached_mc_token(&account, now).is_none());
|
||||
assert!(valid_cached_mc_token(µsoft_account(Some(i64::MIN)), now).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+50
-34
@@ -1,7 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// cli handlers for account management (microsoft oauth + offline accounts)
|
||||
use std::io;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -24,6 +23,7 @@ pub async fn handle_account(matches: &ArgMatches) -> CliResult {
|
||||
|
||||
fn list_accounts() -> CliResult {
|
||||
let store = AccountStore::load();
|
||||
store.check_loaded()?;
|
||||
let rows = store
|
||||
.accounts
|
||||
.iter()
|
||||
@@ -32,11 +32,12 @@ fn list_accounts() -> CliResult {
|
||||
active_marker(account.active).to_string(),
|
||||
account.username.clone(),
|
||||
format!("{:?}", account.account_type),
|
||||
account.uuid.clone(),
|
||||
]
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
print_table(&[" ", "Username", "Type"], &rows);
|
||||
print_table(&[" ", "Username", "Type", "UUID"], &rows);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -54,38 +55,21 @@ async fn add_account(matches: &ArgMatches) -> CliResult {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// microsoft auth runs on a background thread via device code flow.
|
||||
// polls two shared slots: one for the device code to display,
|
||||
// then one for the final auth result. not the prettiest pattern
|
||||
// but it keeps the oauth complexity out of the CLI layer.
|
||||
async fn add_microsoft_account() -> CliResult {
|
||||
if let Ok(mut slot) = crate::auth::DEVICE_CODE_DISPLAY.lock() {
|
||||
*slot = None;
|
||||
}
|
||||
|
||||
let result_arc = crate::auth::start_microsoft_auth();
|
||||
|
||||
// wait for the device code to become available before showing it
|
||||
loop {
|
||||
if let Ok(slot) = crate::auth::DEVICE_CODE_DISPLAY.lock()
|
||||
&& let Some(info) = slot.as_ref()
|
||||
{
|
||||
println!("Open: {}", info.verification_uri);
|
||||
println!("Code: {}", info.user_code);
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
let info = wait_for_device_code(&result_arc).await?;
|
||||
println!("Open: {}", info.verification_uri);
|
||||
println!("Code: {}", info.user_code);
|
||||
|
||||
// now wait for the user to complete auth in their browser
|
||||
loop {
|
||||
if let Ok(slot) = result_arc.lock()
|
||||
if let Ok(slot) = result_arc.result.lock()
|
||||
&& let Some(result) = slot.as_ref()
|
||||
{
|
||||
return match result {
|
||||
AuthResult::Success(account) => {
|
||||
let mut store = AccountStore::load();
|
||||
store.add(account.clone());
|
||||
store.add(account.clone())?;
|
||||
println!("Added Microsoft account '{}'.", account.username);
|
||||
Ok(())
|
||||
}
|
||||
@@ -96,7 +80,26 @@ async fn add_microsoft_account() -> CliResult {
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_device_code(
|
||||
result: &crate::auth::MicrosoftAuth,
|
||||
) -> io::Result<crate::auth::DeviceCodeInfo> {
|
||||
loop {
|
||||
if let Ok(slot) = result.device_code.lock()
|
||||
&& let Some(info) = slot.as_ref()
|
||||
{
|
||||
return Ok(info.clone());
|
||||
}
|
||||
if let Ok(slot) = result.result.lock()
|
||||
&& let Some(AuthResult::Error(message)) = slot.as_ref()
|
||||
{
|
||||
return Err(io::Error::other(message.clone()));
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn add_offline_account(store: &mut AccountStore, username: &str) -> CliResult {
|
||||
store.check_loaded()?;
|
||||
let username = username.trim();
|
||||
if username.is_empty() {
|
||||
return Err(io::Error::other("offline username cannot be empty").into());
|
||||
@@ -108,22 +111,22 @@ fn add_offline_account(store: &mut AccountStore, username: &str) -> CliResult {
|
||||
.into());
|
||||
}
|
||||
|
||||
store.add(crate::auth::create_offline_account(username));
|
||||
store.add(crate::auth::create_offline_account(username))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete_account(matches: &ArgMatches) -> CliResult {
|
||||
let username = required_arg(matches, "username")?;
|
||||
let mut store = AccountStore::load();
|
||||
let index = find_account_index(&store.accounts, username)
|
||||
.ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?;
|
||||
store.check_loaded()?;
|
||||
let index = find_account_index(&store.accounts, username)?;
|
||||
|
||||
if !matches.get_flag("yes") && !confirm(&format!("Delete '{}'", username))? {
|
||||
println!("Cancelled.");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
store.remove(index);
|
||||
store.remove(index)?;
|
||||
println!("Deleted '{}'.", username);
|
||||
Ok(())
|
||||
}
|
||||
@@ -131,17 +134,30 @@ fn delete_account(matches: &ArgMatches) -> CliResult {
|
||||
fn use_account(matches: &ArgMatches) -> CliResult {
|
||||
let username = required_arg(matches, "username")?;
|
||||
let mut store = AccountStore::load();
|
||||
let index = find_account_index(&store.accounts, username)
|
||||
.ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?;
|
||||
store.set_active(index);
|
||||
store.check_loaded()?;
|
||||
let index = find_account_index(&store.accounts, username)?;
|
||||
store.set_active(index)?;
|
||||
println!("Active account set to '{}'.", username);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn find_account_index(accounts: &[Account], username: &str) -> Option<usize> {
|
||||
accounts
|
||||
fn find_account_index(accounts: &[Account], selector: &str) -> io::Result<usize> {
|
||||
if let Some(index) = accounts.iter().position(|account| account.uuid == selector) {
|
||||
return Ok(index);
|
||||
}
|
||||
let mut matches = accounts
|
||||
.iter()
|
||||
.position(|account| account.username.eq_ignore_ascii_case(username))
|
||||
.enumerate()
|
||||
.filter(|(_, account)| account.username.eq_ignore_ascii_case(selector));
|
||||
let (index, _) = matches
|
||||
.next()
|
||||
.ok_or_else(|| io::Error::other(format!("account '{selector}' not found")))?;
|
||||
if matches.next().is_some() {
|
||||
return Err(io::Error::other(format!(
|
||||
"Account '{selector}' is ambiguous; use its UUID"
|
||||
)));
|
||||
}
|
||||
Ok(index)
|
||||
}
|
||||
|
||||
use super::utils::{confirm, required_arg};
|
||||
|
||||
+18
-7
@@ -1,9 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// unified content management for mods, resource packs, and shaders.
|
||||
// all three content types share the same list/enable/disable workflow,
|
||||
// just with different scanner functions plugged in.
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
@@ -61,10 +58,24 @@ fn handle_content(matches: &ArgMatches, kind: &str, scan: Scanner) -> CliResult
|
||||
pub(crate) fn find_entry_by_stem<'a>(
|
||||
entries: &'a [ContentEntry],
|
||||
target: &str,
|
||||
) -> Option<&'a ContentEntry> {
|
||||
entries
|
||||
) -> io::Result<Option<&'a ContentEntry>> {
|
||||
let exact = entries
|
||||
.iter()
|
||||
.find(|entry| entry.file_stem.eq_ignore_ascii_case(target))
|
||||
.any(|entry| entry.path.file_name().is_some_and(|name| name == target));
|
||||
let mut matches = entries.iter().filter(|entry| {
|
||||
if exact {
|
||||
entry.path.file_name().is_some_and(|name| name == target)
|
||||
} else {
|
||||
entry.file_stem.eq_ignore_ascii_case(target)
|
||||
}
|
||||
});
|
||||
let found = matches.next();
|
||||
if matches.next().is_some() {
|
||||
return Err(io::Error::other(format!(
|
||||
"Content selector '{target}' is ambiguous; use its filename"
|
||||
)));
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
fn list_entries(instance: &str, scan: Scanner) -> CliResult {
|
||||
@@ -98,7 +109,7 @@ fn toggle_entry(
|
||||
let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
|
||||
require_instance(&instances_dir, instance)?;
|
||||
let entries = scan(&instances_dir, instance);
|
||||
let entry = find_entry_by_stem(&entries, target)
|
||||
let entry = find_entry_by_stem(&entries, target)?
|
||||
.ok_or_else(|| io::Error::other(format!("{} '{}' not found", kind, target)))?;
|
||||
|
||||
if entry.enabled == should_enable {
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
use clap::{Arg, ArgAction, ArgGroup, ArgMatches, Command};
|
||||
|
||||
use crate::instance::InstanceManager;
|
||||
use crate::instance::export::{
|
||||
ExportOptions, PackFormat, prepare_export, prepare_instance_export, validate_output,
|
||||
write_export,
|
||||
};
|
||||
|
||||
pub fn command() -> Command {
|
||||
Command::new("export")
|
||||
.about("Export a CurseForge, Modrinth, or MultiMC/Prism modpack")
|
||||
.arg(
|
||||
Arg::new("format")
|
||||
.long("format")
|
||||
.value_parser(["curseforge", "mrpack", "mmc"])
|
||||
.default_value("curseforge"),
|
||||
)
|
||||
.arg(Arg::new("instance").help("Instance name"))
|
||||
.arg(
|
||||
Arg::new("directory")
|
||||
.long("directory")
|
||||
.requires_all(["minecraft", "loader"])
|
||||
.help("Standalone Minecraft game folder"),
|
||||
)
|
||||
.group(
|
||||
ArgGroup::new("source")
|
||||
.args(["instance", "directory"])
|
||||
.required(true),
|
||||
)
|
||||
.arg(Arg::new("output").long("output").short('o').required(true))
|
||||
.arg(Arg::new("name").long("name"))
|
||||
.arg(Arg::new("version").long("version").default_value("1.0.0"))
|
||||
.arg(Arg::new("author").long("author").default_value(""))
|
||||
.arg(
|
||||
Arg::new("minecraft")
|
||||
.long("minecraft")
|
||||
.requires("directory"),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("loader")
|
||||
.long("loader")
|
||||
.requires("directory")
|
||||
.value_parser(["vanilla", "forge", "fabric", "neoforge", "quilt"]),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("loader-version")
|
||||
.long("loader-version")
|
||||
.requires("directory"),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("include")
|
||||
.long("include")
|
||||
.action(ArgAction::Append)
|
||||
.help("Additional game-relative file or folder; repeatable"),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("bundle-unmatched")
|
||||
.long("bundle-unmatched")
|
||||
.action(ArgAction::SetTrue)
|
||||
.help("Allow bundling custom/unmatched content (check redistribution permissions)"),
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn handle_export(matches: &ArgMatches) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut instance_manager = None;
|
||||
let (root, name, game_version, loader, loader_version) = if let Some(directory) =
|
||||
matches.get_one::<String>("directory")
|
||||
{
|
||||
let game_version = matches
|
||||
.get_one::<String>("minecraft")
|
||||
.ok_or("--directory requires --minecraft")?
|
||||
.clone();
|
||||
let loader = super::instance::parse_loader(super::utils::required_arg(matches, "loader")?)?;
|
||||
let root = crate::config::settings::resolve_path(directory);
|
||||
let name = root
|
||||
.file_name()
|
||||
.and_then(|value| value.to_str())
|
||||
.unwrap_or("Modpack")
|
||||
.to_owned();
|
||||
(
|
||||
root,
|
||||
name,
|
||||
game_version,
|
||||
loader,
|
||||
matches.get_one::<String>("loader-version").cloned(),
|
||||
)
|
||||
} else {
|
||||
let name = super::utils::required_arg(matches, "instance")?;
|
||||
let settings = crate::config::SETTINGS.read();
|
||||
let manager = InstanceManager::new(
|
||||
settings.paths.resolve_instances_dir(),
|
||||
settings.paths.resolve_meta_dir(),
|
||||
);
|
||||
drop(settings);
|
||||
let config = manager.load_one(name)?;
|
||||
let root = crate::storage::InstancePaths::new(manager.instances_dir.join(name)).minecraft();
|
||||
instance_manager = Some(manager);
|
||||
(
|
||||
root,
|
||||
config.name,
|
||||
config.game_version,
|
||||
config.loader,
|
||||
config.loader_version,
|
||||
)
|
||||
};
|
||||
let options = ExportOptions {
|
||||
format: match super::utils::required_arg(matches, "format")? {
|
||||
"mrpack" => PackFormat::Mrpack,
|
||||
"mmc" => PackFormat::Mmc,
|
||||
_ => PackFormat::CurseForge,
|
||||
},
|
||||
name: matches.get_one::<String>("name").cloned().unwrap_or(name),
|
||||
version: super::utils::required_arg(matches, "version")?.to_owned(),
|
||||
author: super::utils::required_arg(matches, "author")?.to_owned(),
|
||||
game_version,
|
||||
loader,
|
||||
loader_version,
|
||||
include: matches
|
||||
.get_many::<String>("include")
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(std::path::PathBuf::from)
|
||||
.collect(),
|
||||
bundle_unmatched: matches.get_flag("bundle-unmatched"),
|
||||
};
|
||||
let output =
|
||||
crate::config::settings::resolve_path(super::utils::required_arg(matches, "output")?);
|
||||
validate_output(&root, &output).map_err(|error| error.to_string())?;
|
||||
println!(
|
||||
"Exporting '{}': identifying mods and packaging selected files...",
|
||||
options.name
|
||||
);
|
||||
let plan = if let Some(manager) = instance_manager {
|
||||
prepare_instance_export(
|
||||
&manager,
|
||||
super::utils::required_arg(matches, "instance")?,
|
||||
&options,
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
prepare_export(&root, &options).await
|
||||
}
|
||||
.map_err(|error| error.to_string())?;
|
||||
if !options.bundle_unmatched && !plan.unmatched.is_empty() {
|
||||
eprintln!(
|
||||
"To allow bundling unmatched content, use --bundle-unmatched after checking redistribution permissions."
|
||||
);
|
||||
}
|
||||
let report = write_export(plan, &output)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
if !report.unmatched.is_empty() {
|
||||
eprintln!(
|
||||
"Bundled unmatched content:\n{}",
|
||||
report
|
||||
.unmatched
|
||||
.iter()
|
||||
.map(|path| path.display().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
);
|
||||
}
|
||||
println!("Exported '{}' to {}", options.name, output.display());
|
||||
println!(
|
||||
"{} referenced files, {} bundled files",
|
||||
report.referenced_count, report.bundled_count
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
+2
-3
@@ -1,10 +1,9 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// modpack importing from modrinth (remote slug/url) or local files (.mrpack, mmc zips).
|
||||
// resolves the input, downloads if needed, then hands off to the import engine.
|
||||
use clap::ArgMatches;
|
||||
|
||||
use super::utils::required_arg;
|
||||
use crate::instance::InstanceManager;
|
||||
use crate::instance::import::{ImportInput, parse_import_input};
|
||||
use crate::net::modrinth;
|
||||
@@ -12,7 +11,7 @@ use crate::net::modrinth;
|
||||
type CliResult = Result<(), Box<dyn std::error::Error>>;
|
||||
|
||||
pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
||||
let input = matches.get_one::<String>("source").unwrap();
|
||||
let input = required_arg(matches, "source")?;
|
||||
let override_name = matches.get_one::<String>("name");
|
||||
let override_version = matches.get_one::<String>("version");
|
||||
|
||||
|
||||
+20
-31
@@ -1,8 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// instance lifecycle: create, delete, rename, launch, config, desktop shortcuts.
|
||||
// the heaviest handler in the CLI since instances are the core concept.
|
||||
use std::io;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -24,7 +22,7 @@ pub async fn handle_instance(matches: &ArgMatches) -> CliResult {
|
||||
Some(("rename", sub_matches)) => rename_instance(sub_matches),
|
||||
Some(("launch", sub_matches)) => launch_instance(sub_matches).await,
|
||||
Some(("config", sub_matches)) => config_instance(sub_matches),
|
||||
Some(("profile", sub_matches)) => profile_instance(sub_matches),
|
||||
Some(("profile", sub_matches)) => profile_instance(sub_matches, &manager()),
|
||||
Some(("desktop", sub_matches)) => desktop_instance(sub_matches),
|
||||
_ => Ok(()),
|
||||
}
|
||||
@@ -130,12 +128,10 @@ async fn launch_instance(matches: &ArgMatches) -> CliResult {
|
||||
loop {
|
||||
match crate::instance::runtime::get(name) {
|
||||
Some(RunState::Crashed(Some(code))) => {
|
||||
println!("Game exited with status {}", code);
|
||||
break;
|
||||
return Err(io::Error::other(format!("Game exited with status {code}")).into());
|
||||
}
|
||||
Some(RunState::Crashed(None)) => {
|
||||
println!("Game was terminated");
|
||||
break;
|
||||
return Err(io::Error::other("Game was terminated without an exit code").into());
|
||||
}
|
||||
Some(_) => tokio::time::sleep(Duration::from_millis(500)).await,
|
||||
None => {
|
||||
@@ -210,7 +206,7 @@ fn config_instance(matches: &ArgMatches) -> CliResult {
|
||||
if config.jvm_args.is_empty() {
|
||||
"-".to_string()
|
||||
} else {
|
||||
config.jvm_args.join(" ")
|
||||
crate::config::settings::format_tag_values(&config.jvm_args)
|
||||
},
|
||||
],
|
||||
vec![
|
||||
@@ -230,19 +226,10 @@ fn config_instance(matches: &ArgMatches) -> CliResult {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn profile_instance(matches: &ArgMatches) -> CliResult {
|
||||
fn profile_instance(matches: &ArgMatches, manager: &InstanceManager) -> CliResult {
|
||||
let name = required_arg(matches, "name")?;
|
||||
let manager = manager();
|
||||
let mut config = manager.load_one(name)?;
|
||||
let profiles = crate::instance::config_sync::list_profiles(&manager.meta_dir)?;
|
||||
if config
|
||||
.config_sync_profile
|
||||
.as_ref()
|
||||
.is_some_and(|profile| !profiles.iter().any(|candidate| candidate == profile))
|
||||
{
|
||||
config.config_sync_profile = None;
|
||||
manager.save(&config)?;
|
||||
}
|
||||
|
||||
let Some(profile) = matches.get_one::<String>("profile") else {
|
||||
let rows = vec![
|
||||
@@ -268,16 +255,7 @@ fn profile_instance(matches: &ArgMatches) -> CliResult {
|
||||
} else {
|
||||
Some(profile.as_str())
|
||||
};
|
||||
let instance_dir = manager.instances_dir.join(&config.name);
|
||||
let selected = crate::instance::config_sync::switch_profile(
|
||||
&config.name,
|
||||
config.config_sync_profile.as_deref(),
|
||||
target,
|
||||
&manager.meta_dir,
|
||||
&instance_dir,
|
||||
)?;
|
||||
config.config_sync_profile = selected;
|
||||
manager.save(&config)?;
|
||||
crate::instance::config_sync::switch_profile_and_save(manager, &mut config, target)?;
|
||||
|
||||
println!(
|
||||
"Updated '{}' config profile to {}.",
|
||||
@@ -308,10 +286,10 @@ fn apply_config_update(
|
||||
) -> CliResult {
|
||||
match key {
|
||||
"memory-max" => {
|
||||
config.memory_max = crate::instance::normalize_memory_value(value);
|
||||
config.memory_max = parse_memory_update(value)?;
|
||||
}
|
||||
"memory-min" => {
|
||||
config.memory_min = crate::instance::normalize_memory_value(value);
|
||||
config.memory_min = parse_memory_update(value)?;
|
||||
}
|
||||
"java-path" => {
|
||||
config.java_path = if value.is_empty() {
|
||||
@@ -321,7 +299,8 @@ fn apply_config_update(
|
||||
}
|
||||
}
|
||||
"jvm-args" => {
|
||||
config.jvm_args = value.split_whitespace().map(String::from).collect();
|
||||
config.jvm_args =
|
||||
crate::config::settings::parse_tag_values(value).map_err(io::Error::other)?;
|
||||
}
|
||||
"resolution" => {
|
||||
config.resolution = if value.is_empty() {
|
||||
@@ -338,6 +317,16 @@ fn apply_config_update(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_memory_update(value: &str) -> Result<Option<String>, io::Error> {
|
||||
if value.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
crate::instance::normalize_memory_value(value)
|
||||
.map(Some)
|
||||
.ok_or_else(|| io::Error::other(format!("invalid memory size '{value}'")))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests/instance.rs"]
|
||||
mod tests;
|
||||
+49
-28
@@ -1,7 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// viewing minecraft log files from the CLI, with optional `--follow` for tailing
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
@@ -45,47 +44,69 @@ async fn show_log(matches: &ArgMatches) -> CliResult {
|
||||
require_instance(&instances_dir, instance)?;
|
||||
let path = resolve_log_path(&instances_dir, instance, file)?;
|
||||
|
||||
let lines = crate::instance::logs::files::read_log_file(&path);
|
||||
for line in &lines {
|
||||
println!("{}", line);
|
||||
}
|
||||
|
||||
// ghetto tail -f: re-read the whole file and print new lines.
|
||||
// not efficient, but log files are small and this is simple.
|
||||
if follow {
|
||||
let mut last_len = lines.len();
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
let new_lines = crate::instance::logs::files::read_log_file(&path);
|
||||
for line in new_lines.iter().skip(last_len) {
|
||||
println!("{}", line);
|
||||
}
|
||||
last_len = new_lines.len();
|
||||
use std::io::Write;
|
||||
if path.extension().is_some_and(|extension| extension == "gz") {
|
||||
return Err(io::Error::other("Cannot follow a compressed log").into());
|
||||
}
|
||||
let mut offset = 0;
|
||||
loop {
|
||||
{
|
||||
let bytes = read_new_log_bytes(&path, &mut offset)?;
|
||||
let mut output = io::stdout().lock();
|
||||
output.write_all(&bytes)?;
|
||||
output.flush()?;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
}
|
||||
for line in crate::instance::logs::files::read_log_file(&path) {
|
||||
println!("{line}");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// if no file is specified, grab the most recent log (first from the sorted scan)
|
||||
fn read_new_log_bytes(path: &Path, offset: &mut u64) -> io::Result<Vec<u8>> {
|
||||
use std::io::{Read, Seek};
|
||||
let mut file = std::fs::File::open(path)?;
|
||||
if file.metadata()?.len() < *offset {
|
||||
*offset = 0;
|
||||
}
|
||||
file.seek(io::SeekFrom::Start(*offset))?;
|
||||
let mut bytes = Vec::new();
|
||||
file.read_to_end(&mut bytes)?;
|
||||
*offset += bytes.len() as u64;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_log_path(
|
||||
instances_dir: &Path,
|
||||
instance: &str,
|
||||
file: Option<&str>,
|
||||
) -> Result<PathBuf, io::Error> {
|
||||
if let Some(name) = file {
|
||||
let path = crate::instance::logs::files::log_dir(instances_dir, instance).join(name);
|
||||
if !path.exists() {
|
||||
return Err(io::Error::other(format!("log '{}' not found", name)));
|
||||
let log_dir = crate::instance::logs::files::log_dir(instances_dir, instance);
|
||||
let path = if let Some(name) = file {
|
||||
let filename = Path::new(name);
|
||||
if !crate::storage::safe_relative_path(filename) || filename.components().count() != 1 {
|
||||
return Err(io::Error::other("log file must be a single filename"));
|
||||
}
|
||||
return Ok(path);
|
||||
log_dir.join(filename)
|
||||
} else {
|
||||
crate::instance::logs::files::scan_log_files(instances_dir, instance)
|
||||
.into_iter()
|
||||
.next()
|
||||
.map(|entry| entry.path)
|
||||
.ok_or_else(|| io::Error::other(format!("no log files found for '{}'", instance)))?
|
||||
};
|
||||
let log_dir = std::fs::canonicalize(log_dir)?;
|
||||
let path = std::fs::canonicalize(path)?;
|
||||
if path.parent() != Some(log_dir.as_path()) || !path.is_file() {
|
||||
return Err(io::Error::other(
|
||||
"log file is outside the instance log directory",
|
||||
));
|
||||
}
|
||||
|
||||
crate::instance::logs::files::scan_log_files(instances_dir, instance)
|
||||
.into_iter()
|
||||
.next()
|
||||
.map(|entry| entry.path)
|
||||
.ok_or_else(|| io::Error::other(format!("no log files found for '{}'", instance)))
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
use super::utils::{require_instance, required_arg};
|
||||
|
||||
+41
-42
@@ -1,10 +1,9 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// cli entry point and clap command definitions.
|
||||
// no subcommand = launch TUI, otherwise dispatch to the appropriate handler.
|
||||
mod account;
|
||||
mod content;
|
||||
mod export;
|
||||
mod import;
|
||||
mod instance;
|
||||
mod log;
|
||||
@@ -17,9 +16,7 @@ use clap::{Arg, ArgAction, ArgGroup, Command};
|
||||
pub async fn init() {
|
||||
let matches = build_command().get_matches();
|
||||
|
||||
// no subcommand means the user just ran `rmcl` bare, so fall through to TUI mode
|
||||
if matches.subcommand().is_none() {
|
||||
// force-init the theme so it's ready before the TUI renders
|
||||
let _ = &*crate::config::theme::THEME;
|
||||
if let Err(e) = crate::tui::show().await {
|
||||
tracing::error!("TUI error: {}", e);
|
||||
@@ -27,51 +24,52 @@ pub async fn init() {
|
||||
return;
|
||||
}
|
||||
|
||||
let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
|
||||
let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir();
|
||||
let config = crate::config::get_config_path().join("config.toml");
|
||||
if crate::layout_migration::is_needed(&instances_dir, &meta_dir) {
|
||||
if let Err(error) =
|
||||
crate::layout_migration::run(&instances_dir, &meta_dir, &config, |progress| {
|
||||
eprintln!(
|
||||
"{}: {} ({}/{})",
|
||||
progress.phase, progress.item, progress.current, progress.total
|
||||
);
|
||||
})
|
||||
{
|
||||
eprintln!("error: layout migration failed safely: {error}");
|
||||
if !matches!(matches.subcommand_name(), Some("account" | "version")) {
|
||||
let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
|
||||
let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir();
|
||||
let config = crate::config::get_config_path().join("config.toml");
|
||||
if crate::layout_migration::is_needed(&instances_dir, &meta_dir) {
|
||||
if let Err(error) =
|
||||
crate::layout_migration::run(&instances_dir, &meta_dir, &config, |progress| {
|
||||
eprintln!(
|
||||
"{}: {} ({}/{})",
|
||||
progress.phase, progress.item, progress.current, progress.total
|
||||
);
|
||||
})
|
||||
{
|
||||
eprintln!("error: layout migration failed safely: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
} else if let Err(error) = crate::layout_migration::initialize_new_layout(&meta_dir) {
|
||||
eprintln!("error: cannot initialize metadata layout: {error}");
|
||||
std::process::exit(1);
|
||||
} else if let Err(error) = crate::config::upgrade_config_file(&config) {
|
||||
eprintln!("warning: cannot upgrade launcher config: {error}");
|
||||
}
|
||||
} else if let Err(error) = crate::layout_migration::initialize_new_layout(&meta_dir) {
|
||||
eprintln!("error: cannot initialize metadata layout: {error}");
|
||||
std::process::exit(1);
|
||||
} else if let Err(error) = crate::config::upgrade_config_file(&config) {
|
||||
eprintln!("warning: cannot upgrade launcher config: {error}");
|
||||
}
|
||||
if crate::layout_migration::cache_rebuild_pending(&meta_dir) {
|
||||
let manager = crate::instance::InstanceManager::new(&instances_dir, &meta_dir);
|
||||
let instances = manager.load_all();
|
||||
for (index, instance) in instances.iter().enumerate() {
|
||||
eprintln!(
|
||||
"Rebuilding runtime cache: {} ({}/{})",
|
||||
instance.name,
|
||||
index + 1,
|
||||
instances.len()
|
||||
);
|
||||
if let Err(error) = manager.repair_runtime_cache(instance).await {
|
||||
if crate::layout_migration::cache_rebuild_pending(&meta_dir) {
|
||||
let manager = crate::instance::InstanceManager::new(&instances_dir, &meta_dir);
|
||||
let instances = manager.load_all();
|
||||
for (index, instance) in instances.iter().enumerate() {
|
||||
eprintln!(
|
||||
"error: runtime cache rebuild stopped safely for '{}': {error}",
|
||||
instance.name
|
||||
"Rebuilding runtime cache: {} ({}/{})",
|
||||
instance.name,
|
||||
index + 1,
|
||||
instances.len()
|
||||
);
|
||||
if let Err(error) = manager.repair_runtime_cache(instance).await {
|
||||
eprintln!(
|
||||
"error: runtime cache rebuild stopped safely for '{}': {error}",
|
||||
instance.name
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
if let Err(error) = crate::layout_migration::finish_cache_rebuild(&meta_dir) {
|
||||
eprintln!("error: cannot finish runtime cache migration: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
if let Err(error) = crate::layout_migration::finish_cache_rebuild(&meta_dir) {
|
||||
eprintln!("error: cannot finish runtime cache migration: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
let result = match matches.subcommand() {
|
||||
Some(("instance", sub_matches)) => instance::handle_instance(sub_matches).await,
|
||||
Some(("mod", sub_matches)) => content::handle_mod(sub_matches),
|
||||
@@ -81,6 +79,7 @@ pub async fn init() {
|
||||
Some(("log", sub_matches)) => log::handle_log(sub_matches).await,
|
||||
Some(("version", sub_matches)) => version::handle_version(sub_matches).await,
|
||||
Some(("import", sub_matches)) => import::handle_import(sub_matches).await,
|
||||
Some(("export", sub_matches)) => export::handle_export(sub_matches).await,
|
||||
_ => Ok(()),
|
||||
};
|
||||
|
||||
@@ -167,6 +166,7 @@ fn build_command() -> Command {
|
||||
),
|
||||
)
|
||||
.subcommand(build_content_command("mod", "mods"))
|
||||
.subcommand(export::command())
|
||||
.subcommand(build_content_command("pack", "resource packs"))
|
||||
.subcommand(build_content_command("shader", "shaders"))
|
||||
.subcommand(
|
||||
@@ -265,7 +265,6 @@ fn build_command() -> Command {
|
||||
)
|
||||
}
|
||||
|
||||
// mods, resource packs, and shaders all share the same list/enable/disable shape
|
||||
fn build_content_command(name: &'static str, about: &'static str) -> Command {
|
||||
Command::new(name)
|
||||
.about(format!("Manage {}", about))
|
||||
|
||||
+1
-7
@@ -1,8 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// plain-text table rendering for CLI output. no fancy box-drawing,
|
||||
// just left-aligned columns with two-space gaps. keeps it pipeable.
|
||||
use chrono::{DateTime, Utc};
|
||||
use ratatui::text::Span;
|
||||
|
||||
@@ -41,13 +39,10 @@ pub fn active_marker(active: bool) -> &'static str {
|
||||
if active { ">" } else { " " }
|
||||
}
|
||||
|
||||
// display width (not byte length): instance and pack names are often
|
||||
// non-ASCII, and padding by bytes misaligns every row below them.
|
||||
fn display_width(value: &str) -> usize {
|
||||
Span::raw(value).width()
|
||||
}
|
||||
|
||||
// find the widest value in each column to pad everything evenly
|
||||
fn column_widths(headers: &[&str], rows: &[Vec<String>]) -> Vec<usize> {
|
||||
let mut widths: Vec<usize> = headers.iter().map(|header| display_width(header)).collect();
|
||||
|
||||
@@ -69,8 +64,7 @@ fn render_row(row: &[String], widths: &[usize]) -> String {
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, width)| {
|
||||
// manual space padding: {:<width$} counts chars, not columns,
|
||||
// so it would under-pad multi-byte names.
|
||||
// Rust's width formatter counts characters rather than terminal cells.
|
||||
let value = row.get(index).map(String::as_str).unwrap_or("");
|
||||
let mut cell = String::from(value);
|
||||
cell.push_str(&" ".repeat(width.saturating_sub(display_width(value))));
|
||||
|
||||
@@ -20,7 +20,7 @@ fn microsoft_account() -> Account {
|
||||
fn creates_offline_account_after_microsoft_account_exists() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json"));
|
||||
store.add(microsoft_account());
|
||||
store.add(microsoft_account()).unwrap();
|
||||
add_offline_account(&mut store, "Steve").expect("offline account should be added");
|
||||
|
||||
assert_eq!(store.accounts.len(), 2);
|
||||
@@ -45,3 +45,36 @@ fn rejects_empty_offline_username() {
|
||||
let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json"));
|
||||
assert!(add_offline_account(&mut store, " ").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_usernames_require_a_unique_account_selector() {
|
||||
let mut microsoft = microsoft_account();
|
||||
microsoft.username = "Steve".to_owned();
|
||||
let offline = crate::auth::create_offline_account("Steve");
|
||||
let accounts = vec![microsoft, offline.clone()];
|
||||
|
||||
assert!(super::find_account_index(&accounts, "Steve").is_err());
|
||||
assert_eq!(
|
||||
super::find_account_index(&accounts, &offline.uuid).unwrap(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_code_failure_does_not_wait_for_a_code() {
|
||||
let _guard = crate::tests::TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|error| error.into_inner());
|
||||
let result = crate::auth::MicrosoftAuth::default();
|
||||
*result.result.lock().unwrap() = Some(crate::auth::AuthResult::Error(
|
||||
"device code failed".to_owned(),
|
||||
));
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_time()
|
||||
.build()
|
||||
.unwrap();
|
||||
let error = runtime
|
||||
.block_on(super::wait_for_device_code(&result))
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("device code failed"));
|
||||
}
|
||||
@@ -17,3 +17,29 @@ fn parses_instance_list_subcommand() {
|
||||
"instance list should resolve to the list subcommand"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exports_accept_each_format_and_preserve_curseforge_default() {
|
||||
for format in [None, Some("curseforge"), Some("mrpack"), Some("mmc")] {
|
||||
let mut args = vec!["rmcl", "export", "Example", "--output", "pack.zip"];
|
||||
if let Some(format) = format {
|
||||
args.extend(["--format", format]);
|
||||
}
|
||||
let matches = build_command().try_get_matches_from(args).unwrap();
|
||||
assert_eq!(
|
||||
matches
|
||||
.subcommand_matches("export")
|
||||
.unwrap()
|
||||
.get_one::<String>("format")
|
||||
.map(String::as_str),
|
||||
Some(format.unwrap_or("curseforge"))
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
build_command()
|
||||
.try_get_matches_from([
|
||||
"rmcl", "export", "Example", "--output", "pack.zip", "--format", "unknown"
|
||||
])
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
@@ -29,12 +29,39 @@ fn entry(file_stem: &str) -> ContentEntry {
|
||||
#[test]
|
||||
fn matches_by_stem_case_insensitively() {
|
||||
let entries = vec![entry("Sodium"), entry("Lithium")];
|
||||
let found = find_entry_by_stem(&entries, "sOdIuM").expect("entry should match");
|
||||
let found = find_entry_by_stem(&entries, "sOdIuM")
|
||||
.unwrap()
|
||||
.expect("entry should match");
|
||||
assert_eq!(found.file_stem, "Sodium");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_none_for_missing_stem() {
|
||||
let entries = vec![entry("Sodium")];
|
||||
assert!(find_entry_by_stem(&entries, "iris").is_none());
|
||||
assert!(find_entry_by_stem(&entries, "iris").unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colliding_enabled_and_disabled_files_require_an_exact_filename_and_cannot_overwrite() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let mut enabled = entry("same");
|
||||
enabled.path = temp.path().join("same.jar");
|
||||
let mut disabled = enabled.clone();
|
||||
disabled.enabled = false;
|
||||
disabled.path = temp.path().join("same.jar.disabled");
|
||||
std::fs::write(&enabled.path, b"enabled").unwrap();
|
||||
std::fs::write(&disabled.path, b"disabled").unwrap();
|
||||
let entries = [enabled, disabled];
|
||||
assert!(find_entry_by_stem(&entries, "same").is_err());
|
||||
assert!(
|
||||
!find_entry_by_stem(&entries, "same.jar.disabled")
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.enabled
|
||||
);
|
||||
for entry in &entries {
|
||||
assert!(crate::instance::content::entry::toggle_entry(entry).is_err());
|
||||
}
|
||||
assert_eq!(std::fs::read(&entries[0].path).unwrap(), b"enabled");
|
||||
assert_eq!(std::fs::read(&entries[1].path).unwrap(), b"disabled");
|
||||
}
|
||||
@@ -17,3 +17,140 @@ fn rejects_invalid_resolution_format() {
|
||||
assert!(parse_resolution("1920xa").is_err());
|
||||
assert!(parse_resolution("0x1080").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_memory_update_keeps_existing_setting() {
|
||||
let mut config: crate::instance::InstanceConfig = serde_json::from_value(serde_json::json!({
|
||||
"name": "test", "game_version": "1.21.1", "loader": "vanilla",
|
||||
"loader_version": null, "created": "2026-01-01T00:00:00Z", "memory_max": "8G"
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
assert!(super::apply_config_update(&mut config, "memory-max", "garbage").is_err());
|
||||
assert_eq!(config.memory_max.as_deref(), Some("8G"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jvm_argument_updates_preserve_quoted_paths_and_repeated_options() {
|
||||
let mut config: crate::instance::InstanceConfig = serde_json::from_value(serde_json::json!({
|
||||
"name": "test", "game_version": "1.21.1", "loader": "vanilla",
|
||||
"loader_version": null, "created": "2026-01-01T00:00:00Z"
|
||||
}))
|
||||
.unwrap();
|
||||
super::apply_config_update(&mut config, "jvm-args", r#""-Dpath=C:\Program Files\Java" --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED"#).unwrap();
|
||||
assert_eq!(
|
||||
config.jvm_args,
|
||||
[
|
||||
r"-Dpath=C:\Program Files\Java",
|
||||
"--add-opens",
|
||||
"java.base/java.lang=ALL-UNNAMED",
|
||||
"--add-opens",
|
||||
"java.base/java.util=ALL-UNNAMED"
|
||||
]
|
||||
);
|
||||
let previous = config.jvm_args.clone();
|
||||
assert!(super::apply_config_update(&mut config, "jvm-args", "\"unterminated").is_err());
|
||||
assert_eq!(config.jvm_args, previous);
|
||||
super::apply_config_update(&mut config, "jvm-args", "").unwrap();
|
||||
assert!(config.jvm_args.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_sync_profile_display_is_read_only_and_deleted_profiles_restore_local_defaults() {
|
||||
for target in ["default", "other"] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let manager = crate::instance::InstanceManager::new(
|
||||
tmp.path().join("instances"),
|
||||
tmp.path().join("meta"),
|
||||
);
|
||||
let instance = manager.instances_dir.join("inst");
|
||||
let minecraft = crate::storage::InstancePaths::new(&instance).minecraft();
|
||||
std::fs::create_dir_all(minecraft.join("config")).unwrap();
|
||||
std::fs::write(minecraft.join("options.txt"), b"local-default").unwrap();
|
||||
std::fs::write(minecraft.join("config/value"), b"local-default").unwrap();
|
||||
let mut config = serde_json::from_value(serde_json::json!({
|
||||
"name": "inst", "game_version": "1.21.1", "loader": "vanilla", "loader_version": null,
|
||||
"created": "2026-01-01T00:00:00Z"
|
||||
}))
|
||||
.unwrap();
|
||||
manager.save(&config).unwrap();
|
||||
crate::instance::config_sync::switch_profile_and_save(&manager, &mut config, Some("main"))
|
||||
.unwrap();
|
||||
std::fs::write(minecraft.join("options.txt"), b"profile-options").unwrap();
|
||||
crate::instance::config_sync::delete_profile(&manager.meta_dir, "main").unwrap();
|
||||
crate::instance::config_sync::create_profile(&manager.meta_dir, "other").unwrap();
|
||||
std::fs::write(
|
||||
crate::storage::MetadataPaths::new(&manager.meta_dir)
|
||||
.profiles()
|
||||
.join("other/options.txt"),
|
||||
b"other-options",
|
||||
)
|
||||
.unwrap();
|
||||
let original_config = std::fs::read(instance.join("instance.json")).unwrap();
|
||||
let matches = crate::cli::build_command()
|
||||
.try_get_matches_from(["rmcl", "instance", "profile", "inst"])
|
||||
.unwrap();
|
||||
let profile_matches = matches
|
||||
.subcommand_matches("instance")
|
||||
.unwrap()
|
||||
.subcommand_matches("profile")
|
||||
.unwrap();
|
||||
super::profile_instance(profile_matches, &manager).unwrap();
|
||||
assert_eq!(
|
||||
std::fs::read(instance.join("instance.json")).unwrap(),
|
||||
original_config
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(minecraft.join("options.txt")).unwrap(),
|
||||
b"profile-options"
|
||||
);
|
||||
|
||||
let matches = crate::cli::build_command()
|
||||
.try_get_matches_from(["rmcl", "instance", "profile", "inst", target])
|
||||
.unwrap();
|
||||
let profile_matches = matches
|
||||
.subcommand_matches("instance")
|
||||
.unwrap()
|
||||
.subcommand_matches("profile")
|
||||
.unwrap();
|
||||
super::profile_instance(profile_matches, &manager).unwrap();
|
||||
if target == "other" {
|
||||
assert_eq!(
|
||||
manager
|
||||
.load_one("inst")
|
||||
.unwrap()
|
||||
.config_sync_profile
|
||||
.as_deref(),
|
||||
Some("other")
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(minecraft.join("options.txt")).unwrap(),
|
||||
b"other-options"
|
||||
);
|
||||
let matches = crate::cli::build_command()
|
||||
.try_get_matches_from(["rmcl", "instance", "profile", "inst", "default"])
|
||||
.unwrap();
|
||||
let profile_matches = matches
|
||||
.subcommand_matches("instance")
|
||||
.unwrap()
|
||||
.subcommand_matches("profile")
|
||||
.unwrap();
|
||||
super::profile_instance(profile_matches, &manager).unwrap();
|
||||
}
|
||||
assert_eq!(manager.load_one("inst").unwrap().config_sync_profile, None);
|
||||
assert_eq!(
|
||||
std::fs::read(minecraft.join("options.txt")).unwrap(),
|
||||
b"local-default"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(minecraft.join("config/value")).unwrap(),
|
||||
b"local-default"
|
||||
);
|
||||
assert!(
|
||||
!crate::storage::MetadataPaths::new(&manager.meta_dir)
|
||||
.profiles()
|
||||
.join("main")
|
||||
.exists()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,29 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
#[test]
|
||||
fn following_log_bytes_keeps_partial_lines_and_handles_truncation() {
|
||||
use super::read_new_log_bytes;
|
||||
use std::io::Write;
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("latest.log");
|
||||
std::fs::write(&path, b"abc").unwrap();
|
||||
let mut offset = 0;
|
||||
assert_eq!(read_new_log_bytes(&path, &mut offset).unwrap(), b"abc");
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.open(&path)
|
||||
.unwrap();
|
||||
file.write_all(b"def\nnext\n").unwrap();
|
||||
assert_eq!(
|
||||
read_new_log_bytes(&path, &mut offset).unwrap(),
|
||||
b"def\nnext\n"
|
||||
);
|
||||
assert!(read_new_log_bytes(&path, &mut offset).unwrap().is_empty());
|
||||
std::fs::write(&path, b"new\n").unwrap();
|
||||
assert_eq!(read_new_log_bytes(&path, &mut offset).unwrap(), b"new\n");
|
||||
}
|
||||
|
||||
use super::resolve_log_path;
|
||||
|
||||
#[test]
|
||||
@@ -32,3 +55,21 @@ fn resolves_named_log_file() {
|
||||
Some("latest.log")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_log_paths_outside_the_instance() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("demo/minecraft/logs/launches");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let outside = tmp.path().join("outside.txt");
|
||||
std::fs::write(&outside, "private").unwrap();
|
||||
|
||||
assert!(resolve_log_path(tmp.path(), "demo", Some(outside.to_str().unwrap())).is_err());
|
||||
assert!(resolve_log_path(tmp.path(), "demo", Some("../../outside.txt")).is_err());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(&outside, dir.join("escape.log")).unwrap();
|
||||
assert!(resolve_log_path(tmp.path(), "demo", Some("escape.log")).is_err());
|
||||
assert!(resolve_log_path(tmp.path(), "demo", None).is_err());
|
||||
}
|
||||
}
|
||||
@@ -44,3 +44,19 @@ fn formats_datetime_consistently() {
|
||||
let dt = Utc.with_ymd_and_hms(2024, 1, 2, 3, 4, 5).unwrap();
|
||||
assert_eq!(format_datetime(&dt), "2024-01-02 03:04:05 UTC");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_padding_uses_cells_for_wide_and_combining_names() {
|
||||
let table = render_table(
|
||||
&["Name", "State"],
|
||||
&[
|
||||
vec!["界界界".to_owned(), "first".to_owned()],
|
||||
vec!["e\u{301}".to_owned(), "second".to_owned()],
|
||||
],
|
||||
);
|
||||
let rows = table.lines().skip(2).collect::<Vec<_>>();
|
||||
for row in rows {
|
||||
let start = row.find(['f', 's']).unwrap();
|
||||
assert_eq!(ratatui::text::Span::raw(&row[..start]).width(), 8);
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -1,7 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// shared CLI helpers: confirmation prompts, arg extraction, instance validation
|
||||
use std::io::{self, Write};
|
||||
|
||||
use clap::ArgMatches;
|
||||
@@ -21,9 +20,9 @@ pub fn required_arg<'a>(matches: &'a ArgMatches, name: &str) -> Result<&'a str,
|
||||
.ok_or_else(|| io::Error::other(format!("missing required argument '{name}'")))
|
||||
}
|
||||
|
||||
// checks for instance.json rather than just the directory, since a folder
|
||||
// without config is just a sad empty directory pretending to be an instance
|
||||
// A directory without instance.json is not an instance.
|
||||
pub fn require_instance(instances_dir: &std::path::Path, name: &str) -> Result<(), io::Error> {
|
||||
crate::instance::manager::validate_name(name).map_err(io::Error::other)?;
|
||||
if !instances_dir.join(name).join("instance.json").exists() {
|
||||
return Err(io::Error::other(format!("Instance '{name}' not found")));
|
||||
}
|
||||
|
||||
+6
-26
@@ -1,9 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// lists available game versions, optionally filtered by mod loader support.
|
||||
// fetches the mojang manifest and cross-references with loader APIs
|
||||
// to show only versions that actually work with a given loader.
|
||||
use std::collections::HashSet;
|
||||
use std::io;
|
||||
|
||||
@@ -53,29 +50,12 @@ async fn fetch_supported_versions(
|
||||
client: &HttpClient,
|
||||
loader: ModLoader,
|
||||
) -> Result<HashSet<String>, Box<dyn std::error::Error>> {
|
||||
let versions: HashSet<String> = match loader {
|
||||
ModLoader::Vanilla => HashSet::new(),
|
||||
ModLoader::Fabric => crate::net::fabric::fetch_fabric_game_versions(client)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|version| version.id)
|
||||
.collect::<HashSet<_>>(),
|
||||
ModLoader::Forge => crate::net::forge::fetch_forge_game_versions(client)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|version| version.id)
|
||||
.collect::<HashSet<_>>(),
|
||||
ModLoader::NeoForge => crate::net::neoforge::fetch_neoforge_game_versions(client)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|version| version.id)
|
||||
.collect::<HashSet<_>>(),
|
||||
ModLoader::Quilt => crate::net::quilt::fetch_quilt_game_versions(client)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|version| version.id)
|
||||
.collect::<HashSet<_>>(),
|
||||
};
|
||||
let versions = crate::instance::loader::get_installer(loader)
|
||||
.get_game_versions(client)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|version| version.id)
|
||||
.collect();
|
||||
|
||||
Ok(versions)
|
||||
}
|
||||
|
||||
+9
-6
@@ -1,9 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// config loading: reads config.toml from the platform config dir, creates defaults if missing.
|
||||
// everything lands in the SETTINGS static so the rest of the app can just grab it.
|
||||
|
||||
use config::{Config as ConfigLoader, ConfigError, File};
|
||||
use std::fs;
|
||||
use std::io;
|
||||
@@ -17,12 +14,11 @@ pub use settings::Config;
|
||||
|
||||
#[must_use]
|
||||
pub fn get_config_path() -> PathBuf {
|
||||
dirs_next::config_dir()
|
||||
dirs::config_dir()
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
.join("rmcl")
|
||||
}
|
||||
|
||||
// seeds the config file from the bundled default on first run
|
||||
fn ensure_config_exists() -> PathBuf {
|
||||
let config_path = get_config_path().join("config.toml");
|
||||
if !config_path.exists() {
|
||||
@@ -90,7 +86,7 @@ pub(crate) fn upgrade_config_file(path: &std::path::Path) -> io::Result<bool> {
|
||||
}
|
||||
|
||||
pub(crate) fn migrate_legacy_data_paths(path: &std::path::Path) -> io::Result<bool> {
|
||||
let Some(data_dir) = dirs_next::data_dir() else {
|
||||
let Some(data_dir) = dirs::data_dir() else {
|
||||
return Ok(false);
|
||||
};
|
||||
migrate_legacy_data_paths_from(path, &data_dir)
|
||||
@@ -255,6 +251,13 @@ pub static SETTINGS: LazyLock<ConfigStore> = LazyLock::new(|| {
|
||||
|
||||
fn write_config_document(path: &std::path::Path, config: &Config) -> io::Result<()> {
|
||||
write_merged_toml_document(path, config, |document| {
|
||||
if let Some(environment) = document
|
||||
.get_mut("defaults")
|
||||
.and_then(|defaults| defaults.get_mut("environment"))
|
||||
.and_then(toml_edit::Item::as_table_mut)
|
||||
{
|
||||
environment.retain(|key, _| config.defaults.environment.contains_key(key));
|
||||
}
|
||||
if config.paths.java_path.is_none()
|
||||
&& let Some(paths) = document
|
||||
.get_mut("paths")
|
||||
|
||||
+73
-11
@@ -1,9 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// all the config structs that map to sections in config.toml.
|
||||
// everything has sane defaults so a blank file (or no file) still works.
|
||||
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
fmt,
|
||||
@@ -215,7 +212,7 @@ pub struct Paths {
|
||||
}
|
||||
|
||||
fn default_instances_dir() -> String {
|
||||
dirs_next::data_dir()
|
||||
dirs::data_dir()
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
.join("rmcl")
|
||||
.join("instances")
|
||||
@@ -228,7 +225,7 @@ fn is_default_instances_dir(path: &str) -> bool {
|
||||
}
|
||||
|
||||
fn default_meta_dir() -> String {
|
||||
dirs_next::data_dir()
|
||||
dirs::data_dir()
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
.join("rmcl")
|
||||
.join("meta")
|
||||
@@ -250,14 +247,13 @@ impl Default for Paths {
|
||||
}
|
||||
}
|
||||
|
||||
// expand ~ in paths since toml doesn't do that for us
|
||||
pub fn resolve_path(raw: &str) -> PathBuf {
|
||||
if let Some(stripped) = raw.strip_prefix("~/") {
|
||||
if let Some(home) = dirs_next::home_dir() {
|
||||
if let Some(stripped) = raw.strip_prefix("~/").or_else(|| raw.strip_prefix("~\\")) {
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
return home.join(stripped);
|
||||
}
|
||||
} else if raw == "~"
|
||||
&& let Some(home) = dirs_next::home_dir()
|
||||
&& let Some(home) = dirs::home_dir()
|
||||
{
|
||||
return home;
|
||||
}
|
||||
@@ -319,9 +315,75 @@ impl Default for Defaults {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse_tag_values(input: &str) -> Result<Vec<String>, String> {
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Quote {
|
||||
None,
|
||||
Single,
|
||||
Double,
|
||||
}
|
||||
|
||||
let mut values = Vec::new();
|
||||
let mut current = String::new();
|
||||
let mut quote = Quote::None;
|
||||
let mut started = false;
|
||||
let mut characters = input.chars().peekable();
|
||||
while let Some(character) = characters.next() {
|
||||
match (quote, character) {
|
||||
(Quote::None, character) if character.is_whitespace() => {
|
||||
if started {
|
||||
values.push(std::mem::take(&mut current));
|
||||
started = false;
|
||||
}
|
||||
}
|
||||
(Quote::None, '\'') => {
|
||||
quote = Quote::Single;
|
||||
started = true;
|
||||
}
|
||||
(Quote::None, '"') => {
|
||||
quote = Quote::Double;
|
||||
started = true;
|
||||
}
|
||||
(Quote::Single, '\'') => quote = Quote::None,
|
||||
(Quote::Double, '"') => quote = Quote::None,
|
||||
(Quote::Double, '\\') if matches!(characters.peek(), Some('"' | '\\')) => {
|
||||
current.push(characters.next().unwrap_or_default());
|
||||
started = true;
|
||||
}
|
||||
(_, character) => {
|
||||
current.push(character);
|
||||
started = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if quote != Quote::None {
|
||||
return Err("Quoted value is missing its closing quote.".to_owned());
|
||||
}
|
||||
if started {
|
||||
values.push(current);
|
||||
}
|
||||
Ok(values)
|
||||
}
|
||||
|
||||
pub(crate) fn format_tag_values(values: &[String]) -> String {
|
||||
values
|
||||
.iter()
|
||||
.map(|value| {
|
||||
if !value.is_empty()
|
||||
&& !value
|
||||
.chars()
|
||||
.any(|character| character.is_whitespace() || matches!(character, '\'' | '"'))
|
||||
{
|
||||
value.clone()
|
||||
} else {
|
||||
format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
// timing knobs for the error toast animation: show for 5s, start sliding at 3.5s,
|
||||
// fly off screen over 300ms. tweak these if the toasts feel too fast or slow.
|
||||
pub struct Ui {
|
||||
#[serde(default)]
|
||||
pub image_protocol: ImageProtocol,
|
||||
|
||||
@@ -3,6 +3,28 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn saving_settings_removes_deleted_environment_keys_and_keeps_retained_comments() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("config.toml");
|
||||
std::fs::write(
|
||||
&path,
|
||||
"[defaults.environment]\nKEEP = 'old' # retained\nREMOVE = 'gone'\n[unknown]\nvalue = 1\n",
|
||||
)
|
||||
.unwrap();
|
||||
let mut config = Config::default();
|
||||
config
|
||||
.defaults
|
||||
.environment
|
||||
.insert("KEEP".to_owned(), "new".to_owned());
|
||||
write_config_document(&path, &config).unwrap();
|
||||
let source = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(!source.contains("REMOVE"));
|
||||
assert!(source.contains("# retained"));
|
||||
assert!(source.contains("[unknown]"));
|
||||
assert_eq!(load_config(&path).unwrap().defaults.environment.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_config_from_valid_toml() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -73,6 +73,26 @@ fn content_provider_settings_are_normalized() {
|
||||
assert_eq!(unknown.preferred_provider, ContentProvider::Modrinth);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovery_provider_only_disables_the_other_provider() {
|
||||
for preferred_provider in [ContentProvider::Modrinth, ContentProvider::CurseForge] {
|
||||
let mut content = Content {
|
||||
preferred_provider,
|
||||
preferred_provider_only: true,
|
||||
..Content::default()
|
||||
};
|
||||
for provider in ["modrinth", "curseforge"] {
|
||||
assert_eq!(
|
||||
content.discovery_provider_enabled_with_curseforge(provider, true),
|
||||
provider == content.preferred_provider_with_curseforge(true)
|
||||
);
|
||||
}
|
||||
content.preferred_provider_only = false;
|
||||
assert!(content.discovery_provider_enabled_with_curseforge("modrinth", true));
|
||||
assert!(content.discovery_provider_enabled_with_curseforge("curseforge", true));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_path_absolute() {
|
||||
assert_eq!(resolve_path("/opt/rmcl"), PathBuf::from("/opt/rmcl"));
|
||||
@@ -80,15 +100,18 @@ fn resolve_path_absolute() {
|
||||
|
||||
#[test]
|
||||
fn resolve_path_tilde_prefix() {
|
||||
let resolved = resolve_path("~/games/rmcl");
|
||||
assert!(!resolved.to_string_lossy().starts_with('~'));
|
||||
assert!(resolved.to_string_lossy().ends_with("games/rmcl"));
|
||||
let home = dirs::home_dir().expect("test environment has a home directory");
|
||||
for path in ["~/games/rmcl", r"~\games/rmcl"] {
|
||||
assert_eq!(resolve_path(path), home.join("games/rmcl"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_path_bare_tilde() {
|
||||
let resolved = resolve_path("~");
|
||||
assert!(!resolved.to_string_lossy().starts_with('~'));
|
||||
assert_eq!(
|
||||
resolve_path("~"),
|
||||
dirs::home_dir().expect("test environment has a home directory")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
// cover every BorderStyle variant. a mutation that swaps two arms of the
|
||||
// match (e.g. Rounded -> Plain) would slip past testing just one variant.
|
||||
#[rstest::rstest]
|
||||
#[case::plain(BorderStyle::Plain, BorderType::Plain)]
|
||||
#[case::rounded(BorderStyle::Rounded, BorderType::Rounded)]
|
||||
@@ -51,13 +49,43 @@ fn resolve_with_overrides_keeps_base() {
|
||||
}),
|
||||
..ThemeConfig::default()
|
||||
};
|
||||
let theme = resolve_app_theme(&config);
|
||||
assert_eq!(theme.accent(), Color::Red);
|
||||
let theme = resolve_app_theme(&config).unwrap();
|
||||
assert_eq!(
|
||||
theme.accent(),
|
||||
if ratatui_themekit::no_color_active() {
|
||||
resolve_theme("dracula").accent()
|
||||
} else {
|
||||
Color::Red
|
||||
}
|
||||
);
|
||||
let base = resolve_theme("dracula");
|
||||
assert_eq!(theme.text(), base.text());
|
||||
assert_eq!(theme.error(), base.error());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_and_invalid_custom_themes_are_errors() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("theme.toml");
|
||||
let config = ThemeConfig {
|
||||
theme: path.to_string_lossy().into_owned(),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(resolve_app_theme(&config).is_err());
|
||||
std::fs::write(&path, "bad theme").unwrap();
|
||||
assert!(resolve_app_theme(&config).is_err());
|
||||
std::fs::write(&path, include_str!("../../../assets/example-theme.toml")).unwrap();
|
||||
let theme = resolve_app_theme(&config).unwrap();
|
||||
assert_eq!(
|
||||
theme.id(),
|
||||
if ratatui_themekit::no_color_active() {
|
||||
"no-color"
|
||||
} else {
|
||||
"my-theme"
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_builtin_theme() {
|
||||
let theme = resolve_theme("dracula");
|
||||
@@ -83,7 +111,6 @@ fn custom_theme_file_parses() {
|
||||
toml::from_str::<CustomTheme>("name = \"X\"\nid = \"x\"\naccent = \"#f97316\"\n").unwrap();
|
||||
assert_eq!(minimal.accent, Color::Rgb(249, 115, 22));
|
||||
|
||||
// the two failure modes users hit: nesting under [theme], or omitting name/id
|
||||
assert!(
|
||||
toml::from_str::<CustomTheme>("[theme]\nname = \"X\"\nid = \"x\"\naccent = \"Red\"\n")
|
||||
.is_err()
|
||||
|
||||
+47
-61
@@ -1,10 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// theme resolution: loads theme.toml, picks a base theme (builtin or custom file),
|
||||
// then layers user color overrides on top. supports loading .toml themes from the
|
||||
// config/theme/ directory or by absolute path.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, LazyLock, RwLock};
|
||||
|
||||
@@ -77,6 +73,7 @@ impl Default for ThemeConfig {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(test))]
|
||||
fn load_theme_config() -> ThemeConfig {
|
||||
let path = super::get_config_path().join("theme.toml");
|
||||
ensure_theme_exists(&path);
|
||||
@@ -89,6 +86,7 @@ fn load_theme_config() -> ThemeConfig {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(test))]
|
||||
fn ensure_theme_exists(path: &Path) {
|
||||
if path.exists() {
|
||||
return;
|
||||
@@ -99,15 +97,17 @@ fn ensure_theme_exists(path: &Path) {
|
||||
let _ = std::fs::write(path, include_str!("../../assets/theme.toml"));
|
||||
}
|
||||
|
||||
// start from a base theme, then override individual colors if the user specified any
|
||||
fn resolve_app_theme(config: &ThemeConfig) -> Box<dyn Theme> {
|
||||
let base = load_base_theme(&config.theme);
|
||||
fn resolve_app_theme(config: &ThemeConfig) -> std::io::Result<Box<dyn Theme>> {
|
||||
let base = load_base_theme(&config.theme)?;
|
||||
if ratatui_themekit::no_color_active() {
|
||||
return Ok(resolve_theme("catppuccin"));
|
||||
}
|
||||
|
||||
let Some(overrides) = &config.custom else {
|
||||
return base;
|
||||
return Ok(base);
|
||||
};
|
||||
|
||||
Box::new(CustomTheme {
|
||||
Ok(Box::new(CustomTheme {
|
||||
name: format!("{} (customized)", base.name()),
|
||||
id: base.id().to_owned(),
|
||||
accent: overrides.accent.unwrap_or_else(|| base.accent()),
|
||||
@@ -129,11 +129,10 @@ fn resolve_app_theme(config: &ThemeConfig) -> Box<dyn Theme> {
|
||||
border: overrides.border.unwrap_or_else(|| base.border()),
|
||||
surface: overrides.surface.unwrap_or_else(|| base.surface()),
|
||||
background: overrides.background.unwrap_or_else(|| base.background()),
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
// tries to find the theme: absolute path > config/theme/<name> > config/theme/<name>.toml > builtin
|
||||
fn load_base_theme(name: &str) -> Box<dyn Theme> {
|
||||
fn load_base_theme(name: &str) -> std::io::Result<Box<dyn Theme>> {
|
||||
let path = if Path::new(name).is_absolute() {
|
||||
Some(std::path::PathBuf::from(name))
|
||||
} else {
|
||||
@@ -151,20 +150,27 @@ fn load_base_theme(name: &str) -> Box<dyn Theme> {
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(path) = path
|
||||
&& let Ok(content) = std::fs::read_to_string(&path)
|
||||
{
|
||||
match toml::from_str::<CustomTheme>(&content) {
|
||||
Ok(custom) => return Box::new(custom),
|
||||
Err(e) => tracing::warn!(
|
||||
"Failed to parse theme file {}: {e}. Theme files need top-level \
|
||||
name, id and accent keys (not nested under [theme]).",
|
||||
path.display()
|
||||
),
|
||||
}
|
||||
if path.is_none() && ratatui_themekit::available_theme_ids().contains(&name) {
|
||||
return Ok(resolve_theme(name));
|
||||
}
|
||||
|
||||
resolve_theme(name)
|
||||
let path = path.unwrap_or_else(|| {
|
||||
super::get_config_path()
|
||||
.join("theme")
|
||||
.join(format!("{name}.toml"))
|
||||
});
|
||||
let content = std::fs::read_to_string(&path).map_err(|error| {
|
||||
std::io::Error::new(
|
||||
error.kind(),
|
||||
format!("failed to load theme {}: {error}", path.display()),
|
||||
)
|
||||
})?;
|
||||
let custom = toml::from_str::<CustomTheme>(&content).map_err(|error| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
format!("invalid theme {}: {error}", path.display()),
|
||||
)
|
||||
})?;
|
||||
Ok(Box::new(custom))
|
||||
}
|
||||
|
||||
pub struct ThemeStore(RwLock<Arc<dyn Theme>>);
|
||||
@@ -207,14 +213,23 @@ impl BorderStyleStore {
|
||||
}
|
||||
}
|
||||
|
||||
static THEME_CONFIG: LazyLock<RwLock<ThemeConfig>> =
|
||||
LazyLock::new(|| RwLock::new(load_theme_config()));
|
||||
static THEME_CONFIG: LazyLock<RwLock<ThemeConfig>> = LazyLock::new(|| {
|
||||
#[cfg(test)]
|
||||
let config = ThemeConfig::default();
|
||||
#[cfg(not(test))]
|
||||
let config = load_theme_config();
|
||||
RwLock::new(config)
|
||||
});
|
||||
|
||||
pub static THEME: LazyLock<ThemeStore> = LazyLock::new(|| {
|
||||
let config = THEME_CONFIG
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
ThemeStore(RwLock::new(Arc::from(resolve_app_theme(&config))))
|
||||
let theme = resolve_app_theme(&config).unwrap_or_else(|error| {
|
||||
tracing::error!("Could not load theme: {error}");
|
||||
resolve_theme("catppuccin")
|
||||
});
|
||||
ThemeStore(RwLock::new(Arc::from(theme)))
|
||||
});
|
||||
|
||||
pub static BORDER_STYLE: LazyLock<BorderStyleStore> = LazyLock::new(|| {
|
||||
@@ -232,10 +247,10 @@ pub fn current_theme_config() -> ThemeConfig {
|
||||
}
|
||||
|
||||
pub fn apply_theme(theme: String, border_style: BorderStyle) -> std::io::Result<()> {
|
||||
validate_theme_name(&theme)?;
|
||||
let mut config = current_theme_config();
|
||||
config.theme = theme;
|
||||
config.border_style = border_style.clone();
|
||||
let resolved = resolve_app_theme(&config)?;
|
||||
super::write_merged_toml_document(
|
||||
&super::get_config_path().join("theme.toml"),
|
||||
&config,
|
||||
@@ -245,7 +260,7 @@ pub fn apply_theme(theme: String, border_style: BorderStyle) -> std::io::Result<
|
||||
}
|
||||
},
|
||||
)?;
|
||||
THEME.set(resolve_app_theme(&config));
|
||||
THEME.set(resolved);
|
||||
BORDER_STYLE.set(border_style);
|
||||
*THEME_CONFIG
|
||||
.write()
|
||||
@@ -254,42 +269,13 @@ pub fn apply_theme(theme: String, border_style: BorderStyle) -> std::io::Result<
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_theme_name(name: &str) -> std::io::Result<()> {
|
||||
if ratatui_themekit::available_theme_ids().contains(&name) {
|
||||
return Ok(());
|
||||
}
|
||||
let path = if Path::new(name).is_absolute() {
|
||||
std::path::PathBuf::from(name)
|
||||
} else {
|
||||
let directory = super::get_config_path().join("theme");
|
||||
let direct = directory.join(name);
|
||||
if direct.exists() {
|
||||
direct
|
||||
} else {
|
||||
directory.join(format!("{name}.toml"))
|
||||
}
|
||||
};
|
||||
let content = std::fs::read_to_string(&path).map_err(|error| {
|
||||
std::io::Error::new(
|
||||
error.kind(),
|
||||
format!("failed to load theme {}: {error}", path.display()),
|
||||
)
|
||||
})?;
|
||||
toml::from_str::<CustomTheme>(&content).map_err(|error| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
format!("invalid theme {}: {error}", path.display()),
|
||||
)
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn reload_theme() -> std::io::Result<()> {
|
||||
let path = super::get_config_path().join("theme.toml");
|
||||
let content = std::fs::read_to_string(path)?;
|
||||
let config: ThemeConfig = toml::from_str(&content)
|
||||
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
|
||||
THEME.set(resolve_app_theme(&config));
|
||||
let resolved = resolve_app_theme(&config)?;
|
||||
THEME.set(resolved);
|
||||
BORDER_STYLE.set(config.border_style.clone());
|
||||
*THEME_CONFIG
|
||||
.write()
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// thread-safe FIFO queue for error/warning toasts displayed in the UI.
|
||||
// also (ab)used for INFO toasts like "desktop shortcut created" because
|
||||
// why build a separate notification system when this one works fine.
|
||||
//
|
||||
// callers pass id: 0 and push_error assigns a real unique id. the id is
|
||||
// used by the render layer to track per-toast animation state.
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// application feedback shared by background work and every frontend.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
pub mod errors;
|
||||
|
||||
+34
-27
@@ -1,9 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// global progress state shared between background tasks and the status bar widget.
|
||||
// background tasks set the action/progress, the render loop reads it every frame.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
@@ -15,7 +12,7 @@ pub struct ProgressState {
|
||||
pub progress: Option<(u64, u64)>,
|
||||
pub sub_action: Option<String>,
|
||||
tasks: BTreeMap<u64, TaskState>,
|
||||
legacy_active: bool,
|
||||
legacy: Option<TaskState>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -31,7 +28,6 @@ static NEXT_TASK_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
pub struct ProgressTask {
|
||||
id: u64,
|
||||
finished: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -56,10 +52,7 @@ impl ProgressTask {
|
||||
}
|
||||
tracing::info!("{}", action);
|
||||
super::request_redraw();
|
||||
Self {
|
||||
id,
|
||||
finished: false,
|
||||
}
|
||||
Self { id }
|
||||
}
|
||||
|
||||
pub fn handle(&self) -> ProgressTaskHandle {
|
||||
@@ -78,15 +71,13 @@ impl ProgressTask {
|
||||
update_task_progress(self.id, current, total);
|
||||
}
|
||||
|
||||
pub fn finish(mut self) {
|
||||
self.remove();
|
||||
self.finished = true;
|
||||
pub fn finish(self) {
|
||||
drop(self);
|
||||
}
|
||||
|
||||
pub fn fail(mut self, error: impl std::fmt::Display) {
|
||||
tracing::warn!("Progress task failed: {error}");
|
||||
self.remove();
|
||||
self.finished = true;
|
||||
pub fn fail(self, error: impl std::fmt::Display) {
|
||||
tracing::debug!("Progress task failed: {error}");
|
||||
drop(self);
|
||||
}
|
||||
|
||||
fn remove(&self) {
|
||||
@@ -141,18 +132,21 @@ fn update_task_progress(id: u64, current: u64, total: u64) {
|
||||
|
||||
impl Drop for ProgressTask {
|
||||
fn drop(&mut self) {
|
||||
if !self.finished {
|
||||
self.remove();
|
||||
}
|
||||
self.remove();
|
||||
}
|
||||
}
|
||||
|
||||
fn refresh_visible(state: &mut ProgressState) {
|
||||
if let Some((_, task)) = state.tasks.last_key_value() {
|
||||
if let Some(task) = state
|
||||
.tasks
|
||||
.last_key_value()
|
||||
.map(|(_, task)| task)
|
||||
.or(state.legacy.as_ref())
|
||||
{
|
||||
state.current_action = Some(task.action.clone());
|
||||
state.sub_action.clone_from(&task.sub_action);
|
||||
state.progress = task.progress;
|
||||
} else if !state.legacy_active {
|
||||
} else {
|
||||
state.current_action = None;
|
||||
state.sub_action = None;
|
||||
state.progress = None;
|
||||
@@ -163,9 +157,16 @@ pub fn set_action(text: impl Into<String>) {
|
||||
let text = text.into();
|
||||
match PROGRESS.lock() {
|
||||
Ok(mut state) => {
|
||||
state.legacy_active = true;
|
||||
state.current_action = Some(text.clone());
|
||||
state.progress = None;
|
||||
let sub_action = state
|
||||
.legacy
|
||||
.as_ref()
|
||||
.and_then(|task| task.sub_action.clone());
|
||||
state.legacy = Some(TaskState {
|
||||
action: text.clone(),
|
||||
sub_action,
|
||||
progress: None,
|
||||
});
|
||||
refresh_visible(&mut state);
|
||||
super::request_redraw();
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -178,7 +179,10 @@ pub fn set_action(text: impl Into<String>) {
|
||||
pub fn set_progress(current: u64, total: u64) {
|
||||
match PROGRESS.lock() {
|
||||
Ok(mut state) => {
|
||||
state.progress = Some((current, total));
|
||||
if let Some(task) = state.legacy.as_mut() {
|
||||
task.progress = Some((current, total));
|
||||
}
|
||||
refresh_visible(&mut state);
|
||||
super::request_redraw();
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -191,7 +195,10 @@ pub fn set_sub_action(text: impl Into<String>) {
|
||||
let text = text.into();
|
||||
match PROGRESS.lock() {
|
||||
Ok(mut state) => {
|
||||
state.sub_action = Some(text.clone());
|
||||
if let Some(task) = state.legacy.as_mut() {
|
||||
task.sub_action = Some(text.clone());
|
||||
}
|
||||
refresh_visible(&mut state);
|
||||
super::request_redraw();
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -204,7 +211,7 @@ pub fn set_sub_action(text: impl Into<String>) {
|
||||
pub fn clear() {
|
||||
match PROGRESS.lock() {
|
||||
Ok(mut state) => {
|
||||
state.legacy_active = false;
|
||||
state.legacy = None;
|
||||
refresh_visible(&mut state);
|
||||
super::request_redraw();
|
||||
}
|
||||
|
||||
@@ -59,6 +59,28 @@ fn clearing_legacy_progress_keeps_owned_tasks() {
|
||||
clear();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owned_tasks_restore_legacy_progress_and_legacy_updates_do_not_cover_them() {
|
||||
let _guard = TEST_LOCK.lock().unwrap();
|
||||
clear();
|
||||
set_action("legacy");
|
||||
set_sub_action("download");
|
||||
set_progress(1, 3);
|
||||
let task = ProgressTask::start("owned");
|
||||
set_progress(2, 3);
|
||||
assert_eq!(
|
||||
PROGRESS.lock().unwrap().current_action.as_deref(),
|
||||
Some("owned")
|
||||
);
|
||||
task.finish();
|
||||
let state = PROGRESS.lock().unwrap();
|
||||
assert_eq!(state.current_action.as_deref(), Some("legacy"));
|
||||
assert_eq!(state.sub_action.as_deref(), Some("download"));
|
||||
assert_eq!(state.progress, Some((2, 3)));
|
||||
drop(state);
|
||||
clear();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_legacy_action_does_not_reuse_the_previous_phase_progress() {
|
||||
let _guard = TEST_LOCK.lock().unwrap();
|
||||
|
||||
+696
-131
@@ -11,13 +11,36 @@ pub enum ConfigSyncError {
|
||||
InvalidProfile(String),
|
||||
#[error("Cannot switch config profiles while '{instance}' is running")]
|
||||
InstanceRunning { instance: String },
|
||||
#[error("Config profile '{0}' is in use by another instance")]
|
||||
ProfileInUse(String),
|
||||
#[error("Config profile '{}' and local settings '{}' have diverged; both were kept", profile.display(), minecraft.display())]
|
||||
Conflict {
|
||||
profile: PathBuf,
|
||||
minecraft: PathBuf,
|
||||
},
|
||||
#[error("IO error: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("Failed to save config profile: {0}")]
|
||||
Save(String),
|
||||
#[error("Config sync failed ({save}) and rollback failed ({rollback})")]
|
||||
SaveRollback { save: String, rollback: String },
|
||||
#[error(transparent)]
|
||||
Instance(#[from] crate::instance::InstanceError),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ConfigSyncLock {
|
||||
file: std::fs::File,
|
||||
profile_dir: PathBuf,
|
||||
recovered_source: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
struct PayloadBaseline {
|
||||
profile: PathBuf,
|
||||
// External relative links are re-anchored on import, so these hashes can differ.
|
||||
local: String,
|
||||
shared: String,
|
||||
}
|
||||
|
||||
impl Drop for ConfigSyncLock {
|
||||
@@ -33,24 +56,63 @@ pub fn prepare(
|
||||
meta_dir: &Path,
|
||||
minecraft_dir: &Path,
|
||||
) -> Result<bool, ConfigSyncError> {
|
||||
Ok(prepare_for_launch(profile, meta_dir, minecraft_dir)?.is_some())
|
||||
}
|
||||
|
||||
pub fn prepare_for_launch(
|
||||
profile: Option<&str>,
|
||||
meta_dir: &Path,
|
||||
minecraft_dir: &Path,
|
||||
) -> Result<Option<ConfigSyncLock>, ConfigSyncError> {
|
||||
let Some(profile) = profile.and_then(normalize_profile) else {
|
||||
return Ok(false);
|
||||
return Ok(None);
|
||||
};
|
||||
validate_profile(profile)?;
|
||||
|
||||
let profile_dir = profile_dir(meta_dir, profile);
|
||||
if !profile_dir.exists() {
|
||||
return Ok(false);
|
||||
if !profile_exists(&profile_dir)? {
|
||||
return Ok(None);
|
||||
}
|
||||
let _lock = acquire_lock(&profile_dir)?;
|
||||
let lock = acquire_lock(&profile_dir)?;
|
||||
prepare_locked(lock, minecraft_dir)
|
||||
}
|
||||
|
||||
if !profile_payload_exists(&profile_dir)? {
|
||||
sync_to_profile(minecraft_dir, &profile_dir)?;
|
||||
fn prepare_locked(
|
||||
lock: ConfigSyncLock,
|
||||
minecraft_dir: &Path,
|
||||
) -> Result<Option<ConfigSyncLock>, ConfigSyncError> {
|
||||
let profile_dir = &lock.profile_dir;
|
||||
if !profile_exists(profile_dir)? {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
if !profile_payload_exists(profile_dir)? {
|
||||
publish_current(minecraft_dir, profile_dir, false)?;
|
||||
persist_with_baseline(minecraft_dir, Some(profile_dir), || {
|
||||
mark_unsynced(profile_dir, minecraft_dir)
|
||||
})?;
|
||||
} else {
|
||||
sync_from_profile(&profile_dir, minecraft_dir)?;
|
||||
let identity = std::fs::canonicalize(profile_dir)?;
|
||||
if read_baseline(minecraft_dir)?.is_some_and(|baseline| baseline.profile == identity) {
|
||||
publish_current(minecraft_dir, profile_dir, false)?;
|
||||
}
|
||||
mirror_payload(profile_dir, minecraft_dir, true, || {
|
||||
persist_with_baseline(minecraft_dir, Some(profile_dir), || {
|
||||
mark_unsynced(profile_dir, minecraft_dir)
|
||||
})
|
||||
})?;
|
||||
}
|
||||
|
||||
Ok(true)
|
||||
Ok(Some(lock))
|
||||
}
|
||||
|
||||
pub fn finish_launch(lock: ConfigSyncLock, minecraft_dir: &Path) -> Result<(), ConfigSyncError> {
|
||||
let allow_untracked = match &lock.recovered_source {
|
||||
Some(source) => std::fs::canonicalize(source)? == std::fs::canonicalize(minecraft_dir)?,
|
||||
None => true,
|
||||
};
|
||||
publish_current(minecraft_dir, &lock.profile_dir, allow_untracked)?;
|
||||
remove_if_exists(&unsynced_marker(&lock.profile_dir))
|
||||
}
|
||||
|
||||
pub fn finish(
|
||||
@@ -64,14 +126,13 @@ pub fn finish(
|
||||
validate_profile(profile)?;
|
||||
|
||||
let profile_dir = profile_dir(meta_dir, profile);
|
||||
let _lock = acquire_lock(&profile_dir)?;
|
||||
sync_to_profile(minecraft_dir, &profile_dir)
|
||||
finish_launch(acquire_lock(&profile_dir)?, minecraft_dir)
|
||||
}
|
||||
|
||||
pub fn list_profiles(meta_dir: &Path) -> Result<Vec<String>, ConfigSyncError> {
|
||||
let root = profiles_dir(meta_dir);
|
||||
let mut profiles = Vec::new();
|
||||
if !root.exists() {
|
||||
if !entry_exists(&root)? {
|
||||
return Ok(profiles);
|
||||
}
|
||||
|
||||
@@ -93,6 +154,7 @@ pub fn create_profile(meta_dir: &Path, profile: &str) -> Result<String, ConfigSy
|
||||
return Err(ConfigSyncError::InvalidProfile(profile.to_string()));
|
||||
};
|
||||
validate_profile(profile)?;
|
||||
let _lock = acquire_lock(&profile_dir(meta_dir, profile))?;
|
||||
std::fs::create_dir_all(profile_dir(meta_dir, profile))?;
|
||||
Ok(profile.to_string())
|
||||
}
|
||||
@@ -100,76 +162,120 @@ pub fn create_profile(meta_dir: &Path, profile: &str) -> Result<String, ConfigSy
|
||||
pub fn delete_profile(meta_dir: &Path, profile: &str) -> Result<(), ConfigSyncError> {
|
||||
validate_profile(profile)?;
|
||||
let dir = profile_dir(meta_dir, profile);
|
||||
if dir.exists() {
|
||||
remove_path(&dir)?;
|
||||
if profile_exists(&dir)? {
|
||||
let _lock = acquire_lock(&dir)?;
|
||||
if profile_exists(&dir)? {
|
||||
remove_path(&dir)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn switch_profile(
|
||||
#[cfg(test)]
|
||||
fn switch_profile(
|
||||
instance_name: &str,
|
||||
current_profile: Option<&str>,
|
||||
target_profile: Option<&str>,
|
||||
meta_dir: &Path,
|
||||
instance_dir: &Path,
|
||||
) -> Result<Option<String>, ConfigSyncError> {
|
||||
switch_profile_and_persist(
|
||||
instance_name,
|
||||
current_profile,
|
||||
target_profile,
|
||||
meta_dir,
|
||||
instance_dir,
|
||||
|_| Ok::<(), std::io::Error>(()),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn switch_profile_and_save(
|
||||
manager: &crate::instance::InstanceManager,
|
||||
config: &mut crate::instance::InstanceConfig,
|
||||
target_profile: Option<&str>,
|
||||
) -> Result<(), ConfigSyncError> {
|
||||
let _instance_lock =
|
||||
crate::instance::runtime::lock_instance(&manager.instances_dir, &config.name)?;
|
||||
let current = manager.load_one(&config.name)?;
|
||||
let instance_dir = manager.instances_dir.join(¤t.name);
|
||||
let mut saved = None;
|
||||
switch_profile_and_persist(
|
||||
¤t.name,
|
||||
current.config_sync_profile.as_deref(),
|
||||
target_profile,
|
||||
&manager.meta_dir,
|
||||
&instance_dir,
|
||||
|selected| {
|
||||
saved =
|
||||
Some(manager.save_config_sync_profile(¤t.name, selected.map(str::to_owned))?);
|
||||
Ok::<(), crate::instance::InstanceError>(())
|
||||
},
|
||||
)?;
|
||||
*config = saved.expect("successful profile switch persisted its selection");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn switch_profile_and_persist<E>(
|
||||
instance_name: &str,
|
||||
current_profile: Option<&str>,
|
||||
target_profile: Option<&str>,
|
||||
meta_dir: &Path,
|
||||
instance_dir: &Path,
|
||||
persist: impl FnOnce(Option<&str>) -> Result<(), E>,
|
||||
) -> Result<Option<String>, ConfigSyncError>
|
||||
where
|
||||
E: std::fmt::Display,
|
||||
{
|
||||
if crate::instance::runtime::is_active(instance_name) {
|
||||
return Err(ConfigSyncError::InstanceRunning {
|
||||
instance: instance_name.to_string(),
|
||||
instance: instance_name.to_owned(),
|
||||
});
|
||||
}
|
||||
|
||||
let current_profile = current_profile.and_then(normalize_profile);
|
||||
let target_profile = target_profile.and_then(normalize_profile);
|
||||
if let Some(profile) = current_profile {
|
||||
let current = current_profile.and_then(normalize_profile);
|
||||
let target = target_profile.and_then(normalize_profile);
|
||||
for profile in [current, target].into_iter().flatten() {
|
||||
validate_profile(profile)?;
|
||||
profile_exists(&profile_dir(meta_dir, profile))?;
|
||||
}
|
||||
if let Some(profile) = target_profile {
|
||||
validate_profile(profile)?;
|
||||
let save =
|
||||
|selected| persist(selected).map_err(|error| ConfigSyncError::Save(error.to_string()));
|
||||
if current == target {
|
||||
save(current)?;
|
||||
return Ok(current.map(str::to_owned));
|
||||
}
|
||||
|
||||
if current_profile == target_profile {
|
||||
return Ok(current_profile.map(str::to_string));
|
||||
}
|
||||
|
||||
if let Some(profile) = current_profile {
|
||||
let profile_dir = profile_dir(meta_dir, profile);
|
||||
if profile_dir.exists() {
|
||||
let _lock = acquire_lock(&profile_dir)?;
|
||||
sync_to_profile(&minecraft_dir(instance_dir), &profile_dir)?;
|
||||
}
|
||||
}
|
||||
|
||||
match (current_profile, target_profile) {
|
||||
(None, Some(_)) => {
|
||||
sync_to_profile(
|
||||
&minecraft_dir(instance_dir),
|
||||
&local_backup_dir(instance_dir),
|
||||
)?;
|
||||
}
|
||||
(Some(_), None) => {
|
||||
let backup = local_backup_dir(instance_dir);
|
||||
if backup.exists() {
|
||||
sync_from_profile(&backup, &minecraft_dir(instance_dir))?;
|
||||
let minecraft = minecraft_dir(instance_dir);
|
||||
if let Some(profile) = current {
|
||||
let dir = profile_dir(meta_dir, profile);
|
||||
if profile_exists(&dir)? {
|
||||
let _lock = acquire_lock(&dir)?;
|
||||
if profile_exists(&dir)? {
|
||||
publish_current(&minecraft, &dir, false)?;
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
let Some(profile) = target_profile else {
|
||||
let local = local_backup_dir(instance_dir);
|
||||
if current.is_none() && target.is_some() {
|
||||
sync_to_profile(&minecraft, &local)?;
|
||||
}
|
||||
let Some(profile) = target else {
|
||||
if current.is_some() && entry_exists(&local)? {
|
||||
return mirror_payload(&local, &minecraft, true, || {
|
||||
persist_with_baseline(&minecraft, None, || save(None))?;
|
||||
Ok(None)
|
||||
});
|
||||
}
|
||||
persist_with_baseline(&minecraft, None, || save(None))?;
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let profile_dir = profile_dir(meta_dir, profile);
|
||||
let _lock = acquire_lock(&profile_dir)?;
|
||||
|
||||
if !profile_payload_exists(&profile_dir)? {
|
||||
sync_to_profile(&minecraft_dir(instance_dir), &profile_dir)?;
|
||||
let dir = profile_dir(meta_dir, profile);
|
||||
let _lock = acquire_lock(&dir)?;
|
||||
if !profile_payload_exists(&dir)? {
|
||||
sync_to_profile(&minecraft, &dir)?;
|
||||
}
|
||||
sync_from_profile(&profile_dir, &minecraft_dir(instance_dir))?;
|
||||
|
||||
Ok(Some(profile.to_string()))
|
||||
mirror_payload(&dir, &minecraft, true, || {
|
||||
persist_with_baseline(&minecraft, Some(&dir), || save(Some(profile)))?;
|
||||
Ok(Some(profile.to_owned()))
|
||||
})
|
||||
}
|
||||
|
||||
fn normalize_profile(profile: &str) -> Option<&str> {
|
||||
@@ -185,16 +291,12 @@ pub fn validate_profile(profile: &str) -> Result<(), ConfigSyncError> {
|
||||
if profile.is_empty()
|
||||
|| profile.len() > 64
|
||||
|| profile.starts_with('.')
|
||||
|| profile.contains('/')
|
||||
|| profile.contains('\\')
|
||||
|| !crate::instance::manager::portable_component(profile)
|
||||
|| profile.eq_ignore_ascii_case("default")
|
||||
|| profile.eq_ignore_ascii_case("none")
|
||||
|| profile.eq_ignore_ascii_case("local")
|
||||
|| profile.eq_ignore_ascii_case("instance default")
|
||||
|| profile.eq_ignore_ascii_case("local default")
|
||||
|| profile
|
||||
.chars()
|
||||
.any(|c| c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*'))
|
||||
{
|
||||
return Err(ConfigSyncError::InvalidProfile(profile.to_string()));
|
||||
}
|
||||
@@ -218,110 +320,492 @@ fn local_backup_dir(instance_dir: &Path) -> PathBuf {
|
||||
}
|
||||
|
||||
fn acquire_lock(profile_dir: &Path) -> Result<ConfigSyncLock, ConfigSyncError> {
|
||||
std::fs::create_dir_all(profile_dir)?;
|
||||
let path = profile_dir.join(".lock");
|
||||
let parent = profile_dir
|
||||
.parent()
|
||||
.ok_or_else(|| std::io::Error::other("Config profile has no parent"))?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
// Keep locks outside deletable profiles so recreating a profile cannot bypass an old handle.
|
||||
let path = parent.join(format!(
|
||||
".{}.lock",
|
||||
profile_dir
|
||||
.file_name()
|
||||
.unwrap_or_default()
|
||||
.to_string_lossy()
|
||||
));
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(path)?;
|
||||
file.lock()?;
|
||||
Ok(ConfigSyncLock { file })
|
||||
match file.try_lock() {
|
||||
Ok(()) => {}
|
||||
Err(std::fs::TryLockError::WouldBlock) => {
|
||||
return Err(ConfigSyncError::ProfileInUse(
|
||||
profile_dir
|
||||
.file_name()
|
||||
.unwrap_or_default()
|
||||
.to_string_lossy()
|
||||
.into_owned(),
|
||||
));
|
||||
}
|
||||
Err(std::fs::TryLockError::Error(error)) => return Err(error.into()),
|
||||
}
|
||||
let mut lock = ConfigSyncLock {
|
||||
file,
|
||||
profile_dir: profile_dir.to_owned(),
|
||||
recovered_source: None,
|
||||
};
|
||||
profile_exists(profile_dir)?;
|
||||
lock.recovered_source = recover_unsynced(profile_dir)?;
|
||||
Ok(lock)
|
||||
}
|
||||
|
||||
fn mirror_dir(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
|
||||
// stage the copy in a sibling temp dir and swap it in only when complete.
|
||||
// deleting dst up-front (the old behaviour) meant a failure mid-copy
|
||||
// destroyed the current config tree with nothing to fall back to.
|
||||
let parent = dst.parent().filter(|p| !p.as_os_str().is_empty());
|
||||
let Some(parent) = parent else {
|
||||
fn unsynced_marker(profile: &Path) -> PathBuf {
|
||||
profile.join(".unsynced.json")
|
||||
}
|
||||
|
||||
fn mark_unsynced(profile: &Path, minecraft: &Path) -> Result<(), ConfigSyncError> {
|
||||
let source = std::path::absolute(minecraft)?;
|
||||
if !std::fs::metadata(&source)?.is_dir() {
|
||||
return Err(std::io::Error::other("Config sync source is not a directory").into());
|
||||
}
|
||||
let bytes = serde_json::to_vec(&source).map_err(std::io::Error::other)?;
|
||||
crate::storage::write_atomic(&unsynced_marker(profile), &bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn recover_unsynced(profile: &Path) -> Result<Option<PathBuf>, ConfigSyncError> {
|
||||
let marker = unsynced_marker(profile);
|
||||
let bytes = match std::fs::read(&marker) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
let source: PathBuf = serde_json::from_slice(&bytes).map_err(|error| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
format!("Invalid config sync marker '{}': {error}", marker.display()),
|
||||
)
|
||||
})?;
|
||||
if !source.is_absolute() || !std::fs::metadata(&source)?.is_dir() {
|
||||
return Err(std::io::Error::other(format!(
|
||||
"Invalid unsynced config source '{}'",
|
||||
source.display()
|
||||
))
|
||||
.into());
|
||||
}
|
||||
publish_current(&source, profile, true)?;
|
||||
std::fs::remove_file(marker)?;
|
||||
Ok(Some(source))
|
||||
}
|
||||
|
||||
fn baseline_path(minecraft: &Path) -> Result<PathBuf, ConfigSyncError> {
|
||||
let instance = minecraft
|
||||
.parent()
|
||||
.ok_or_else(|| std::io::Error::other("Config sync source has no parent"))?;
|
||||
Ok(crate::storage::InstancePaths::new(instance)
|
||||
.state()
|
||||
.join("config-sync.json"))
|
||||
}
|
||||
|
||||
fn read_baseline(minecraft: &Path) -> Result<Option<PayloadBaseline>, ConfigSyncError> {
|
||||
let path = baseline_path(minecraft)?;
|
||||
match std::fs::read(&path) {
|
||||
Ok(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|error| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
format!("Invalid config sync baseline '{}': {error}", path.display()),
|
||||
)
|
||||
.into()
|
||||
}),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn baseline_bytes(
|
||||
profile: &Path,
|
||||
local: String,
|
||||
shared: String,
|
||||
) -> Result<Vec<u8>, ConfigSyncError> {
|
||||
let baseline = PayloadBaseline {
|
||||
profile: std::fs::canonicalize(profile)?,
|
||||
local,
|
||||
shared,
|
||||
};
|
||||
Ok(serde_json::to_vec(&baseline).map_err(std::io::Error::other)?)
|
||||
}
|
||||
|
||||
fn persist_with_baseline<T>(
|
||||
minecraft: &Path,
|
||||
profile: Option<&Path>,
|
||||
persist: impl FnOnce() -> Result<T, ConfigSyncError>,
|
||||
) -> Result<T, ConfigSyncError> {
|
||||
let path = baseline_path(minecraft)?;
|
||||
let previous = match std::fs::read(&path) {
|
||||
Ok(bytes) => Some(bytes),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
if let Some(profile) = profile {
|
||||
crate::storage::write_atomic(
|
||||
&path,
|
||||
&baseline_bytes(profile, payload_hash(minecraft)?, payload_hash(profile)?)?,
|
||||
)?;
|
||||
} else {
|
||||
remove_if_exists(&path)?;
|
||||
}
|
||||
match persist() {
|
||||
Ok(value) => Ok(value),
|
||||
Err(error) => {
|
||||
let rollback = match previous {
|
||||
Some(bytes) => {
|
||||
crate::storage::write_atomic(&path, &bytes).map_err(ConfigSyncError::from)
|
||||
}
|
||||
None => remove_if_exists(&path),
|
||||
};
|
||||
match rollback {
|
||||
Ok(()) => Err(error),
|
||||
Err(rollback) => Err(ConfigSyncError::SaveRollback {
|
||||
save: error.to_string(),
|
||||
rollback: format!("Restoring baseline '{}': {rollback}", path.display()),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_current(
|
||||
minecraft: &Path,
|
||||
profile: &Path,
|
||||
allow_untracked: bool,
|
||||
) -> Result<(), ConfigSyncError> {
|
||||
let local = payload_hash(minecraft)?;
|
||||
let shared = payload_hash(profile)?;
|
||||
let identity = std::fs::canonicalize(profile)?;
|
||||
let baseline = read_baseline(minecraft)?.filter(|baseline| baseline.profile == identity);
|
||||
let needs_export = local != shared;
|
||||
if needs_export {
|
||||
match baseline {
|
||||
Some(baseline) if local == baseline.local => return Ok(()),
|
||||
Some(baseline) if shared == baseline.shared => {}
|
||||
None if allow_untracked || !profile_payload_exists(profile)? => {}
|
||||
_ => {
|
||||
return Err(ConfigSyncError::Conflict {
|
||||
profile: profile.to_owned(),
|
||||
minecraft: minecraft.to_owned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let persist = |shared| {
|
||||
crate::storage::write_atomic(
|
||||
&baseline_path(minecraft)?,
|
||||
&baseline_bytes(profile, local, shared)?,
|
||||
)?;
|
||||
Ok(())
|
||||
};
|
||||
if needs_export {
|
||||
mirror_payload(minecraft, profile, true, || persist(payload_hash(profile)?))
|
||||
} else {
|
||||
persist(shared)
|
||||
}
|
||||
}
|
||||
|
||||
fn payload_hash(dir: &Path) -> Result<String, ConfigSyncError> {
|
||||
use sha2::Digest;
|
||||
require_source_dir(dir)?;
|
||||
check_config_root(dir)?;
|
||||
let mut hash = sha2::Sha256::new();
|
||||
for name in payload_names(dir, true)? {
|
||||
hash_payload_entry(&dir.join(name), dir, &mut hash)?;
|
||||
}
|
||||
Ok(format!("{:x}", hash.finalize()))
|
||||
}
|
||||
|
||||
fn hash_payload_entry(
|
||||
path: &Path,
|
||||
root: &Path,
|
||||
hash: &mut sha2::Sha256,
|
||||
) -> Result<(), ConfigSyncError> {
|
||||
use sha2::Digest;
|
||||
let relative = path.strip_prefix(root).map_err(std::io::Error::other)?;
|
||||
let bytes = relative.as_os_str().as_encoded_bytes();
|
||||
hash.update((bytes.len() as u64).to_le_bytes());
|
||||
hash.update(bytes);
|
||||
let kind = std::fs::symlink_metadata(path)?.file_type();
|
||||
if kind.is_symlink() {
|
||||
hash.update(b"link");
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::fs::FileTypeExt;
|
||||
hash.update([u8::from(kind.is_symlink_dir())]);
|
||||
}
|
||||
let target = std::fs::read_link(path)?;
|
||||
let bytes = target.as_os_str().as_encoded_bytes();
|
||||
hash.update((bytes.len() as u64).to_le_bytes());
|
||||
hash.update(bytes);
|
||||
} else if kind.is_file() {
|
||||
hash.update(b"file");
|
||||
hash.update(
|
||||
crate::instance::content::manifest::fingerprint(path)?.hashes["sha512"].as_bytes(),
|
||||
);
|
||||
} else if kind.is_dir() {
|
||||
hash.update(b"dir");
|
||||
let mut entries = std::fs::read_dir(path)?
|
||||
.map(|entry| entry.map(|entry| entry.path()))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
entries.sort();
|
||||
for entry in entries {
|
||||
hash_payload_entry(&entry, root, hash)?;
|
||||
}
|
||||
} else {
|
||||
return Err(std::io::Error::other(format!(
|
||||
"Unsupported config entry '{}'",
|
||||
path.display()
|
||||
))
|
||||
.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn profile_exists(dir: &Path) -> Result<bool, ConfigSyncError> {
|
||||
match std::fs::symlink_metadata(dir) {
|
||||
Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => Ok(true),
|
||||
Ok(_) => Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
format!(
|
||||
"Config profile must be a real directory: '{}'",
|
||||
dir.display()
|
||||
),
|
||||
)
|
||||
.into()),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn require_source_dir(src: &Path) -> Result<(), ConfigSyncError> {
|
||||
let metadata = std::fs::metadata(src).map_err(|error| {
|
||||
std::io::Error::new(
|
||||
error.kind(),
|
||||
format!(
|
||||
"Cannot read config sync source '{}': {error}",
|
||||
src.display()
|
||||
),
|
||||
)
|
||||
})?;
|
||||
if !metadata.is_dir() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
format!("no parent directory for {}", dst.display()),
|
||||
format!("Config sync source is not a directory: '{}'", src.display()),
|
||||
)
|
||||
.into());
|
||||
};
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let name = dst.file_name().and_then(|s| s.to_str()).unwrap_or("mirror");
|
||||
let staging = parent.join(format!(".{name}.mirror-tmp"));
|
||||
if staging.exists() {
|
||||
remove_path(&staging)?;
|
||||
}
|
||||
std::fs::create_dir_all(&staging)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
let result = (|| {
|
||||
if src.exists() {
|
||||
copy_dir_contents(src, &staging)?;
|
||||
}
|
||||
if dst.exists() {
|
||||
remove_path(dst)?;
|
||||
}
|
||||
std::fs::rename(&staging, dst)?;
|
||||
Ok(())
|
||||
})();
|
||||
|
||||
if result.is_err() {
|
||||
let _ = std::fs::remove_dir_all(&staging);
|
||||
fn check_config_root(dir: &Path) -> Result<(), ConfigSyncError> {
|
||||
let config = dir.join("config");
|
||||
if entry_exists(&config)? && std::fs::symlink_metadata(&config)?.file_type().is_symlink() {
|
||||
return Err(std::io::Error::other(format!(
|
||||
"Cannot mirror symlinked config directory '{}'",
|
||||
config.display()
|
||||
))
|
||||
.into());
|
||||
}
|
||||
result
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn sync_to_profile(minecraft_dir: &Path, profile_dir: &Path) -> Result<(), ConfigSyncError> {
|
||||
mirror_dir(&minecraft_dir.join("config"), &profile_dir.join("config"))?;
|
||||
mirror_options(minecraft_dir, profile_dir)
|
||||
mirror_payload(minecraft_dir, profile_dir, true, || Ok(()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn sync_from_profile(profile_dir: &Path, minecraft_dir: &Path) -> Result<(), ConfigSyncError> {
|
||||
mirror_dir(&profile_dir.join("config"), &minecraft_dir.join("config"))?;
|
||||
mirror_options(profile_dir, minecraft_dir)
|
||||
mirror_payload(profile_dir, minecraft_dir, true, || Ok(()))
|
||||
}
|
||||
|
||||
fn profile_payload_exists(profile_dir: &Path) -> Result<bool, ConfigSyncError> {
|
||||
if profile_dir.join("config").exists() {
|
||||
return Ok(true);
|
||||
}
|
||||
if !profile_dir.exists() {
|
||||
return Ok(false);
|
||||
}
|
||||
for entry in std::fs::read_dir(profile_dir)? {
|
||||
let entry = entry?;
|
||||
if entry.file_type()?.is_file() && is_options_file(&entry.file_name().to_string_lossy()) {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
Ok(!payload_names(profile_dir, true)?.is_empty())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn mirror_options(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
|
||||
remove_options(dst)?;
|
||||
std::fs::create_dir_all(dst)?;
|
||||
if !src.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
mirror_payload(src, dst, false, || Ok(()))
|
||||
}
|
||||
|
||||
for entry in std::fs::read_dir(src)? {
|
||||
let entry = entry?;
|
||||
let name = entry.file_name();
|
||||
if entry.file_type()?.is_file() && is_options_file(&name.to_string_lossy()) {
|
||||
std::fs::copy(entry.path(), dst.join(name))?;
|
||||
}
|
||||
fn entry_exists(path: &Path) -> Result<bool, ConfigSyncError> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(_) => Ok(true),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_if_exists(path: &Path) -> Result<(), ConfigSyncError> {
|
||||
if entry_exists(path)? {
|
||||
remove_path(path)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove_options(dir: &Path) -> Result<(), ConfigSyncError> {
|
||||
if !dir.exists() {
|
||||
return Ok(());
|
||||
fn cleanup_sync_path(path: &Path) {
|
||||
if let Err(error) = remove_if_exists(path) {
|
||||
tracing::warn!(
|
||||
"Could not remove config sync staging/backup '{}': {error}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn payload_names(
|
||||
dir: &Path,
|
||||
include_config: bool,
|
||||
) -> Result<Vec<std::ffi::OsString>, ConfigSyncError> {
|
||||
if !entry_exists(dir)? {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut names = Vec::new();
|
||||
for entry in std::fs::read_dir(dir)? {
|
||||
let entry = entry?;
|
||||
if is_options_file(&entry.file_name().to_string_lossy()) {
|
||||
remove_path(&entry.path())?;
|
||||
let name = entry.file_name();
|
||||
let kind = entry.file_type()?;
|
||||
if include_config && name == "config"
|
||||
|| is_options_file(&name.to_string_lossy()) && (kind.is_file() || kind.is_symlink())
|
||||
{
|
||||
names.push(name);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
names.sort();
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
fn rollback_payload(
|
||||
dst: &Path,
|
||||
backup: &Path,
|
||||
installed: &[std::ffi::OsString],
|
||||
moved: &[std::ffi::OsString],
|
||||
) -> Result<(), String> {
|
||||
let mut errors = Vec::new();
|
||||
for name in installed.iter().rev() {
|
||||
if let Err(error) = remove_if_exists(&dst.join(name)) {
|
||||
errors.push(format!("Removing '{}': {error}", dst.join(name).display()));
|
||||
}
|
||||
}
|
||||
for name in moved.iter().rev() {
|
||||
let target = dst.join(name);
|
||||
match entry_exists(&target) {
|
||||
Ok(false) => {
|
||||
if let Err(error) = std::fs::rename(backup.join(name), &target) {
|
||||
errors.push(format!("Restoring '{}': {error}", target.display()));
|
||||
}
|
||||
}
|
||||
Ok(true) => errors.push(format!("Cannot restore occupied '{}'", target.display())),
|
||||
Err(error) => errors.push(format!("Inspecting '{}': {error}", target.display())),
|
||||
}
|
||||
}
|
||||
if errors.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(errors.join("; "))
|
||||
}
|
||||
}
|
||||
|
||||
fn mirror_payload<T>(
|
||||
src: &Path,
|
||||
dst: &Path,
|
||||
include_config: bool,
|
||||
commit: impl FnOnce() -> Result<T, ConfigSyncError>,
|
||||
) -> Result<T, ConfigSyncError> {
|
||||
require_source_dir(src)?;
|
||||
let parent = dst
|
||||
.parent()
|
||||
.filter(|parent| !parent.as_os_str().is_empty())
|
||||
.ok_or_else(|| std::io::Error::other(format!("No parent for '{}'", dst.display())))?;
|
||||
std::fs::create_dir_all(dst)?;
|
||||
if include_config {
|
||||
check_config_root(src)?;
|
||||
check_config_root(dst)?;
|
||||
let old_backup = dst.join(".config.mirror-backup");
|
||||
if entry_exists(&old_backup)? {
|
||||
return Err(std::io::Error::other(format!(
|
||||
"Previous config backup remains at '{}'",
|
||||
old_backup.display()
|
||||
))
|
||||
.into());
|
||||
}
|
||||
}
|
||||
let name = dst
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or("payload");
|
||||
let staging = parent.join(format!(".{name}.sync-stage"));
|
||||
let backup = parent.join(format!(".{name}.sync-backup"));
|
||||
// An existing backup belongs to an interrupted transaction and must survive for recovery.
|
||||
std::fs::create_dir(&backup).map_err(|error| {
|
||||
std::io::Error::new(
|
||||
error.kind(),
|
||||
format!("Cannot create backup '{}': {error}", backup.display()),
|
||||
)
|
||||
})?;
|
||||
let mut moved = Vec::new();
|
||||
let mut installed = Vec::new();
|
||||
let result = (|| {
|
||||
remove_if_exists(&staging)?;
|
||||
std::fs::create_dir(&staging)?;
|
||||
if include_config {
|
||||
std::fs::create_dir(staging.join("config"))?;
|
||||
if entry_exists(&src.join("config"))? {
|
||||
copy_dir_contents(
|
||||
&src.join("config"),
|
||||
&staging.join("config"),
|
||||
src,
|
||||
include_config,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
for name in payload_names(src, false)? {
|
||||
let source = src.join(&name);
|
||||
let target = staging.join(&name);
|
||||
if std::fs::symlink_metadata(&source)?.file_type().is_symlink() {
|
||||
copy_payload_symlink(&source, &target, src, include_config)?;
|
||||
} else {
|
||||
std::fs::copy(&source, &target)?;
|
||||
}
|
||||
}
|
||||
for name in payload_names(dst, include_config)? {
|
||||
std::fs::rename(dst.join(&name), backup.join(&name))?;
|
||||
moved.push(name);
|
||||
}
|
||||
for name in payload_names(&staging, include_config)? {
|
||||
std::fs::rename(staging.join(&name), dst.join(&name))?;
|
||||
installed.push(name);
|
||||
}
|
||||
commit()
|
||||
})();
|
||||
let result = match result {
|
||||
Ok(value) => {
|
||||
cleanup_sync_path(&backup);
|
||||
Ok(value)
|
||||
}
|
||||
Err(error) => match rollback_payload(dst, &backup, &installed, &moved) {
|
||||
Ok(()) => {
|
||||
cleanup_sync_path(&backup);
|
||||
Err(error)
|
||||
}
|
||||
Err(rollback) => Err(ConfigSyncError::SaveRollback {
|
||||
save: error.to_string(),
|
||||
rollback: format!(
|
||||
"{rollback}; recovery backup retained at '{}'",
|
||||
backup.display()
|
||||
),
|
||||
}),
|
||||
},
|
||||
};
|
||||
cleanup_sync_path(&staging);
|
||||
result
|
||||
}
|
||||
|
||||
fn is_options_file(name: &str) -> bool {
|
||||
@@ -330,6 +814,14 @@ fn is_options_file(name: &str) -> bool {
|
||||
|
||||
fn remove_path(path: &Path) -> Result<(), ConfigSyncError> {
|
||||
let meta = std::fs::symlink_metadata(path)?;
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::fs::FileTypeExt;
|
||||
if meta.file_type().is_symlink_dir() {
|
||||
std::fs::remove_dir(path)?;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if meta.is_dir() {
|
||||
std::fs::remove_dir_all(path)?;
|
||||
} else {
|
||||
@@ -338,7 +830,12 @@ fn remove_path(path: &Path) -> Result<(), ConfigSyncError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn copy_dir_contents(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
|
||||
fn copy_dir_contents(
|
||||
src: &Path,
|
||||
dst: &Path,
|
||||
payload: &Path,
|
||||
include_config: bool,
|
||||
) -> Result<(), ConfigSyncError> {
|
||||
for entry in std::fs::read_dir(src)? {
|
||||
let entry = entry?;
|
||||
let source = entry.path();
|
||||
@@ -347,15 +844,83 @@ fn copy_dir_contents(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
|
||||
|
||||
if file_type.is_dir() {
|
||||
std::fs::create_dir_all(&target)?;
|
||||
copy_dir_contents(&source, &target)?;
|
||||
copy_dir_contents(&source, &target, payload, include_config)?;
|
||||
} else if file_type.is_file() {
|
||||
std::fs::copy(&source, &target)?;
|
||||
} else if file_type.is_symlink() {
|
||||
copy_payload_symlink(&source, &target, payload, include_config)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn copy_payload_symlink(
|
||||
source: &Path,
|
||||
destination: &Path,
|
||||
payload: &Path,
|
||||
include_config: bool,
|
||||
) -> Result<(), ConfigSyncError> {
|
||||
let mut target = std::fs::read_link(source)?;
|
||||
if target.is_relative() {
|
||||
let relative = source
|
||||
.strip_prefix(payload)
|
||||
.map_err(std::io::Error::other)?;
|
||||
let mut position = relative.parent().unwrap_or(Path::new("")).to_owned();
|
||||
let mut internal = true;
|
||||
for component in target.components() {
|
||||
match component {
|
||||
std::path::Component::Normal(name) => position.push(name),
|
||||
std::path::Component::CurDir => {}
|
||||
std::path::Component::ParentDir => {
|
||||
if !position.pop() {
|
||||
internal = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
internal = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let Some(first) = position.components().next() {
|
||||
let name = first.as_os_str();
|
||||
if include_config && name == "config" {
|
||||
continue;
|
||||
}
|
||||
if !is_options_file(&name.to_string_lossy()) {
|
||||
internal = false;
|
||||
break;
|
||||
}
|
||||
match std::fs::symlink_metadata(payload.join(name)) {
|
||||
Ok(metadata) if metadata.is_file() || metadata.file_type().is_symlink() => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error.into()),
|
||||
_ => {
|
||||
internal = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
internal &= !position.as_os_str().is_empty();
|
||||
if !internal {
|
||||
// External links keep their source anchor; internal links move with the payload.
|
||||
let anchored = std::path::absolute(source.parent().unwrap().join(target))?;
|
||||
target = match (anchored.parent(), anchored.file_name()) {
|
||||
(Some(parent), Some(name)) => match std::fs::canonicalize(parent) {
|
||||
Ok(parent) => parent.join(name),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => anchored,
|
||||
Err(error) => return Err(error.into()),
|
||||
},
|
||||
_ => std::fs::canonicalize(anchored)?,
|
||||
};
|
||||
}
|
||||
}
|
||||
crate::storage::copy_symlink_target(source, destination, &target)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests/config_sync.rs"]
|
||||
mod tests;
|
||||
@@ -1,8 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// data pack scanning backed by the same pack.mcmeta reader as resource packs.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use super::entry::ContentEntry;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -55,22 +55,10 @@ pub struct ContentEntry {
|
||||
pub icon_lines: Option<Vec<Vec<IconCell>>>,
|
||||
}
|
||||
|
||||
// enable/disable by renaming the file with/without ".disabled" suffix.
|
||||
pub fn toggle_entry(entry: &ContentEntry) -> Result<(), std::io::Error> {
|
||||
toggle_entry_path(entry).map(drop)
|
||||
}
|
||||
|
||||
pub(crate) fn toggle_entry_path(entry: &ContentEntry) -> Result<Option<PathBuf>, std::io::Error> {
|
||||
let Some(file_name) = entry.path.file_name().and_then(|name| name.to_str()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let new_name = if entry.enabled {
|
||||
format!("{file_name}.disabled")
|
||||
} else {
|
||||
file_name.trim_end_matches(".disabled").to_owned()
|
||||
};
|
||||
let mut new_path = entry.path.clone();
|
||||
new_path.set_file_name(new_name);
|
||||
std::fs::rename(&entry.path, &new_path)?;
|
||||
Ok(Some(new_path))
|
||||
super::local::toggle(entry)
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// terminal icon rasterization shared by every content type and markdown.
|
||||
|
||||
// a single "pixel" in a terminal icon.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct IconCell {
|
||||
pub symbol: char,
|
||||
@@ -45,7 +42,7 @@ pub(crate) fn make_icon_pixels_from_image(
|
||||
let [tr, tg, tb] = rgb.get_pixel(u32::from(column), top_y).0;
|
||||
let [br, bg, bb] = rgb.get_pixel(u32::from(column), bottom_y).0;
|
||||
columns.push(IconCell {
|
||||
symbol: '\u{2584}',
|
||||
symbol: '\u{2580}',
|
||||
bg_r: br,
|
||||
bg_g: bg,
|
||||
bg_b: bb,
|
||||
|
||||
@@ -0,0 +1,451 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use super::entry::ContentEntry;
|
||||
use super::manifest::{
|
||||
ContentFileRecord, ContentLock, ContentManifest, FileFingerprint, fingerprint,
|
||||
fingerprint_metadata,
|
||||
};
|
||||
|
||||
pub(crate) struct StagingDirectory {
|
||||
path: PathBuf,
|
||||
retained: bool,
|
||||
}
|
||||
|
||||
impl StagingDirectory {
|
||||
pub(crate) fn new(minecraft_dir: &Path) -> io::Result<Self> {
|
||||
std::fs::create_dir_all(minecraft_dir)?;
|
||||
Ok(Self {
|
||||
path: tempfile::Builder::new()
|
||||
.prefix(".rmcl-install-")
|
||||
.tempdir_in(minecraft_dir)?
|
||||
.keep(),
|
||||
retained: false,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for StagingDirectory {
|
||||
fn drop(&mut self) {
|
||||
if !self.retained
|
||||
&& !std::thread::panicking()
|
||||
&& let Err(error) = std::fs::remove_dir_all(&self.path)
|
||||
&& error.kind() != io::ErrorKind::NotFound
|
||||
{
|
||||
tracing::warn!(
|
||||
"Could not remove content staging '{}': {error}",
|
||||
self.path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct FileTransaction {
|
||||
staging: StagingDirectory,
|
||||
moves: Vec<(PathBuf, PathBuf)>,
|
||||
}
|
||||
|
||||
impl FileTransaction {
|
||||
pub(crate) fn new(staging: StagingDirectory) -> Self {
|
||||
Self {
|
||||
staging,
|
||||
moves: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn staging(&self) -> &Path {
|
||||
self.staging.path()
|
||||
}
|
||||
|
||||
pub(crate) fn move_path(&mut self, from: &Path, to: &Path) -> io::Result<()> {
|
||||
require_absent(to)?;
|
||||
std::fs::rename(from, to)?;
|
||||
self.moves.push((from.to_owned(), to.to_owned()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn finish<T, E: From<io::Error> + std::fmt::Display>(
|
||||
&mut self,
|
||||
result: Result<T, E>,
|
||||
) -> Result<T, E> {
|
||||
match result {
|
||||
Ok(value) => {
|
||||
self.moves.clear();
|
||||
Ok(value)
|
||||
}
|
||||
Err(error) => match self.rollback() {
|
||||
Ok(()) => Err(error),
|
||||
Err(rollback) => Err(io::Error::other(format!("{error}; {rollback}")).into()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn rollback(&mut self) -> io::Result<()> {
|
||||
let mut errors = Vec::new();
|
||||
for (from, to) in self.moves.iter().rev() {
|
||||
if let Err(error) = require_absent(from).and_then(|()| std::fs::rename(to, from)) {
|
||||
errors.push(format!(
|
||||
"restore '{}' from '{}': {error}",
|
||||
from.display(),
|
||||
to.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
self.moves.clear();
|
||||
if errors.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
self.staging.retained = true;
|
||||
Err(io::Error::other(format!(
|
||||
"Content rollback failed: {}; recovery staging retained at '{}'",
|
||||
errors.join("; "),
|
||||
self.staging.path.display()
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FileTransaction {
|
||||
fn drop(&mut self) {
|
||||
if !self.moves.is_empty()
|
||||
&& let Err(error) = self.rollback()
|
||||
{
|
||||
tracing::error!("{error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn require_absent(path: &Path) -> io::Result<()> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(_) => Err(io::Error::new(
|
||||
io::ErrorKind::AlreadyExists,
|
||||
format!("'{}' already exists", path.display()),
|
||||
)),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn relative_path(minecraft_dir: &Path, path: &Path) -> io::Result<PathBuf> {
|
||||
let relative = path.strip_prefix(minecraft_dir).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("'{}' is outside the Minecraft directory", path.display()),
|
||||
)
|
||||
})?;
|
||||
if !crate::storage::safe_relative_path(relative) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("Invalid content path '{}'", path.display()),
|
||||
));
|
||||
}
|
||||
let root = minecraft_dir.canonicalize()?;
|
||||
let mut parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| io::Error::other("Content path has no parent"))?;
|
||||
loop {
|
||||
match parent.canonicalize() {
|
||||
Ok(parent) if parent.starts_with(&root) => break,
|
||||
Ok(_) => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!(
|
||||
"Content path '{}' escapes through a symlink",
|
||||
path.display()
|
||||
),
|
||||
));
|
||||
}
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {
|
||||
parent = parent.parent().ok_or(error)?;
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Ok(relative.to_owned())
|
||||
}
|
||||
|
||||
fn mutation_lock(manifest_path: &Path, relative: &Path) -> io::Result<ContentLock> {
|
||||
if relative.starts_with("saves") && relative.components().count() <= 2 {
|
||||
ContentLock::acquire_stopped(manifest_path)
|
||||
} else {
|
||||
ContentLock::acquire(manifest_path)
|
||||
}
|
||||
.map_err(io::Error::other)
|
||||
}
|
||||
|
||||
pub(crate) fn validate_record(minecraft_dir: &Path, record: &ContentFileRecord) -> io::Result<()> {
|
||||
let path = minecraft_dir.join(&record.relative_path);
|
||||
relative_path(minecraft_dir, &path)?;
|
||||
if current_fingerprint(&path, &record.fingerprint)? != record.fingerprint {
|
||||
return Err(io::Error::other(format!(
|
||||
"Content '{}' changed; refresh before retrying",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn current_fingerprint(
|
||||
path: &Path,
|
||||
expected: &FileFingerprint,
|
||||
) -> io::Result<FileFingerprint> {
|
||||
let metadata = std::fs::symlink_metadata(path)?;
|
||||
if metadata.file_type().is_symlink() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("Content '{}' is a symlink", path.display()),
|
||||
));
|
||||
}
|
||||
if metadata.is_dir() {
|
||||
directory_fingerprint_metadata(path)
|
||||
} else if metadata.is_file() && expected.hashes.is_empty() {
|
||||
fingerprint_metadata(path)
|
||||
} else if metadata.is_file() {
|
||||
fingerprint(path)
|
||||
} else {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("Content '{}' is not a file or directory", path.display()),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn directory_fingerprint_metadata(path: &Path) -> io::Result<FileFingerprint> {
|
||||
fn accumulate(path: &Path, size: &mut u64, modified_ns: &mut u128) -> io::Result<()> {
|
||||
for entry in std::fs::read_dir(path)? {
|
||||
let entry = entry?;
|
||||
let metadata = std::fs::symlink_metadata(entry.path())?;
|
||||
if metadata.file_type().is_symlink() {
|
||||
continue;
|
||||
}
|
||||
let modified = metadata
|
||||
.modified()
|
||||
.unwrap_or(SystemTime::UNIX_EPOCH)
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_nanos();
|
||||
*modified_ns = (*modified_ns).max(modified);
|
||||
if metadata.is_dir() {
|
||||
accumulate(&entry.path(), size, modified_ns)?;
|
||||
} else if metadata.is_file() {
|
||||
*size = size.saturating_add(metadata.len());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
let mut size = 0;
|
||||
let mut modified_ns = 0;
|
||||
accumulate(path, &mut size, &mut modified_ns)?;
|
||||
Ok(FileFingerprint {
|
||||
size,
|
||||
modified_ns,
|
||||
hashes: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn toggle(entry: &ContentEntry) -> io::Result<Option<PathBuf>> {
|
||||
let Some(name) = entry.path.file_name().and_then(|name| name.to_str()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let disabled = name.ends_with(".disabled");
|
||||
if disabled == entry.enabled {
|
||||
return Err(io::Error::other(format!(
|
||||
"Enabled state of '{}' changed; refresh before retrying",
|
||||
entry.path.display()
|
||||
)));
|
||||
}
|
||||
let new_name = if entry.enabled {
|
||||
format!("{name}.disabled")
|
||||
} else {
|
||||
name.trim_end_matches(".disabled").to_owned()
|
||||
};
|
||||
let new_path = entry.path.with_file_name(new_name);
|
||||
let instance_minecraft = entry.path.ancestors().find(|path| {
|
||||
path.file_name()
|
||||
.is_some_and(|name| name == crate::storage::MINECRAFT_DIR_NAME)
|
||||
&& entry.path.strip_prefix(path).is_ok_and(|relative| {
|
||||
relative.components().next().is_some_and(|component| {
|
||||
matches!(component, std::path::Component::Normal(name)
|
||||
if name == "mods" || name == "resourcepacks" || name == "shaderpacks" || name == "saves")
|
||||
})
|
||||
})
|
||||
});
|
||||
let minecraft_dir = instance_minecraft
|
||||
.or_else(|| entry.path.parent())
|
||||
.ok_or_else(|| io::Error::other("Content path has no parent"))?;
|
||||
let manifest_path = if let Some(minecraft) = instance_minecraft {
|
||||
crate::storage::InstancePaths::new(
|
||||
minecraft
|
||||
.parent()
|
||||
.ok_or_else(|| io::Error::other("Minecraft directory has no instance parent"))?,
|
||||
)
|
||||
.content_manifest()
|
||||
} else {
|
||||
minecraft_dir.join(".rmcl-content.json")
|
||||
};
|
||||
let relative = relative_path(minecraft_dir, &entry.path)?;
|
||||
let lock = mutation_lock(&manifest_path, &relative)?;
|
||||
let mut manifest = if instance_minecraft.is_some() {
|
||||
lock.load().map_err(io::Error::other)?
|
||||
} else {
|
||||
ContentManifest::default()
|
||||
};
|
||||
let new_relative = relative_path(minecraft_dir, &new_path)?;
|
||||
require_absent(&new_path)?;
|
||||
if manifest.record(&new_relative).is_some() {
|
||||
return Err(io::Error::other(format!(
|
||||
"Content manifest already owns '{}'",
|
||||
new_path.display()
|
||||
)));
|
||||
}
|
||||
let record = manifest.record(&relative).cloned();
|
||||
let previous = manifest.clone();
|
||||
if let Some(project) = &entry.provider_project
|
||||
&& record
|
||||
.as_ref()
|
||||
.and_then(|record| record.project_for_provider(&project.provider, &project.project_id))
|
||||
!= Some(project)
|
||||
{
|
||||
return Err(io::Error::other(format!(
|
||||
"Ownership of '{}' changed; refresh before retrying",
|
||||
entry.path.display()
|
||||
)));
|
||||
}
|
||||
if let Some(record) = &record {
|
||||
if record.enabled != entry.enabled {
|
||||
return Err(io::Error::other(format!(
|
||||
"Enabled state of '{}' changed; refresh before retrying",
|
||||
entry.path.display()
|
||||
)));
|
||||
}
|
||||
validate_record(minecraft_dir, record)?;
|
||||
} else {
|
||||
current_fingerprint(
|
||||
&entry.path,
|
||||
&FileFingerprint {
|
||||
size: 0,
|
||||
modified_ns: 0,
|
||||
hashes: Default::default(),
|
||||
},
|
||||
)?;
|
||||
}
|
||||
let mut transaction = FileTransaction::new(StagingDirectory::new(minecraft_dir)?);
|
||||
let result = (|| {
|
||||
transaction.move_path(&entry.path, &new_path)?;
|
||||
if let Some(mut record) = record {
|
||||
manifest.remove(&relative);
|
||||
record.relative_path = new_relative;
|
||||
record.enabled = !entry.enabled;
|
||||
manifest.upsert(record);
|
||||
lock.save_if_unchanged(&manifest, &previous)
|
||||
.map_err(io::Error::other)?;
|
||||
}
|
||||
Ok(Some(new_path))
|
||||
})();
|
||||
transaction.finish(result)
|
||||
}
|
||||
|
||||
pub(crate) fn record_toggle(
|
||||
manifest: &mut ContentManifest,
|
||||
minecraft_dir: &Path,
|
||||
old_path: &Path,
|
||||
new_path: &Path,
|
||||
enabled: bool,
|
||||
) -> io::Result<bool> {
|
||||
let old_relative = relative_path(minecraft_dir, old_path)?;
|
||||
let new_relative = relative_path(minecraft_dir, new_path)?;
|
||||
match std::fs::symlink_metadata(old_path) {
|
||||
Ok(_) => return Ok(false),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
if let Some(record) = manifest.record(&new_relative) {
|
||||
if manifest.record(&old_relative).is_some() || record.enabled != enabled {
|
||||
return Ok(false);
|
||||
}
|
||||
validate_record(minecraft_dir, record)?;
|
||||
return Ok(true);
|
||||
}
|
||||
let Some(record) = manifest.record(&old_relative) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let fresh = match current_fingerprint(new_path, &record.fingerprint) {
|
||||
Ok(fresh) => fresh,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
Ok(
|
||||
fresh == record.fingerprint
|
||||
&& manifest.rename_record(&old_relative, &new_relative, enabled),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn remove(
|
||||
manifest_path: &Path,
|
||||
minecraft_dir: &Path,
|
||||
path: &Path,
|
||||
expected: &[ContentFileRecord],
|
||||
orphan_only: bool,
|
||||
) -> io::Result<(ContentManifest, Vec<PathBuf>)> {
|
||||
let relative = relative_path(minecraft_dir, path)?;
|
||||
let lock = mutation_lock(manifest_path, &relative)?;
|
||||
let mut manifest = lock.load().map_err(io::Error::other)?;
|
||||
let previous = manifest.clone();
|
||||
if manifest
|
||||
.files
|
||||
.iter()
|
||||
.filter(|record| record.relative_path.starts_with(&relative))
|
||||
.ne(expected.iter())
|
||||
{
|
||||
return Err(io::Error::other(format!(
|
||||
"Ownership of '{}' changed; refresh before retrying",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
if orphan_only && !manifest.orphaned_dependencies().contains(&relative) {
|
||||
return Err(io::Error::other(format!(
|
||||
"'{}' is no longer an unused dependency",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
for record in expected {
|
||||
match validate_record(minecraft_dir, record) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
let mut transaction = FileTransaction::new(StagingDirectory::new(minecraft_dir)?);
|
||||
let result = (|| {
|
||||
let backup = transaction.staging().join("removed");
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(_) => transaction.move_path(path, &backup)?,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
manifest
|
||||
.files
|
||||
.retain(|record| !record.relative_path.starts_with(&relative));
|
||||
let orphans = manifest
|
||||
.orphaned_dependencies()
|
||||
.into_iter()
|
||||
.map(|relative| minecraft_dir.join(relative))
|
||||
.collect();
|
||||
lock.save_if_unchanged(&manifest, &previous)
|
||||
.map_err(io::Error::other)?;
|
||||
Ok((manifest, orphans))
|
||||
})();
|
||||
transaction.finish(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../tests/content/local.rs"]
|
||||
mod tests;
|
||||
@@ -1,18 +1,146 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{Read, Seek};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha1::Digest as _;
|
||||
|
||||
const MANIFEST_VERSION: u32 = 1;
|
||||
static MANIFEST_LOCKS: LazyLock<Mutex<HashMap<PathBuf, Arc<Mutex<()>>>>> =
|
||||
LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
pub(crate) struct ContentLock {
|
||||
file: File,
|
||||
_instance_lock: Option<crate::instance::runtime::InstanceLock>,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl ContentLock {
|
||||
pub(crate) fn acquire(path: &Path) -> Result<Self, ManifestError> {
|
||||
Self::acquire_with_instance_guard(path, false)
|
||||
}
|
||||
|
||||
pub(crate) fn acquire_stopped(path: &Path) -> Result<Self, ManifestError> {
|
||||
Self::acquire_with_instance_guard(path, true)
|
||||
}
|
||||
|
||||
fn acquire_with_instance_guard(
|
||||
path: &Path,
|
||||
require_stopped: bool,
|
||||
) -> Result<Self, ManifestError> {
|
||||
let parent = path.parent().ok_or_else(|| {
|
||||
ManifestError::InvalidPath(format!("{} has no parent", path.display()))
|
||||
})?;
|
||||
let instance_dir = parent
|
||||
.parent()
|
||||
.filter(|state| {
|
||||
path.file_name().is_some_and(|name| name == "manifest.json")
|
||||
&& parent.file_name().is_some_and(|name| name == "content")
|
||||
&& state
|
||||
.file_name()
|
||||
.is_some_and(|name| name == crate::storage::INSTANCE_STATE_DIR_NAME)
|
||||
})
|
||||
.and_then(Path::parent);
|
||||
let instance_lock = if let Some(instance_dir) = instance_dir {
|
||||
let root = instance_dir.parent().ok_or_else(|| {
|
||||
ManifestError::InvalidPath(format!("{} has no instance root", path.display()))
|
||||
})?;
|
||||
let name = instance_dir
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.ok_or_else(|| {
|
||||
ManifestError::InvalidPath(format!("{} has no instance name", path.display()))
|
||||
})?;
|
||||
let lock = if require_stopped {
|
||||
crate::instance::runtime::lock_instance(root, name)
|
||||
} else {
|
||||
crate::instance::runtime::lock_content(root, name)
|
||||
};
|
||||
Some(lock.map_err(|error| match error {
|
||||
crate::instance::manager::InstanceError::InstanceRunning(_) => {
|
||||
ManifestError::Busy(path.to_owned())
|
||||
}
|
||||
error => ManifestError::Io(std::io::Error::other(error)),
|
||||
})?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Self::acquire_file(path, instance_lock)
|
||||
}
|
||||
|
||||
pub(crate) fn acquire_with_held_instance_lock(
|
||||
path: &Path,
|
||||
_guard: &crate::instance::runtime::InstanceLock,
|
||||
) -> Result<Self, ManifestError> {
|
||||
Self::acquire_file(path, None)
|
||||
}
|
||||
|
||||
fn acquire_file(
|
||||
path: &Path,
|
||||
instance_lock: Option<crate::instance::runtime::InstanceLock>,
|
||||
) -> Result<Self, ManifestError> {
|
||||
let parent = path.parent().ok_or_else(|| {
|
||||
ManifestError::InvalidPath(format!("{} has no parent", path.display()))
|
||||
})?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(path.with_extension("lock"))?;
|
||||
if let Err(error) = fs2::FileExt::try_lock_exclusive(&file) {
|
||||
if error.raw_os_error() == fs2::lock_contended_error().raw_os_error() {
|
||||
return Err(ManifestError::Busy(path.to_owned()));
|
||||
}
|
||||
return Err(error.into());
|
||||
}
|
||||
Ok(Self {
|
||||
file,
|
||||
_instance_lock: instance_lock,
|
||||
path: path.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn load(&self) -> Result<ContentManifest, ManifestError> {
|
||||
ContentManifest::load(&self.path)
|
||||
}
|
||||
|
||||
pub(crate) fn save(&self, manifest: &ContentManifest) -> Result<(), ManifestError> {
|
||||
let bytes = serde_json::to_vec_pretty(manifest)?;
|
||||
crate::storage::write_atomic(&self.path, &bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn save_if_unchanged(
|
||||
&self,
|
||||
manifest: &ContentManifest,
|
||||
previous: &ContentManifest,
|
||||
) -> Result<(), ManifestError> {
|
||||
let current = self.load()?;
|
||||
if current.version != previous.version || current.files != previous.files {
|
||||
return Err(ManifestError::Changed(self.path.clone()));
|
||||
}
|
||||
if manifest.version != previous.version || manifest.files != previous.files {
|
||||
self.save(manifest)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ContentLock {
|
||||
fn drop(&mut self) {
|
||||
if let Err(error) = fs2::FileExt::unlock(&self.file) {
|
||||
tracing::warn!(
|
||||
"Could not release content lock '{}': {error}",
|
||||
self.path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
@@ -120,10 +248,13 @@ impl Default for ContentManifest {
|
||||
|
||||
impl ContentManifest {
|
||||
pub fn load(path: &Path) -> Result<Self, ManifestError> {
|
||||
if !path.exists() {
|
||||
return Ok(Self::default());
|
||||
}
|
||||
let bytes = std::fs::read(path)?;
|
||||
let bytes = match std::fs::read(path) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
return Ok(Self::default());
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
let mut manifest: Self = serde_json::from_slice(&bytes)?;
|
||||
if manifest.version != MANIFEST_VERSION {
|
||||
return Err(ManifestError::UnsupportedVersion(manifest.version));
|
||||
@@ -133,36 +264,32 @@ impl ContentManifest {
|
||||
manifest
|
||||
.files
|
||||
.sort_by(|left, right| left.relative_path.cmp(&right.relative_path));
|
||||
for (index, record) in manifest.files.iter().enumerate() {
|
||||
if !crate::storage::safe_relative_path(&record.relative_path)
|
||||
|| index > 0 && manifest.files[index - 1].relative_path == record.relative_path
|
||||
{
|
||||
return Err(ManifestError::InvalidPath(format!(
|
||||
"Unsafe or duplicate content path '{}'",
|
||||
record.relative_path.display()
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
pub fn save(&self, path: &Path) -> Result<(), ManifestError> {
|
||||
let parent = path.parent().ok_or_else(|| {
|
||||
ManifestError::InvalidPath(format!("{} has no parent", path.display()))
|
||||
})?;
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let bytes = serde_json::to_vec_pretty(self)?;
|
||||
crate::storage::write_atomic(path, &bytes)?;
|
||||
Ok(())
|
||||
ContentLock::acquire(path)?.save(self)
|
||||
}
|
||||
|
||||
pub fn update<T>(
|
||||
path: &Path,
|
||||
update: impl FnOnce(&mut Self) -> Result<T, ManifestError>,
|
||||
) -> Result<T, ManifestError> {
|
||||
let lock = {
|
||||
let mut locks = MANIFEST_LOCKS
|
||||
.lock()
|
||||
.map_err(|_| ManifestError::LockPoisoned)?;
|
||||
locks
|
||||
.entry(path.to_owned())
|
||||
.or_insert_with(|| Arc::new(Mutex::new(())))
|
||||
.clone()
|
||||
};
|
||||
let _guard = lock.lock().map_err(|_| ManifestError::LockPoisoned)?;
|
||||
let mut manifest = Self::load(path)?;
|
||||
let lock = ContentLock::acquire(path)?;
|
||||
let mut manifest = lock.load()?;
|
||||
let previous = manifest.clone();
|
||||
let result = update(&mut manifest)?;
|
||||
manifest.save(path)?;
|
||||
lock.save_if_unchanged(&manifest, &previous)?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
@@ -200,10 +327,13 @@ impl ContentManifest {
|
||||
}
|
||||
|
||||
pub fn rename_record(&mut self, from: &Path, to: &Path, enabled: bool) -> bool {
|
||||
if from != to && self.record(to).is_some() {
|
||||
return false;
|
||||
}
|
||||
let Some(index) = self
|
||||
.files
|
||||
.iter()
|
||||
.position(|record| record.relative_path == from || record.relative_path == to)
|
||||
.position(|record| record.relative_path == from)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
@@ -362,11 +492,21 @@ pub enum ManifestError {
|
||||
UnsupportedVersion(u32),
|
||||
#[error("Invalid manifest path: {0}")]
|
||||
InvalidPath(String),
|
||||
#[error("Content manifest lock was poisoned")]
|
||||
LockPoisoned,
|
||||
#[error("Content is being changed by another operation: {0}")]
|
||||
Busy(PathBuf),
|
||||
#[error("Content manifest changed during the operation; refresh before retrying: {0}")]
|
||||
Changed(PathBuf),
|
||||
}
|
||||
|
||||
pub fn fingerprint(path: &Path) -> Result<FileFingerprint, std::io::Error> {
|
||||
fingerprint_with_check(path, || Ok(()))
|
||||
}
|
||||
|
||||
pub(crate) fn fingerprint_with_check(
|
||||
path: &Path,
|
||||
check: impl Fn() -> std::io::Result<()>,
|
||||
) -> Result<FileFingerprint, std::io::Error> {
|
||||
check()?;
|
||||
let metadata = std::fs::metadata(path)?;
|
||||
let modified_ns = metadata
|
||||
.modified()
|
||||
@@ -380,6 +520,7 @@ pub fn fingerprint(path: &Path) -> Result<FileFingerprint, std::io::Error> {
|
||||
let mut curseforge_len = 0u32;
|
||||
let mut buffer = [0u8; 64 * 1024];
|
||||
loop {
|
||||
check()?;
|
||||
let read = file.read(&mut buffer)?;
|
||||
if read == 0 {
|
||||
break;
|
||||
@@ -399,7 +540,7 @@ pub fn fingerprint(path: &Path) -> Result<FileFingerprint, std::io::Error> {
|
||||
("sha512".to_owned(), format!("{:x}", sha512.finalize())),
|
||||
(
|
||||
"curseforge".to_owned(),
|
||||
curseforge_fingerprint(&mut file, curseforge_len)?.to_string(),
|
||||
curseforge_fingerprint(&mut file, curseforge_len, &check)?.to_string(),
|
||||
),
|
||||
]);
|
||||
Ok(FileFingerprint {
|
||||
@@ -409,13 +550,18 @@ pub fn fingerprint(path: &Path) -> Result<FileFingerprint, std::io::Error> {
|
||||
})
|
||||
}
|
||||
|
||||
fn curseforge_fingerprint(reader: &mut impl Read, length: u32) -> std::io::Result<u32> {
|
||||
fn curseforge_fingerprint(
|
||||
reader: &mut impl Read,
|
||||
length: u32,
|
||||
check: &impl Fn() -> std::io::Result<()>,
|
||||
) -> std::io::Result<u32> {
|
||||
const M: u32 = 0x5bd1e995;
|
||||
let mut hash = 1 ^ length;
|
||||
let mut block = [0u8; 4];
|
||||
let mut block_len = 0;
|
||||
let mut buffer = [0u8; 64 * 1024];
|
||||
loop {
|
||||
check()?;
|
||||
let read = reader.read(&mut buffer)?;
|
||||
if read == 0 {
|
||||
break;
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// scanning and toggling instance content (mods, resource packs, shaders, worlds).
|
||||
// minecraft uses a ".disabled" suffix convention for disabled content, so this leans on that heavily.
|
||||
|
||||
pub mod datapacks;
|
||||
pub mod dependencies;
|
||||
pub mod entry;
|
||||
pub mod icons;
|
||||
pub(crate) mod local;
|
||||
pub mod manifest;
|
||||
pub mod mods;
|
||||
mod packs;
|
||||
@@ -30,8 +30,17 @@ pub use worlds::{scan_one_world, scan_worlds};
|
||||
|
||||
use std::io::Read;
|
||||
|
||||
// figures out if a file is enabled or disabled based on the ".disabled" suffix,
|
||||
// and strips the extension to get a clean stem name
|
||||
const MAX_LOCAL_METADATA_BYTES: u64 = 8 * 1024 * 1024;
|
||||
|
||||
fn read_local_metadata(reader: impl Read) -> Option<Vec<u8>> {
|
||||
let mut bytes = Vec::new();
|
||||
reader
|
||||
.take(MAX_LOCAL_METADATA_BYTES + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.ok()?;
|
||||
(bytes.len() as u64 <= MAX_LOCAL_METADATA_BYTES).then_some(bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn parse_enabled_stem(file_name: &str, ext: &str) -> Option<(bool, String)> {
|
||||
let disabled_ext = format!("{ext}.disabled");
|
||||
if let Some(stem) = file_name.strip_suffix(&disabled_ext) {
|
||||
@@ -43,7 +52,6 @@ pub(crate) fn parse_enabled_stem(file_name: &str, ext: &str) -> Option<(bool, St
|
||||
}
|
||||
}
|
||||
|
||||
// same idea but for directories, which don't have a file extension to strip
|
||||
pub(crate) fn parse_enabled_stem_dir(file_name: &str) -> (bool, String) {
|
||||
if let Some(stem) = file_name.strip_suffix(".disabled") {
|
||||
(false, stem.to_string())
|
||||
@@ -53,10 +61,7 @@ pub(crate) fn parse_enabled_stem_dir(file_name: &str) -> (bool, String) {
|
||||
}
|
||||
|
||||
pub(crate) fn read_icon_from_zip(archive: &mut zip::ZipArchive<std::fs::File>) -> Option<Vec<u8>> {
|
||||
let mut entry = archive.by_name("pack.png").ok()?;
|
||||
let mut buf = Vec::new();
|
||||
entry.read_to_end(&mut buf).ok()?;
|
||||
Some(buf)
|
||||
read_local_metadata(archive.by_name("pack.png").ok()?)
|
||||
}
|
||||
|
||||
pub(crate) fn open_zip(path: &std::path::Path) -> Option<zip::ZipArchive<std::fs::File>> {
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// mod scanning and loader-specific metadata extraction.
|
||||
// jar files are just zips, so it cracks them open looking for loader-specific
|
||||
// metadata (fabric.mod.json, quilt.mod.json, mods.toml, mcmod.info) to get
|
||||
// names, descriptions, and icons. if none of those work, falls back to common
|
||||
// root-level icon paths (logo.png, icon.png, pack.png) or just the filename.
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Deserialize;
|
||||
@@ -47,7 +40,6 @@ fn icon_path_from_value(value: &serde_json::Value) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
// quilt puts its metadata under a "metadata" sub-object
|
||||
#[derive(Deserialize, Default)]
|
||||
struct QuiltModJson {
|
||||
#[serde(default)]
|
||||
@@ -142,10 +134,6 @@ pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry>
|
||||
entries
|
||||
}
|
||||
|
||||
// tries each loader's metadata file to extract name, description, and icon.
|
||||
// checks fabric.mod.json, quilt.mod.json, META-INF/mods.toml (forge),
|
||||
// META-INF/neoforge.mods.toml, and mcmod.info (legacy forge). if none of
|
||||
// those yield an icon, falls back to common root-level paths.
|
||||
fn read_mod_metadata(jar_path: &Path) -> (String, String, String, Option<Vec<u8>>) {
|
||||
let file = match std::fs::File::open(jar_path) {
|
||||
Ok(file) => file,
|
||||
@@ -197,7 +185,6 @@ fn read_mod_metadata(jar_path: &Path) -> (String, String, String, Option<Vec<u8>
|
||||
}
|
||||
}
|
||||
|
||||
// no recognized metadata at all, try common icon paths
|
||||
let icon_bytes = try_fallback_icons(&mut archive);
|
||||
tracing::trace!(
|
||||
"No recognized mod metadata in {}; fallback_icon={}",
|
||||
@@ -224,9 +211,10 @@ fn try_fallback_icons(archive: &mut zip::ZipArchive<std::fs::File>) -> Option<Ve
|
||||
fn read_fabric_meta(
|
||||
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||
) -> Option<(String, String, String, String)> {
|
||||
let mut entry = archive.by_name("fabric.mod.json").ok()?;
|
||||
let mut raw = String::new();
|
||||
entry.read_to_string(&mut raw).ok()?;
|
||||
let raw = String::from_utf8(super::read_local_metadata(
|
||||
archive.by_name("fabric.mod.json").ok()?,
|
||||
)?)
|
||||
.ok()?;
|
||||
let sanitized = sanitize_json_strings(&raw);
|
||||
let data: FabricModJson = serde_json::from_str(&sanitized).ok()?;
|
||||
let icon = data.icon_path();
|
||||
@@ -236,9 +224,10 @@ fn read_fabric_meta(
|
||||
fn read_quilt_meta(
|
||||
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||
) -> Option<(String, String, String, String)> {
|
||||
let mut entry = archive.by_name("quilt.mod.json").ok()?;
|
||||
let mut raw = String::new();
|
||||
entry.read_to_string(&mut raw).ok()?;
|
||||
let raw = String::from_utf8(super::read_local_metadata(
|
||||
archive.by_name("quilt.mod.json").ok()?,
|
||||
)?)
|
||||
.ok()?;
|
||||
let sanitized = sanitize_json_strings(&raw);
|
||||
let data: QuiltModJson = serde_json::from_str(&sanitized).ok()?;
|
||||
let version = data.quilt_loader.version;
|
||||
@@ -291,14 +280,13 @@ fn read_forge_toml_meta(
|
||||
Some((name, description, version, logo))
|
||||
}
|
||||
|
||||
// legacy forge mcmod.info is either a bare json array of mod entries
|
||||
// or an object with a "modList" key wrapping the array
|
||||
fn read_mcmod_info(
|
||||
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||
) -> Option<(String, String, String, String)> {
|
||||
let mut entry = archive.by_name("mcmod.info").ok()?;
|
||||
let mut raw = String::new();
|
||||
entry.read_to_string(&mut raw).ok()?;
|
||||
let raw = String::from_utf8(super::read_local_metadata(
|
||||
archive.by_name("mcmod.info").ok()?,
|
||||
)?)
|
||||
.ok()?;
|
||||
let sanitized = sanitize_json_strings(&raw);
|
||||
let parsed: serde_json::Value = serde_json::from_str(&sanitized).ok()?;
|
||||
let first = match &parsed {
|
||||
@@ -330,10 +318,7 @@ fn read_mcmod_info(
|
||||
}
|
||||
|
||||
fn read_zip_string(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> Option<String> {
|
||||
let mut entry = archive.by_name(path).ok()?;
|
||||
let mut s = String::new();
|
||||
entry.read_to_string(&mut s).ok()?;
|
||||
Some(s)
|
||||
String::from_utf8(super::read_local_metadata(archive.by_name(path).ok()?)?).ok()
|
||||
}
|
||||
|
||||
// some mod authors put raw newlines/tabs inside json string values which is
|
||||
@@ -374,10 +359,7 @@ fn sanitize_json_strings(input: &str) -> String {
|
||||
}
|
||||
|
||||
fn read_zip_bytes(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> Option<Vec<u8>> {
|
||||
let mut entry = archive.by_name(path).ok()?;
|
||||
let mut bytes = Vec::new();
|
||||
entry.read_to_end(&mut bytes).ok()?;
|
||||
Some(bytes)
|
||||
super::read_local_metadata(archive.by_name(path).ok()?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// shared pack.mcmeta scanning for resource packs and shader packs.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Deserialize;
|
||||
@@ -112,7 +110,8 @@ fn read_metadata_from_zip(path: &Path) -> (String, Option<Vec<u8>>) {
|
||||
let description = archive
|
||||
.by_name("pack.mcmeta")
|
||||
.ok()
|
||||
.and_then(|entry| serde_json::from_reader::<_, PackMcMeta>(entry).ok())
|
||||
.and_then(super::read_local_metadata)
|
||||
.and_then(|bytes| serde_json::from_slice::<PackMcMeta>(&bytes).ok())
|
||||
.map(|meta| extract_description(&meta.pack.description))
|
||||
.unwrap_or_default();
|
||||
let icon_bytes = super::read_icon_from_zip(&mut archive);
|
||||
@@ -120,10 +119,16 @@ fn read_metadata_from_zip(path: &Path) -> (String, Option<Vec<u8>>) {
|
||||
}
|
||||
|
||||
fn read_metadata_from_dir(path: &Path) -> (String, Option<Vec<u8>>) {
|
||||
let description = std::fs::read_to_string(path.join("pack.mcmeta"))
|
||||
let description = std::fs::File::open(path.join("pack.mcmeta"))
|
||||
.ok()
|
||||
.and_then(|content| serde_json::from_str::<PackMcMeta>(&content).ok())
|
||||
.and_then(super::read_local_metadata)
|
||||
.and_then(|bytes| serde_json::from_slice::<PackMcMeta>(&bytes).ok())
|
||||
.map(|meta| extract_description(&meta.pack.description))
|
||||
.unwrap_or_default();
|
||||
(description, std::fs::read(path.join("pack.png")).ok())
|
||||
(
|
||||
description,
|
||||
std::fs::File::open(path.join("pack.png"))
|
||||
.ok()
|
||||
.and_then(super::read_local_metadata),
|
||||
)
|
||||
}
|
||||
@@ -9,6 +9,45 @@ use crate::instance::content::manifest::{ContentKind, FileFingerprint, ProviderP
|
||||
use crate::instance::{InstanceConfig, ModLoader};
|
||||
use crate::net::modrinth::{DiscoveryResults, VersionInfo};
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DiscoverySort {
|
||||
#[default]
|
||||
Relevance,
|
||||
Downloads,
|
||||
Popular,
|
||||
Updated,
|
||||
Newest,
|
||||
Released,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct DiscoverySearchFilters {
|
||||
pub game_versions: Vec<String>,
|
||||
pub excluded_versions: Vec<String>,
|
||||
pub included_categories: Vec<String>,
|
||||
pub excluded_categories: Vec<String>,
|
||||
}
|
||||
|
||||
impl DiscoverySort {
|
||||
pub const ALL: [Self; 5] = [
|
||||
Self::Relevance,
|
||||
Self::Popular,
|
||||
Self::Newest,
|
||||
Self::Downloads,
|
||||
Self::Updated,
|
||||
];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Relevance => "Best match",
|
||||
Self::Downloads => "Downloads",
|
||||
Self::Popular => "Popularity",
|
||||
Self::Updated => "Updates",
|
||||
Self::Newest | Self::Released => "Release date",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FingerprintQuery {
|
||||
pub key: String,
|
||||
@@ -22,15 +61,23 @@ pub struct ResolvedFile {
|
||||
pub project: ProviderProject,
|
||||
}
|
||||
|
||||
#[allow(
|
||||
clippy::double_must_use,
|
||||
reason = "async_trait adds #[must_use] to generated futures"
|
||||
)]
|
||||
#[async_trait]
|
||||
pub trait ContentProvider: Send + Sync {
|
||||
fn id(&self) -> &'static str;
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn search(
|
||||
&self,
|
||||
kind: ContentKind,
|
||||
query: &str,
|
||||
instance: &InstanceConfig,
|
||||
filters: &DiscoverySearchFilters,
|
||||
sort: DiscoverySort,
|
||||
reversed: bool,
|
||||
offset: usize,
|
||||
limit: usize,
|
||||
) -> Result<DiscoveryResults, crate::net::NetError>;
|
||||
@@ -38,6 +85,9 @@ pub trait ContentProvider: Send + Sync {
|
||||
async fn search_modpacks(
|
||||
&self,
|
||||
query: &str,
|
||||
filters: &DiscoverySearchFilters,
|
||||
sort: DiscoverySort,
|
||||
reversed: bool,
|
||||
offset: usize,
|
||||
limit: usize,
|
||||
) -> Result<DiscoveryResults, crate::net::NetError>;
|
||||
@@ -94,6 +144,9 @@ impl ContentProvider for ModrinthProvider {
|
||||
kind: ContentKind,
|
||||
query: &str,
|
||||
instance: &InstanceConfig,
|
||||
filters: &DiscoverySearchFilters,
|
||||
sort: DiscoverySort,
|
||||
reversed: bool,
|
||||
offset: usize,
|
||||
limit: usize,
|
||||
) -> Result<DiscoveryResults, crate::net::NetError> {
|
||||
@@ -101,8 +154,10 @@ impl ContentProvider for ModrinthProvider {
|
||||
&self.client,
|
||||
kind,
|
||||
query,
|
||||
&instance.game_version,
|
||||
filters,
|
||||
instance.loader,
|
||||
sort,
|
||||
reversed,
|
||||
offset,
|
||||
limit,
|
||||
)
|
||||
@@ -112,10 +167,22 @@ impl ContentProvider for ModrinthProvider {
|
||||
async fn search_modpacks(
|
||||
&self,
|
||||
query: &str,
|
||||
filters: &DiscoverySearchFilters,
|
||||
sort: DiscoverySort,
|
||||
reversed: bool,
|
||||
offset: usize,
|
||||
limit: usize,
|
||||
) -> Result<DiscoveryResults, crate::net::NetError> {
|
||||
crate::net::modrinth::search_modpacks(&self.client, query, offset, limit).await
|
||||
crate::net::modrinth::search_modpacks(
|
||||
&self.client,
|
||||
query,
|
||||
filters,
|
||||
sort,
|
||||
reversed,
|
||||
offset,
|
||||
limit,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn resolve_files(
|
||||
@@ -235,6 +302,9 @@ impl ContentProvider for CurseForgeProvider {
|
||||
kind: ContentKind,
|
||||
query: &str,
|
||||
instance: &InstanceConfig,
|
||||
filters: &DiscoverySearchFilters,
|
||||
sort: DiscoverySort,
|
||||
reversed: bool,
|
||||
offset: usize,
|
||||
limit: usize,
|
||||
) -> Result<DiscoveryResults, crate::net::NetError> {
|
||||
@@ -243,8 +313,11 @@ impl ContentProvider for CurseForgeProvider {
|
||||
&self.api_key,
|
||||
kind,
|
||||
query,
|
||||
&instance.game_version,
|
||||
&filters.game_versions,
|
||||
instance.loader,
|
||||
&filters.included_categories,
|
||||
sort,
|
||||
reversed,
|
||||
offset,
|
||||
limit,
|
||||
)
|
||||
@@ -254,11 +327,24 @@ impl ContentProvider for CurseForgeProvider {
|
||||
async fn search_modpacks(
|
||||
&self,
|
||||
query: &str,
|
||||
filters: &DiscoverySearchFilters,
|
||||
sort: DiscoverySort,
|
||||
reversed: bool,
|
||||
offset: usize,
|
||||
limit: usize,
|
||||
) -> Result<DiscoveryResults, crate::net::NetError> {
|
||||
crate::net::curseforge::search_modpacks(&self.client, &self.api_key, query, offset, limit)
|
||||
.await
|
||||
crate::net::curseforge::search_modpacks(
|
||||
&self.client,
|
||||
&self.api_key,
|
||||
query,
|
||||
&filters.game_versions,
|
||||
&filters.included_categories,
|
||||
sort,
|
||||
reversed,
|
||||
offset,
|
||||
limit,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn resolve_files(
|
||||
@@ -380,9 +466,10 @@ pub struct ProviderRegistry {
|
||||
pub(crate) fn newest_version(versions: &[VersionInfo]) -> Option<&VersionInfo> {
|
||||
let first = versions.first()?;
|
||||
Some(versions.iter().fold(first, |newest, version| {
|
||||
match (published_at(version), published_at(newest)) {
|
||||
(Some(candidate), Some(current)) if candidate > current => version,
|
||||
_ => newest,
|
||||
if published_at(version) > published_at(newest) {
|
||||
version
|
||||
} else {
|
||||
newest
|
||||
}
|
||||
}))
|
||||
}
|
||||
@@ -401,6 +488,12 @@ fn published_at(version: &VersionInfo) -> Option<chrono::DateTime<chrono::FixedO
|
||||
chrono::DateTime::parse_from_rfc3339(&version.date_published).ok()
|
||||
}
|
||||
|
||||
/// Keep provider order for equal or missing dates. Mod version names are
|
||||
/// arbitrary labels, not necessarily comparable version numbers.
|
||||
pub(crate) fn sort_versions_newest_first(versions: &mut [VersionInfo]) {
|
||||
versions.sort_by_cached_key(|version| std::cmp::Reverse(published_at(version)));
|
||||
}
|
||||
|
||||
pub(crate) fn has_newer_compatible_version(
|
||||
versions: &[VersionInfo],
|
||||
installed_version_id: &str,
|
||||
|
||||
+231
-129
@@ -4,13 +4,13 @@
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use super::local::{current_fingerprint, directory_fingerprint_metadata, relative_path};
|
||||
use crate::feedback::progress::{ProgressTask, ProgressTaskHandle};
|
||||
use crate::instance::InstanceConfig;
|
||||
use crate::instance::content::manifest::{
|
||||
ContentFileRecord, ContentKind, ContentManifest, FileFingerprint, ProviderProject, Resolution,
|
||||
fingerprint, fingerprint_metadata,
|
||||
ContentFileRecord, ContentKind, ContentLock, ContentManifest, ManifestError, ProviderProject,
|
||||
Resolution, fingerprint, fingerprint_metadata,
|
||||
};
|
||||
use crate::instance::content::provider::{FingerprintQuery, ProviderRegistry};
|
||||
use crate::storage::InstancePaths;
|
||||
@@ -20,6 +20,7 @@ pub struct ReconcileResult {
|
||||
pub instance_name: String,
|
||||
pub instance_created: chrono::DateTime<chrono::Utc>,
|
||||
pub manifest: ContentManifest,
|
||||
pub complete: bool,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
@@ -118,14 +119,15 @@ async fn reconcile_worker() {
|
||||
};
|
||||
let instance = (job.instance.name.clone(), job.instance.created);
|
||||
let rerun_job = job.clone();
|
||||
let result = reconcile(job, &task).await;
|
||||
if let Ok(mut results) = PENDING_RECONCILIATIONS.lock() {
|
||||
results.retain(|pending| {
|
||||
(pending.instance_name.as_str(), pending.instance_created)
|
||||
!= (instance.0.as_str(), instance.1)
|
||||
});
|
||||
results.push(result);
|
||||
}
|
||||
let result = reconcile(
|
||||
job.instance,
|
||||
job.instances_dir,
|
||||
job.client,
|
||||
&task,
|
||||
publish_reconciliation,
|
||||
)
|
||||
.await;
|
||||
publish_reconciliation(result);
|
||||
if let Ok(mut coordinator) = RECONCILE_COORDINATOR.lock() {
|
||||
if coordinator.rerun.remove(&instance) {
|
||||
coordinator.queue.push_back(rerun_job);
|
||||
@@ -133,19 +135,30 @@ async fn reconcile_worker() {
|
||||
coordinator.scheduled.remove(&instance);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn publish_reconciliation(result: ReconcileResult) {
|
||||
if let Ok(mut results) = PENDING_RECONCILIATIONS.lock() {
|
||||
results.retain(|pending| {
|
||||
pending.instance_name != result.instance_name
|
||||
|| pending.instance_created != result.instance_created
|
||||
});
|
||||
results.push(result);
|
||||
crate::feedback::request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult {
|
||||
let ReconcileJob {
|
||||
instance,
|
||||
instances_dir,
|
||||
client,
|
||||
} = job;
|
||||
pub(crate) async fn reconcile(
|
||||
instance: InstanceConfig,
|
||||
instances_dir: PathBuf,
|
||||
client: crate::net::HttpClient,
|
||||
task: &ProgressTask,
|
||||
mut publish: impl FnMut(ReconcileResult),
|
||||
) -> ReconcileResult {
|
||||
let instance_name = instance.name;
|
||||
let instance_created = instance.created;
|
||||
task.set_action(format!("Checking content for {instance_name}"));
|
||||
task.set_action("Checking content");
|
||||
task.set_sub_action("Reading saved content index");
|
||||
task.set_progress(0, 1);
|
||||
let paths = InstancePaths::new(instances_dir.join(&instance_name));
|
||||
@@ -174,64 +187,113 @@ async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult {
|
||||
|
||||
match inventory {
|
||||
Ok(Ok((mut inventory, manifest_path))) => {
|
||||
let registry = ProviderRegistry::configured(client);
|
||||
task.set_action(format!("Identifying content for {instance_name}"));
|
||||
task.set_sub_action(format!("{} file(s) need matching", inventory.queries.len()));
|
||||
if !inventory.queries.is_empty() {
|
||||
task.set_progress(0, inventory.queries.len() as u64);
|
||||
let resolution_result = if inventory.queries.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
let registry = ProviderRegistry::configured(client);
|
||||
task.set_action("Identifying content");
|
||||
resolve_queries(
|
||||
®istry,
|
||||
&inventory.queries,
|
||||
&mut inventory.manifest,
|
||||
&task.handle(),
|
||||
)
|
||||
.await
|
||||
};
|
||||
let changed = inventory
|
||||
.manifest
|
||||
.files
|
||||
.iter()
|
||||
.filter(|record| inventory.previous.record(&record.relative_path) != Some(record))
|
||||
.count();
|
||||
if changed > 0 {
|
||||
task.set_action("Validating content files");
|
||||
task.set_sub_action("Rechecking changed files");
|
||||
task.set_progress(0, changed as u64);
|
||||
}
|
||||
let resolution_result =
|
||||
resolve_queries(®istry, &inventory.queries, &mut inventory.manifest).await;
|
||||
if !inventory.queries.is_empty() {
|
||||
task.set_progress(
|
||||
inventory.queries.len() as u64,
|
||||
inventory.queries.len() as u64,
|
||||
);
|
||||
}
|
||||
match resolution_result {
|
||||
Ok(()) => match save_reconciled_manifest(
|
||||
publish(ReconcileResult {
|
||||
instance_name: instance_name.clone(),
|
||||
instance_created,
|
||||
manifest: inventory.manifest.clone(),
|
||||
complete: false,
|
||||
error: None,
|
||||
});
|
||||
let save_progress = task.handle();
|
||||
let saved = tokio::task::spawn_blocking(move || {
|
||||
save_reconciled_manifest(
|
||||
&manifest_path,
|
||||
&minecraft_dir,
|
||||
inventory.manifest,
|
||||
) {
|
||||
Ok(manifest) => ReconcileResult {
|
||||
instance_name,
|
||||
instance_created,
|
||||
manifest,
|
||||
error: None,
|
||||
},
|
||||
Err(error) => ReconcileResult {
|
||||
instance_name,
|
||||
instance_created,
|
||||
manifest: ContentManifest::default(),
|
||||
error: Some(error.to_string()),
|
||||
},
|
||||
},
|
||||
Err(error) => {
|
||||
let saved = save_reconciled_manifest(
|
||||
&manifest_path,
|
||||
&minecraft_dir,
|
||||
inventory.manifest,
|
||||
);
|
||||
ReconcileResult {
|
||||
instance_name,
|
||||
instance_created,
|
||||
manifest: saved.unwrap_or_default(),
|
||||
error: Some(error.to_string()),
|
||||
}
|
||||
}
|
||||
&inventory.previous,
|
||||
&save_progress,
|
||||
)
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|error| {
|
||||
Err(std::io::Error::other(format!("Content save task failed: {error}")).into())
|
||||
});
|
||||
if matches!(saved, Err(ManifestError::Busy(_))) {
|
||||
// Another operation (for example a reinstall commit) holds the
|
||||
// manifest lock. It triggers its own reconciliation when done,
|
||||
// so stay silent instead of warning on every reinstall.
|
||||
tracing::debug!(
|
||||
"Content reconciliation for {instance_name} deferred: manifest busy"
|
||||
);
|
||||
let manifest = ContentManifest::load(&paths.content_manifest()).unwrap_or_default();
|
||||
return ReconcileResult {
|
||||
instance_name,
|
||||
instance_created,
|
||||
manifest,
|
||||
complete: true,
|
||||
error: None,
|
||||
};
|
||||
}
|
||||
let error = match (resolution_result, &saved) {
|
||||
(Ok(()), Ok(_)) => None,
|
||||
(Err(error), Ok(_)) => Some(error.to_string()),
|
||||
(Ok(()), Err(error)) => Some(error.to_string()),
|
||||
(Err(error), Err(save_error)) => Some(format!(
|
||||
"Provider matching failed: {error}; could not save content inventory: {save_error}"
|
||||
)),
|
||||
};
|
||||
ReconcileResult {
|
||||
instance_name,
|
||||
instance_created,
|
||||
manifest: saved.unwrap_or_default(),
|
||||
complete: true,
|
||||
error,
|
||||
}
|
||||
}
|
||||
Ok(Err(error)) => {
|
||||
if error
|
||||
.downcast_ref::<ManifestError>()
|
||||
.is_some_and(|error| matches!(error, ManifestError::Busy(_)))
|
||||
{
|
||||
tracing::debug!(
|
||||
"Content reconciliation for {instance_name} deferred: manifest busy"
|
||||
);
|
||||
let manifest = ContentManifest::load(&paths.content_manifest()).unwrap_or_default();
|
||||
return ReconcileResult {
|
||||
instance_name,
|
||||
instance_created,
|
||||
manifest,
|
||||
complete: true,
|
||||
error: None,
|
||||
};
|
||||
}
|
||||
ReconcileResult {
|
||||
instance_name,
|
||||
instance_created,
|
||||
manifest: ContentManifest::default(),
|
||||
complete: true,
|
||||
error: Some(error.to_string()),
|
||||
}
|
||||
}
|
||||
Ok(Err(error)) => ReconcileResult {
|
||||
instance_name,
|
||||
instance_created,
|
||||
manifest: ContentManifest::default(),
|
||||
error: Some(error.to_string()),
|
||||
},
|
||||
Err(error) => ReconcileResult {
|
||||
instance_name,
|
||||
instance_created,
|
||||
manifest: ContentManifest::default(),
|
||||
complete: true,
|
||||
error: Some(error.to_string()),
|
||||
},
|
||||
}
|
||||
@@ -241,18 +303,56 @@ fn save_reconciled_manifest(
|
||||
manifest_path: &Path,
|
||||
minecraft_dir: &Path,
|
||||
reconciled: ContentManifest,
|
||||
previous: &ContentManifest,
|
||||
task: &impl InventoryProgress,
|
||||
) -> Result<ContentManifest, crate::instance::content::manifest::ManifestError> {
|
||||
let reconciled_paths = reconciled
|
||||
let records = reconciled
|
||||
.files
|
||||
.iter()
|
||||
.map(|record| record.relative_path.clone())
|
||||
.collect::<HashSet<_>>();
|
||||
.into_iter()
|
||||
.filter(|record| previous.record(&record.relative_path) != Some(record))
|
||||
.collect::<Vec<_>>();
|
||||
ContentManifest::update(manifest_path, |current| {
|
||||
current.files.retain(|record| {
|
||||
reconciled_paths.contains(&record.relative_path)
|
||||
|| minecraft_dir.join(&record.relative_path).exists()
|
||||
});
|
||||
for record in reconciled.files {
|
||||
for record in current.files.clone() {
|
||||
relative_path(minecraft_dir, &minecraft_dir.join(&record.relative_path))?;
|
||||
match std::fs::symlink_metadata(minecraft_dir.join(&record.relative_path)) {
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
current.remove(&record.relative_path)
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
}
|
||||
let total = records.len() as u64;
|
||||
task.set_progress(0, total);
|
||||
for (index, mut record) in records.into_iter().enumerate() {
|
||||
task.set_sub_action(record.relative_path.to_string_lossy().as_ref());
|
||||
task.set_progress(index as u64, total);
|
||||
let path = minecraft_dir.join(&record.relative_path);
|
||||
relative_path(minecraft_dir, &path)?;
|
||||
if current.record(&record.relative_path) != previous.record(&record.relative_path) {
|
||||
continue;
|
||||
}
|
||||
let metadata = match std::fs::symlink_metadata(&path) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
if metadata.file_type().is_symlink() {
|
||||
continue;
|
||||
}
|
||||
let fresh = current_fingerprint(&path, &record.fingerprint)?;
|
||||
if fresh != record.fingerprint {
|
||||
continue;
|
||||
}
|
||||
if let Some(existing) = current.record(&record.relative_path)
|
||||
&& existing.fingerprint == record.fingerprint
|
||||
{
|
||||
record
|
||||
.required_dependencies
|
||||
.clone_from(&existing.required_dependencies);
|
||||
record.automatic_dependency = existing.automatic_dependency;
|
||||
record.cleanup_eligible = existing.cleanup_eligible;
|
||||
}
|
||||
let keep_resolved = current
|
||||
.record(&record.relative_path)
|
||||
.is_some_and(|existing| {
|
||||
@@ -268,11 +368,13 @@ fn save_reconciled_manifest(
|
||||
current.upsert(record);
|
||||
}
|
||||
}
|
||||
task.set_progress(total, total);
|
||||
Ok(current.clone())
|
||||
})
|
||||
}
|
||||
|
||||
struct Inventory {
|
||||
previous: ContentManifest,
|
||||
manifest: ContentManifest,
|
||||
queries: Vec<FingerprintQuery>,
|
||||
}
|
||||
@@ -299,7 +401,8 @@ fn reconcile_inventory(
|
||||
max_fingerprint_size_mib: u64,
|
||||
task: &impl InventoryProgress,
|
||||
) -> Result<Inventory, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let previous = ContentManifest::load(manifest_path)?;
|
||||
let lock = ContentLock::acquire(manifest_path)?;
|
||||
let previous = lock.load()?;
|
||||
let files = content_files(minecraft_dir)?;
|
||||
let file_count = files.len() as u64;
|
||||
if file_count == 0 {
|
||||
@@ -319,7 +422,7 @@ fn reconcile_inventory(
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or("content"),
|
||||
);
|
||||
let relative_path = path.strip_prefix(minecraft_dir)?.to_path_buf();
|
||||
let relative_path = relative_path(minecraft_dir, &path)?;
|
||||
let enabled = !path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
@@ -443,7 +546,11 @@ fn reconcile_inventory(
|
||||
manifest.files.push(record);
|
||||
task.set_progress(index as u64 + 1, file_count);
|
||||
}
|
||||
Ok(Inventory { manifest, queries })
|
||||
Ok(Inventory {
|
||||
previous,
|
||||
manifest,
|
||||
queries,
|
||||
})
|
||||
}
|
||||
|
||||
fn provider_was_not_checked(record: &ContentFileRecord, provider: &str) -> bool {
|
||||
@@ -469,6 +576,7 @@ async fn resolve_queries(
|
||||
registry: &ProviderRegistry,
|
||||
queries: &[FingerprintQuery],
|
||||
manifest: &mut ContentManifest,
|
||||
task: &impl InventoryProgress,
|
||||
) -> Result<(), crate::net::NetError> {
|
||||
if queries.is_empty() {
|
||||
return Ok(());
|
||||
@@ -476,8 +584,14 @@ async fn resolve_queries(
|
||||
let mut matches: HashMap<String, Vec<ProviderProject>> = HashMap::new();
|
||||
let mut checked = Vec::new();
|
||||
let mut last_error = None;
|
||||
for provider in registry.providers() {
|
||||
let total = (queries.len() * registry.providers().len()) as u64;
|
||||
task.set_progress(0, total);
|
||||
for (index, provider) in registry.providers().iter().enumerate() {
|
||||
let provider_id = provider.id();
|
||||
task.set_sub_action(&format!(
|
||||
"{} file(s) need matching ({provider_id})",
|
||||
queries.len()
|
||||
));
|
||||
match tokio::time::timeout(
|
||||
std::time::Duration::from_secs(10),
|
||||
provider.resolve_files(queries),
|
||||
@@ -506,6 +620,7 @@ async fn resolve_queries(
|
||||
last_error = Some(format!("{provider_id} content matching timed out"));
|
||||
}
|
||||
}
|
||||
task.set_progress(((index + 1) * queries.len()) as u64, total);
|
||||
}
|
||||
if checked.is_empty() {
|
||||
return Err(crate::net::NetError::TaskFailed(last_error.unwrap_or_else(
|
||||
@@ -609,24 +724,26 @@ fn content_files(minecraft_dir: &Path) -> std::io::Result<Vec<(ContentKind, Path
|
||||
ContentKind::Shader,
|
||||
] {
|
||||
let directory = minecraft_dir.join(kind.directory());
|
||||
let Ok(entries) = std::fs::read_dir(directory) else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let entries = read_content_directory(&directory)?;
|
||||
for entry in entries {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
if supported_content_path(kind, &path) {
|
||||
if supported_content_path(kind, &path)? {
|
||||
files.push((kind, path));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(worlds) = std::fs::read_dir(minecraft_dir.join("saves")) {
|
||||
for world in worlds.flatten().filter(|entry| entry.path().is_dir()) {
|
||||
let Ok(entries) = std::fs::read_dir(world.path().join("datapacks")) else {
|
||||
{
|
||||
for world in read_content_directory(&minecraft_dir.join("saves"))? {
|
||||
let world = world?;
|
||||
if !world.file_type()?.is_dir() {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
}
|
||||
let entries = read_content_directory(&world.path().join("datapacks"))?;
|
||||
for entry in entries {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
if supported_content_path(ContentKind::DataPack, &path) {
|
||||
if supported_content_path(ContentKind::DataPack, &path)? {
|
||||
files.push((ContentKind::DataPack, path));
|
||||
}
|
||||
}
|
||||
@@ -636,55 +753,40 @@ fn content_files(minecraft_dir: &Path) -> std::io::Result<Vec<(ContentKind, Path
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn supported_content_path(kind: ContentKind, path: &Path) -> bool {
|
||||
if path.is_dir() {
|
||||
return matches!(
|
||||
fn read_content_directory(
|
||||
path: &Path,
|
||||
) -> std::io::Result<impl Iterator<Item = std::io::Result<std::fs::DirEntry>> + use<>> {
|
||||
match std::fs::read_dir(path) {
|
||||
Ok(entries) => Ok(Some(entries).into_iter().flatten()),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
Ok(None.into_iter().flatten())
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
fn supported_content_path(kind: ContentKind, path: &Path) -> std::io::Result<bool> {
|
||||
let metadata = std::fs::symlink_metadata(path)?;
|
||||
if metadata.file_type().is_symlink() {
|
||||
return Ok(false);
|
||||
}
|
||||
if metadata.is_dir() {
|
||||
return Ok(matches!(
|
||||
kind,
|
||||
ContentKind::ResourcePack | ContentKind::Shader | ContentKind::DataPack
|
||||
);
|
||||
));
|
||||
}
|
||||
if !path.is_file() {
|
||||
return false;
|
||||
if !metadata.is_file() {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
|
||||
return false;
|
||||
return Ok(false);
|
||||
};
|
||||
match kind {
|
||||
Ok(match kind {
|
||||
ContentKind::Mod => name.ends_with(".jar") || name.ends_with(".jar.disabled"),
|
||||
ContentKind::ResourcePack | ContentKind::Shader | ContentKind::DataPack => {
|
||||
name.ends_with(".zip") || name.ends_with(".zip.disabled")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn directory_fingerprint_metadata(path: &Path) -> Result<FileFingerprint, std::io::Error> {
|
||||
fn accumulate(path: &Path, size: &mut u64, modified_ns: &mut u128) -> std::io::Result<()> {
|
||||
for entry in std::fs::read_dir(path)? {
|
||||
let entry = entry?;
|
||||
let metadata = entry.metadata()?;
|
||||
let modified = metadata
|
||||
.modified()
|
||||
.unwrap_or(SystemTime::UNIX_EPOCH)
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_nanos();
|
||||
*modified_ns = (*modified_ns).max(modified);
|
||||
if metadata.is_dir() {
|
||||
accumulate(&entry.path(), size, modified_ns)?;
|
||||
} else if metadata.is_file() {
|
||||
*size = size.saturating_add(metadata.len());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
let mut size = 0;
|
||||
let mut modified_ns = 0;
|
||||
accumulate(path, &mut size, &mut modified_ns)?;
|
||||
Ok(FileFingerprint {
|
||||
size,
|
||||
modified_ns,
|
||||
hashes: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// resource pack scanner backed by the shared pack.mcmeta reader.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use super::entry::ContentEntry;
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// shader pack scanner backed by the shared pack.mcmeta reader.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use super::entry::ContentEntry;
|
||||
|
||||
+436
-213
@@ -1,6 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -82,6 +83,24 @@ pub struct BulkUpdatePlan {
|
||||
pub static PENDING_UPDATE_SNAPSHOTS: LazyLock<Arc<Mutex<Vec<PendingUpdateSnapshot>>>> =
|
||||
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
|
||||
|
||||
struct RunningCheck {
|
||||
instance: InstanceConfig,
|
||||
inventory: Vec<ProviderProject>,
|
||||
task: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl RunningCheck {
|
||||
fn matches(&self, instance: &InstanceConfig, manifest: &ContentManifest) -> bool {
|
||||
self.instance.created == instance.created
|
||||
&& self.instance.game_version == instance.game_version
|
||||
&& self.instance.loader == instance.loader
|
||||
&& self.inventory == resolved_inventory(manifest)
|
||||
}
|
||||
}
|
||||
|
||||
static RUNNING_CHECKS: LazyLock<Mutex<HashMap<std::path::PathBuf, RunningCheck>>> =
|
||||
LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
impl UpdateSnapshot {
|
||||
pub fn load(path: &std::path::Path) -> Option<Self> {
|
||||
std::fs::read(path)
|
||||
@@ -109,17 +128,6 @@ impl UpdateSnapshot {
|
||||
>= RECHECK_AFTER_SECONDS
|
||||
}
|
||||
|
||||
/// Keeps known updates for entries whose check failed this round so a flaky
|
||||
/// network or a rate limited provider does not drop labels that were correct.
|
||||
fn carry_over(&mut self, previous: &Self) {
|
||||
for failure in &self.failures {
|
||||
if let Some(update) = previous.update_for(&failure.installed) {
|
||||
self.updates.push(update.clone());
|
||||
}
|
||||
}
|
||||
sort_updates(&mut self.updates);
|
||||
}
|
||||
|
||||
pub fn update_for(&self, installed: &ProviderProject) -> Option<&AvailableUpdate> {
|
||||
self.updates.iter().find(|update| {
|
||||
update.installed.provider == installed.provider
|
||||
@@ -129,31 +137,171 @@ impl UpdateSnapshot {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spawn(instance: InstanceConfig, manifest: ContentManifest, path: std::path::PathBuf) {
|
||||
tokio::spawn(async move {
|
||||
let previous =
|
||||
UpdateSnapshot::load(&path).filter(|previous| previous.applies_to(&instance));
|
||||
let mut snapshot = scan(&instance, &manifest).await;
|
||||
if let Some(previous) = previous {
|
||||
snapshot.carry_over(&previous);
|
||||
}
|
||||
if let Ok(bytes) = serde_json::to_vec_pretty(&snapshot)
|
||||
&& let Err(error) = crate::storage::write_atomic(&path, &bytes)
|
||||
{
|
||||
tracing::debug!("Could not cache content update snapshot: {error}");
|
||||
}
|
||||
if let Ok(mut pending) = PENDING_UPDATE_SNAPSHOTS.lock() {
|
||||
pending.push(PendingUpdateSnapshot {
|
||||
instance_name: instance.name,
|
||||
instance_created: instance.created,
|
||||
snapshot,
|
||||
});
|
||||
crate::feedback::request_redraw();
|
||||
pub fn spawn(
|
||||
instance: InstanceConfig,
|
||||
manifest: ContentManifest,
|
||||
path: std::path::PathBuf,
|
||||
priority: Vec<ProviderProject>,
|
||||
previous: Option<UpdateSnapshot>,
|
||||
) {
|
||||
spawn_with_registry(
|
||||
instance,
|
||||
manifest,
|
||||
path,
|
||||
priority,
|
||||
previous,
|
||||
Arc::new(super::provider::ProviderRegistry::configured(
|
||||
crate::net::HttpClient::new(),
|
||||
)),
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn is_running(
|
||||
instance: &InstanceConfig,
|
||||
manifest: &ContentManifest,
|
||||
path: &std::path::Path,
|
||||
) -> bool {
|
||||
RUNNING_CHECKS.lock().is_ok_and(|checks| {
|
||||
checks
|
||||
.get(path)
|
||||
.is_some_and(|check| !check.task.is_finished() && check.matches(instance, manifest))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn cancel(path: Option<&std::path::Path>) {
|
||||
if let Ok(mut checks) = RUNNING_CHECKS.lock() {
|
||||
checks.retain(|check_path, check| {
|
||||
if path.is_none_or(|path| path == check_path) {
|
||||
check.task.abort();
|
||||
if let Ok(mut pending) = PENDING_UPDATE_SNAPSHOTS.lock() {
|
||||
pending.retain(|pending| {
|
||||
pending.instance_name != check.instance.name
|
||||
|| pending.instance_created != check.instance.created
|
||||
});
|
||||
}
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn spawn_with_registry(
|
||||
instance: InstanceConfig,
|
||||
manifest: ContentManifest,
|
||||
path: std::path::PathBuf,
|
||||
priority: Vec<ProviderProject>,
|
||||
previous: Option<UpdateSnapshot>,
|
||||
registry: Arc<super::provider::ProviderRegistry>,
|
||||
) -> bool {
|
||||
let Ok(mut checks) = RUNNING_CHECKS.lock() else {
|
||||
return false;
|
||||
};
|
||||
if let Some(check) = checks.get(&path) {
|
||||
if !check.task.is_finished() && check.matches(&instance, &manifest) {
|
||||
return false;
|
||||
}
|
||||
check.task.abort();
|
||||
}
|
||||
let check_path = path.clone();
|
||||
let check_instance = instance.clone();
|
||||
let inventory = resolved_inventory(&manifest);
|
||||
let task = tokio::spawn(async move {
|
||||
let previous = previous
|
||||
.or_else(|| UpdateSnapshot::load(&path))
|
||||
.filter(|previous| previous.applies_to(&instance));
|
||||
let snapshot = scan_with_registry(
|
||||
&instance,
|
||||
&manifest,
|
||||
&priority,
|
||||
registry,
|
||||
previous.as_ref(),
|
||||
|snapshot| publish_current_snapshot(&instance, snapshot.clone(), &path, false),
|
||||
)
|
||||
.await;
|
||||
publish_current_snapshot(&instance, snapshot, &path, true);
|
||||
});
|
||||
checks.insert(
|
||||
check_path,
|
||||
RunningCheck {
|
||||
instance: check_instance,
|
||||
inventory,
|
||||
task,
|
||||
},
|
||||
);
|
||||
true
|
||||
}
|
||||
|
||||
fn publish_current_snapshot(
|
||||
instance: &InstanceConfig,
|
||||
snapshot: UpdateSnapshot,
|
||||
path: &std::path::Path,
|
||||
complete: bool,
|
||||
) {
|
||||
let Ok(checks) = RUNNING_CHECKS.lock() else {
|
||||
return;
|
||||
};
|
||||
if checks
|
||||
.get(path)
|
||||
.is_none_or(|check| check.task.id() != tokio::task::id())
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Hold the check registry through persistence and publication so a replaced
|
||||
// worker cannot overwrite its successor's snapshot.
|
||||
if complete
|
||||
&& let Ok(bytes) = serde_json::to_vec_pretty(&snapshot)
|
||||
&& let Err(error) = crate::storage::write_atomic(path, &bytes)
|
||||
{
|
||||
tracing::debug!("Could not cache content update snapshot: {error}");
|
||||
}
|
||||
publish_snapshot(instance, snapshot);
|
||||
}
|
||||
|
||||
fn publish_snapshot(instance: &InstanceConfig, snapshot: UpdateSnapshot) {
|
||||
if let Ok(mut pending) = PENDING_UPDATE_SNAPSHOTS.lock() {
|
||||
pending.retain(|pending| {
|
||||
pending.instance_name != instance.name
|
||||
|| pending.instance_created != instance.created
|
||||
|| pending.snapshot.game_version != snapshot.game_version
|
||||
|| pending.snapshot.loader != snapshot.loader
|
||||
});
|
||||
pending.push(PendingUpdateSnapshot {
|
||||
instance_name: instance.name.clone(),
|
||||
instance_created: instance.created,
|
||||
snapshot,
|
||||
});
|
||||
crate::feedback::request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn scan(instance: &InstanceConfig, manifest: &ContentManifest) -> UpdateSnapshot {
|
||||
scan_with_registry(
|
||||
instance,
|
||||
manifest,
|
||||
&[],
|
||||
Arc::new(super::provider::ProviderRegistry::configured(
|
||||
crate::net::HttpClient::new(),
|
||||
)),
|
||||
None,
|
||||
|_| {},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn scan_with_registry(
|
||||
instance: &InstanceConfig,
|
||||
manifest: &ContentManifest,
|
||||
priority: &[ProviderProject],
|
||||
registry: Arc<super::provider::ProviderRegistry>,
|
||||
previous: Option<&UpdateSnapshot>,
|
||||
mut publish: impl FnMut(&UpdateSnapshot),
|
||||
) -> UpdateSnapshot {
|
||||
let previous = previous.filter(|snapshot| snapshot.applies_to(instance));
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
let reusable =
|
||||
previous.filter(|snapshot| now.saturating_sub(snapshot.checked_at) < RECHECK_AFTER_SECONDS);
|
||||
let mut projects = manifest
|
||||
.files
|
||||
.iter()
|
||||
@@ -176,92 +324,136 @@ pub async fn scan(instance: &InstanceConfig, manifest: &ContentManifest) -> Upda
|
||||
&& left.0.project_id == right.0.project_id
|
||||
&& left.0.version_id == right.0.version_id
|
||||
});
|
||||
let inventory = projects
|
||||
let inventory = resolved_inventory(manifest);
|
||||
let priority = priority
|
||||
.iter()
|
||||
.map(|(project, _)| project.clone())
|
||||
.collect();
|
||||
|
||||
let slots = Arc::new(tokio::sync::Semaphore::new(8));
|
||||
// one registry (and therefore one pooled http client) for the whole scan
|
||||
let registry = Arc::new(
|
||||
crate::instance::content::provider::ProviderRegistry::configured(
|
||||
crate::net::HttpClient::new(),
|
||||
),
|
||||
);
|
||||
let mut tasks = tokio::task::JoinSet::new();
|
||||
for (installed, kind) in projects {
|
||||
let slots = slots.clone();
|
||||
let registry = registry.clone();
|
||||
let game_version = instance.game_version.clone();
|
||||
let loader = instance.loader;
|
||||
tasks.spawn(async move {
|
||||
let result = async {
|
||||
let _permit = slots
|
||||
.acquire_owned()
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
let provider = registry.get(&installed.provider).ok_or_else(|| {
|
||||
format!("{} content provider is unavailable", installed.provider)
|
||||
})?;
|
||||
let versions = provider
|
||||
.compatible_versions(&installed.project_id, kind, &game_version, loader)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
let Some(newest) = crate::instance::content::provider::newest_version(&versions)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
// a modpack pins files that are often not tagged for the exact
|
||||
// game version of the instance, so the installed version can be
|
||||
// missing from the compatible list. asking the provider for it
|
||||
// directly is the only way to tell "up to date" from "unknown".
|
||||
let current = match versions
|
||||
.enumerate()
|
||||
.rev()
|
||||
.map(|(index, project)| {
|
||||
(
|
||||
(&project.provider, &project.project_id, &project.version_id),
|
||||
index,
|
||||
)
|
||||
})
|
||||
.collect::<HashMap<_, _>>();
|
||||
projects.sort_by_key(|(project, _)| {
|
||||
priority
|
||||
.get(&(&project.provider, &project.project_id, &project.version_id))
|
||||
.copied()
|
||||
.unwrap_or(usize::MAX)
|
||||
});
|
||||
let mut snapshot = UpdateSnapshot {
|
||||
game_version: instance.game_version.clone(),
|
||||
loader: instance.loader,
|
||||
inventory,
|
||||
checked_at: 0,
|
||||
updates: previous
|
||||
.into_iter()
|
||||
.flat_map(|previous| previous.updates.iter())
|
||||
.filter(|update| {
|
||||
projects
|
||||
.iter()
|
||||
.find(|version| version.id == installed.version_id)
|
||||
{
|
||||
Some(current) => current.clone(),
|
||||
None => provider
|
||||
.version(&installed.version_id)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?,
|
||||
};
|
||||
let target = crate::instance::content::provider::is_newer(newest, ¤t)
|
||||
.then(|| newest.clone());
|
||||
Ok::<_, String>(target.map(|target| (Some(current), target)))
|
||||
}
|
||||
.await;
|
||||
(installed, kind, result)
|
||||
});
|
||||
.any(|(installed, _)| installed == &update.installed)
|
||||
})
|
||||
.cloned()
|
||||
.collect(),
|
||||
failures: Vec::new(),
|
||||
};
|
||||
projects.retain(|(installed, _)| {
|
||||
reusable.is_none_or(|snapshot| {
|
||||
!snapshot.inventory.contains(installed)
|
||||
|| snapshot
|
||||
.failures
|
||||
.iter()
|
||||
.any(|failure| &failure.installed == installed)
|
||||
})
|
||||
});
|
||||
// Reusing old results must not extend their freshness on each inventory change.
|
||||
let checked_at = reusable.map_or(now, |snapshot| snapshot.checked_at);
|
||||
if projects.is_empty() {
|
||||
snapshot.checked_at = checked_at;
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
let mut updates = Vec::new();
|
||||
let mut failures = Vec::new();
|
||||
while let Some(result) = tasks.join_next().await {
|
||||
let total = projects.len() as u64;
|
||||
let progress = crate::feedback::progress::ProgressTask::start("Checking content updates");
|
||||
progress.set_progress(0, total);
|
||||
let mut completed = 0;
|
||||
let mut projects = projects.into_iter();
|
||||
let mut tasks = tokio::task::JoinSet::new();
|
||||
loop {
|
||||
while tasks.len() < 8 {
|
||||
let Some((installed, kind)) = projects.next() else {
|
||||
break;
|
||||
};
|
||||
let registry = registry.clone();
|
||||
let game_version = instance.game_version.clone();
|
||||
let loader = instance.loader;
|
||||
tasks.spawn(async move {
|
||||
let result = async {
|
||||
let provider = registry.get(&installed.provider).ok_or_else(|| {
|
||||
format!("{} content provider is unavailable", installed.provider)
|
||||
})?;
|
||||
let versions = provider
|
||||
.compatible_versions(&installed.project_id, kind, &game_version, loader)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
let Some(newest) =
|
||||
crate::instance::content::provider::newest_version(&versions)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
// Packs can pin versions omitted from the compatible list.
|
||||
let current = match versions
|
||||
.iter()
|
||||
.find(|version| version.id == installed.version_id)
|
||||
{
|
||||
Some(current) => current.clone(),
|
||||
None => provider
|
||||
.version(&installed.version_id)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?,
|
||||
};
|
||||
let target =
|
||||
super::provider::is_newer(newest, ¤t).then(|| newest.clone());
|
||||
Ok::<_, String>(target.map(|target| (Some(current), target)))
|
||||
}
|
||||
.await;
|
||||
(installed, kind, result)
|
||||
});
|
||||
}
|
||||
let Some(result) = tasks.join_next().await else {
|
||||
break;
|
||||
};
|
||||
if let Ok((installed, _, Ok(_))) = &result {
|
||||
snapshot
|
||||
.updates
|
||||
.retain(|update| &update.installed != installed);
|
||||
}
|
||||
match result {
|
||||
Ok((installed, kind, Ok(Some((current, target))))) => updates.push(AvailableUpdate {
|
||||
installed,
|
||||
current,
|
||||
target,
|
||||
kind,
|
||||
}),
|
||||
Ok((installed, kind, Ok(Some((current, target))))) => {
|
||||
snapshot.updates.push(AvailableUpdate {
|
||||
installed,
|
||||
current,
|
||||
target,
|
||||
kind,
|
||||
})
|
||||
}
|
||||
Ok((_, _, Ok(None))) => {}
|
||||
Ok((installed, kind, Err(reason))) => failures.push(UpdateCheckFailure {
|
||||
Ok((installed, kind, Err(reason))) => snapshot.failures.push(UpdateCheckFailure {
|
||||
installed,
|
||||
kind,
|
||||
reason,
|
||||
}),
|
||||
Err(error) => tracing::debug!("Content update task failed: {error}"),
|
||||
}
|
||||
completed += 1;
|
||||
progress.set_sub_action(format!("{completed}/{total} item(s) checked"));
|
||||
progress.set_progress(completed, total);
|
||||
publish(&snapshot);
|
||||
}
|
||||
sort_updates(&mut updates);
|
||||
UpdateSnapshot {
|
||||
game_version: instance.game_version.clone(),
|
||||
loader: instance.loader,
|
||||
inventory,
|
||||
checked_at: chrono::Utc::now().timestamp(),
|
||||
updates,
|
||||
failures,
|
||||
}
|
||||
sort_updates(&mut snapshot.updates);
|
||||
snapshot.checked_at = checked_at;
|
||||
snapshot
|
||||
}
|
||||
|
||||
fn sort_updates(updates: &mut [AvailableUpdate]) {
|
||||
@@ -293,83 +485,153 @@ pub async fn plan_bulk(
|
||||
manifest: &ContentManifest,
|
||||
minecraft_dir: &std::path::Path,
|
||||
requests: Vec<UpdateRequest>,
|
||||
mut conflicts: Vec<UpdateConflict>,
|
||||
conflicts: Vec<UpdateConflict>,
|
||||
progress: Option<&crate::feedback::progress::ProgressTaskHandle>,
|
||||
) -> BulkUpdatePlan {
|
||||
let registry = crate::instance::content::provider::ProviderRegistry::configured(
|
||||
crate::net::HttpClient::new(),
|
||||
);
|
||||
let projected_manifest = project_updates(manifest, minecraft_dir, &requests);
|
||||
let mut accepted = Vec::new();
|
||||
let mut roots = Vec::new();
|
||||
for request in requests {
|
||||
let root = InstallRoot {
|
||||
provider: request.update.installed.provider.clone(),
|
||||
project_id: request.update.installed.project_id.clone(),
|
||||
title: request.title.clone(),
|
||||
version: request.update.target.clone(),
|
||||
installed_path: Some(request.installed_path.clone()),
|
||||
kind: request.update.kind,
|
||||
target_world: request.target_world.clone(),
|
||||
force_reinstall: false,
|
||||
};
|
||||
let mut resolution_manifest = projected_manifest.clone();
|
||||
if let Ok(relative_path) = request.installed_path.strip_prefix(minecraft_dir)
|
||||
&& let Some(current) = manifest.record(relative_path)
|
||||
&& let Some(projected) = resolution_manifest
|
||||
.files
|
||||
.iter_mut()
|
||||
.find(|record| record.relative_path == relative_path)
|
||||
plan_bulk_with_registry(
|
||||
®istry,
|
||||
instance,
|
||||
manifest,
|
||||
minecraft_dir,
|
||||
requests,
|
||||
conflicts,
|
||||
progress,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn plan_bulk_with_registry(
|
||||
registry: &super::provider::ProviderRegistry,
|
||||
instance: &InstanceConfig,
|
||||
manifest: &ContentManifest,
|
||||
minecraft_dir: &std::path::Path,
|
||||
mut requests: Vec<UpdateRequest>,
|
||||
mut conflicts: Vec<UpdateConflict>,
|
||||
progress: Option<&crate::feedback::progress::ProgressTaskHandle>,
|
||||
) -> BulkUpdatePlan {
|
||||
loop {
|
||||
let request_count = requests.len();
|
||||
if let Some(progress) = progress
|
||||
&& request_count > 0
|
||||
{
|
||||
projected.resolution = current.resolution.clone();
|
||||
progress.set_progress(0, request_count as u64);
|
||||
}
|
||||
let plan = match super::dependencies::resolve(
|
||||
®istry,
|
||||
&resolution_manifest,
|
||||
minecraft_dir,
|
||||
instance,
|
||||
root,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(plan) => plan,
|
||||
Err(error) => {
|
||||
conflicts.push(UpdateConflict {
|
||||
title: request.title,
|
||||
installed_path: request.installed_path,
|
||||
reason: error.to_string(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut proposed = accepted.clone();
|
||||
proposed.push(plan.clone());
|
||||
if let Err(error) = super::dependencies::merge(proposed) {
|
||||
conflicts.push(UpdateConflict {
|
||||
title: request.title,
|
||||
installed_path: request.installed_path,
|
||||
reason: error.to_string(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
roots.push(PlannedRootUpdate {
|
||||
title: request.title,
|
||||
installed_path: request.installed_path,
|
||||
current_version: request.update.current.as_ref().map_or_else(
|
||||
|| request.update.installed.version_id.clone(),
|
||||
|version| version.version_number.clone(),
|
||||
),
|
||||
target: request.update.target,
|
||||
});
|
||||
accepted.push(plan);
|
||||
}
|
||||
BulkUpdatePlan {
|
||||
dependency_plan: super::dependencies::merge(accepted).unwrap_or(DependencyPlan {
|
||||
let mut completed = 0;
|
||||
let projected_manifest = project_updates(manifest, minecraft_dir, &requests);
|
||||
let mut accepted = Vec::new();
|
||||
let mut survivors = Vec::new();
|
||||
let mut dependency_plan = DependencyPlan {
|
||||
items: Vec::new(),
|
||||
root_count: 0,
|
||||
optional_dependencies: 0,
|
||||
}),
|
||||
roots,
|
||||
conflicts,
|
||||
};
|
||||
for request in requests {
|
||||
if let Some(progress) = progress {
|
||||
progress.set_sub_action(format!(
|
||||
"Checking {} ({}/{request_count})",
|
||||
request.title,
|
||||
completed + 1
|
||||
));
|
||||
}
|
||||
let root = InstallRoot {
|
||||
provider: request.update.installed.provider.clone(),
|
||||
project_id: request.update.installed.project_id.clone(),
|
||||
title: request.title.clone(),
|
||||
version: request.update.target.clone(),
|
||||
installed_path: Some(request.installed_path.clone()),
|
||||
kind: request.update.kind,
|
||||
target_world: request.target_world.clone(),
|
||||
force_reinstall: false,
|
||||
};
|
||||
let mut resolution_manifest = projected_manifest.clone();
|
||||
if let Ok(relative_path) = request.installed_path.strip_prefix(minecraft_dir)
|
||||
&& let Some(current) = manifest.record(relative_path)
|
||||
&& let Some(projected) = resolution_manifest
|
||||
.files
|
||||
.iter_mut()
|
||||
.find(|record| record.relative_path == relative_path)
|
||||
{
|
||||
*projected = current.clone();
|
||||
}
|
||||
let mut plan = match super::dependencies::resolve(
|
||||
registry,
|
||||
&resolution_manifest,
|
||||
minecraft_dir,
|
||||
instance,
|
||||
root,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(plan) => plan,
|
||||
Err(error) => {
|
||||
conflicts.push(UpdateConflict {
|
||||
title: request.title,
|
||||
installed_path: request.installed_path,
|
||||
reason: error.to_string(),
|
||||
});
|
||||
completed += 1;
|
||||
if let Some(progress) = progress {
|
||||
progress.set_progress(completed, request_count as u64);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
for item in &mut plan.items {
|
||||
item.expected_record = item
|
||||
.installed_path
|
||||
.as_ref()
|
||||
.and_then(|path| path.strip_prefix(minecraft_dir).ok())
|
||||
.and_then(|relative| manifest.record(relative))
|
||||
.cloned();
|
||||
}
|
||||
let mut proposed = accepted.clone();
|
||||
proposed.push(plan.clone());
|
||||
match super::dependencies::merge(proposed) {
|
||||
Ok(merged) => dependency_plan = merged,
|
||||
Err(error) => {
|
||||
conflicts.push(UpdateConflict {
|
||||
title: request.title,
|
||||
installed_path: request.installed_path,
|
||||
reason: error.to_string(),
|
||||
});
|
||||
completed += 1;
|
||||
if let Some(progress) = progress {
|
||||
progress.set_progress(completed, request_count as u64);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
accepted.push(plan);
|
||||
survivors.push(request);
|
||||
completed += 1;
|
||||
if let Some(progress) = progress {
|
||||
progress.set_progress(completed, request_count as u64);
|
||||
}
|
||||
}
|
||||
if survivors.len() != request_count {
|
||||
requests = survivors;
|
||||
continue;
|
||||
}
|
||||
let roots = survivors
|
||||
.into_iter()
|
||||
.map(|request| PlannedRootUpdate {
|
||||
current_version: request.update.current.as_ref().map_or_else(
|
||||
|| request.update.installed.version_id.clone(),
|
||||
|version| version.version_number.clone(),
|
||||
),
|
||||
title: request.title,
|
||||
installed_path: request.installed_path,
|
||||
target: request.update.target,
|
||||
})
|
||||
.collect();
|
||||
return BulkUpdatePlan {
|
||||
dependency_plan,
|
||||
roots,
|
||||
conflicts,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -397,6 +659,7 @@ fn project_updates(
|
||||
version_id: request.update.target.id.clone(),
|
||||
},
|
||||
};
|
||||
record.provider_aliases.clear();
|
||||
}
|
||||
projected
|
||||
}
|
||||
@@ -500,46 +763,6 @@ mod tests {
|
||||
assert!(expired.is_stale(&manifest));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_checks_keep_the_previously_known_update() {
|
||||
let installed = ProviderProject {
|
||||
provider: "modrinth".to_owned(),
|
||||
project_id: "project".to_owned(),
|
||||
version_id: "old".to_owned(),
|
||||
};
|
||||
let previous = UpdateSnapshot {
|
||||
game_version: "1.21.1".to_owned(),
|
||||
loader: ModLoader::Fabric,
|
||||
inventory: vec![installed.clone()],
|
||||
checked_at: 0,
|
||||
updates: vec![AvailableUpdate {
|
||||
installed: installed.clone(),
|
||||
current: Some(version("old")),
|
||||
target: version("new"),
|
||||
kind: ContentKind::Mod,
|
||||
}],
|
||||
failures: Vec::new(),
|
||||
};
|
||||
let mut offline = UpdateSnapshot {
|
||||
updates: Vec::new(),
|
||||
failures: vec![UpdateCheckFailure {
|
||||
installed: installed.clone(),
|
||||
kind: ContentKind::Mod,
|
||||
reason: "request timed out".to_owned(),
|
||||
}],
|
||||
..previous.clone()
|
||||
};
|
||||
|
||||
offline.carry_over(&previous);
|
||||
|
||||
assert_eq!(
|
||||
offline
|
||||
.update_for(&installed)
|
||||
.map(|update| &update.target.id),
|
||||
Some(&"new".to_owned())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bulk_planning_projects_other_selected_updates() {
|
||||
let minecraft = std::path::Path::new("/instance/minecraft");
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// world save scanning. worlds are always directories (never zips) and store
|
||||
// their icon as icon.png. also computes an approximate size from top-level
|
||||
// files + region data so the user gets some sense of how chonky their world is.
|
||||
|
||||
use std::{fs::File, path::Path};
|
||||
|
||||
use flate2::read::GzDecoder;
|
||||
@@ -14,7 +10,9 @@ use super::entry::{ContentEntry, WorldDetails, WorldGameMode};
|
||||
use super::{fallback_icon_large, make_icon_pixels};
|
||||
|
||||
pub fn scan_one_world(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||
let icon_bytes = std::fs::read(path.join("icon.png")).ok();
|
||||
let icon_bytes = File::open(path.join("icon.png"))
|
||||
.ok()
|
||||
.and_then(super::read_local_metadata);
|
||||
let icon_lines = icon_bytes
|
||||
.as_ref()
|
||||
.and_then(|bytes| make_icon_pixels(bytes, 12, 6))
|
||||
@@ -159,7 +157,8 @@ impl WorldMetadata {
|
||||
fn read_world_metadata(world_dir: &Path) -> Option<WorldMetadata> {
|
||||
let path = world_dir.join("level.dat");
|
||||
let file = File::open(&path).ok()?;
|
||||
match fastnbt::from_reader::<_, LevelDat>(GzDecoder::new(file)) {
|
||||
let bytes = super::read_local_metadata(GzDecoder::new(file))?;
|
||||
match fastnbt::from_bytes::<LevelDat>(&bytes) {
|
||||
Ok(level) => Some(level.data),
|
||||
Err(error) => {
|
||||
tracing::debug!(
|
||||
@@ -204,7 +203,6 @@ fn dir_size_approx(path: &Path) -> u64 {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Check region folder too (main chunk data)
|
||||
let region = path.join("region");
|
||||
if let Ok(rd) = std::fs::read_dir(region) {
|
||||
for entry in rd.flatten() {
|
||||
|
||||
+224
-40
@@ -1,9 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// creates OS-native shortcuts for launching instances directly:
|
||||
// .desktop files on linux, .bat on windows, .command on macos
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::instance::models::InstanceConfig;
|
||||
@@ -11,11 +8,11 @@ use crate::instance::models::InstanceConfig;
|
||||
const ICON_BYTES: &[u8] = include_bytes!("../../assets/icon.svg");
|
||||
|
||||
pub fn desktop_path(name: &str) -> Option<PathBuf> {
|
||||
let sanitized = sanitize(name);
|
||||
let sanitized = shortcut_name(name);
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
dirs_next::data_dir().map(|d| {
|
||||
dirs::data_dir().map(|d| {
|
||||
d.join("applications")
|
||||
.join(format!("rmcl-{sanitized}.desktop"))
|
||||
})
|
||||
@@ -39,10 +36,9 @@ pub fn desktop_path(name: &str) -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
pub fn icon_path() -> Option<PathBuf> {
|
||||
dirs_next::data_dir().map(|d| d.join("rmcl").join("icon.svg"))
|
||||
dirs::data_dir().map(|d| d.join("rmcl").join("icon.svg"))
|
||||
}
|
||||
|
||||
// lazily writes the bundled svg icon to disk the first time a shortcut needs it
|
||||
fn ensure_icon() -> Option<PathBuf> {
|
||||
let path = icon_path()?;
|
||||
if std::fs::read(&path).ok().as_deref() == Some(ICON_BYTES) {
|
||||
@@ -60,22 +56,138 @@ fn ensure_icon() -> Option<PathBuf> {
|
||||
Some(path)
|
||||
}
|
||||
|
||||
fn shortcut_name(name: &str) -> String {
|
||||
let mut encoded = String::new();
|
||||
for character in name.chars() {
|
||||
if character.is_alphanumeric() || matches!(character, '-' | '_') {
|
||||
encoded.push(character);
|
||||
} else {
|
||||
for byte in character.to_string().bytes() {
|
||||
encoded.push_str(&format!("%{byte:02X}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
encoded
|
||||
}
|
||||
|
||||
fn legacy_path(name: &str) -> Option<PathBuf> {
|
||||
let legacy = desktop_path(&sanitize(name))?;
|
||||
(Some(&legacy) != desktop_path(name).as_ref()).then_some(legacy)
|
||||
}
|
||||
|
||||
fn owns_legacy_shortcut(path: &Path, name: &str) -> bool {
|
||||
let Ok(existing) = read_shortcut(path) else {
|
||||
return false;
|
||||
};
|
||||
let marker = shortcut_marker(name);
|
||||
if existing.lines().any(|line| line == marker) {
|
||||
return true;
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
let commands = {
|
||||
let quoted = quote_desktop_exec_arg(name);
|
||||
[
|
||||
format!("Exec=rmcl instance launch {quoted}"),
|
||||
format!(
|
||||
"Exec=rmcl instance launch {}",
|
||||
quoted.replace("\\\\", "\\").replace("%%", "%")
|
||||
),
|
||||
]
|
||||
};
|
||||
#[cfg(target_os = "windows")]
|
||||
let commands = {
|
||||
let command =
|
||||
format!("rmcl instance launch {}", quote_windows_arg(name)).replace('"', "\"\"");
|
||||
[format!("shell.Run \"{command}\", 0, False")]
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
let commands = [format!("rmcl instance launch {}", quote_shell_arg(name))];
|
||||
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
|
||||
let commands: [String; 0] = [];
|
||||
existing
|
||||
.lines()
|
||||
.any(|line| commands.iter().any(|command| line == command))
|
||||
}
|
||||
|
||||
fn read_shortcut(path: &Path) -> std::io::Result<String> {
|
||||
let bytes = std::fs::read(path)?;
|
||||
if let Some(bytes) = bytes.strip_prefix(&[0xff, 0xfe]) {
|
||||
if bytes.len() % 2 != 0 {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"Invalid UTF-16 shortcut",
|
||||
));
|
||||
}
|
||||
let units = bytes
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|pair| u16::from_le_bytes([pair[0], pair[1]]))
|
||||
.collect::<Vec<_>>();
|
||||
String::from_utf16(&units)
|
||||
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
|
||||
} else {
|
||||
String::from_utf8(bytes)
|
||||
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(windows, test))]
|
||||
fn windows_script_bytes(content: &str) -> Vec<u8> {
|
||||
// Windows Script Host reads Unicode scripts as BOM-prefixed UTF-16, not UTF-8.
|
||||
[0xfeff]
|
||||
.into_iter()
|
||||
.chain(content.encode_utf16())
|
||||
.flat_map(u16::to_le_bytes)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn shortcut_marker(name: &str) -> String {
|
||||
let prefix = if cfg!(windows) { "'" } else { "#" };
|
||||
format!("{prefix} rmcl-instance: {}", shortcut_name(name))
|
||||
}
|
||||
pub fn exists(name: &str) -> bool {
|
||||
desktop_path(name).map(|p| p.exists()).unwrap_or(false)
|
||||
desktop_path(name).is_some_and(|path| owns_legacy_shortcut(&path, name))
|
||||
|| legacy_path(name).is_some_and(|path| owns_legacy_shortcut(&path, name))
|
||||
}
|
||||
|
||||
pub fn create(config: &InstanceConfig) -> std::io::Result<PathBuf> {
|
||||
crate::instance::manager::validate_name(&config.name).map_err(std::io::Error::other)?;
|
||||
let path = desktop_path(&config.name)
|
||||
.ok_or_else(|| std::io::Error::other("cannot resolve shortcut directory"))?;
|
||||
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Ok(_) if !owns_legacy_shortcut(&path, &config.name) => {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::AlreadyExists,
|
||||
format!("Another shortcut already exists at '{}'", path.display()),
|
||||
));
|
||||
}
|
||||
Err(error) if error.kind() != std::io::ErrorKind::NotFound => return Err(error),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
|
||||
let icon = ensure_icon();
|
||||
let content = build_content(&config.name, icon.as_deref());
|
||||
if std::fs::read_to_string(&path).ok().as_deref() != Some(content.as_str()) {
|
||||
crate::storage::write_atomic(&path, content.as_bytes())?;
|
||||
let executable = std::env::current_exe()?;
|
||||
let executable = executable.to_str().ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"Launcher executable path is not UTF-8",
|
||||
)
|
||||
})?;
|
||||
let content = build_content(&config.name, icon.as_deref(), executable);
|
||||
if read_shortcut(&path).ok().as_deref() != Some(content.as_str()) {
|
||||
#[cfg(windows)]
|
||||
let encoded = windows_script_bytes(&content);
|
||||
#[cfg(windows)]
|
||||
let bytes = encoded.as_slice();
|
||||
#[cfg(not(windows))]
|
||||
let bytes = content.as_bytes();
|
||||
crate::storage::write_atomic(&path, bytes)?;
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -85,6 +197,12 @@ pub fn create(config: &InstanceConfig) -> std::io::Result<PathBuf> {
|
||||
std::fs::set_permissions(&path, perms)?;
|
||||
}
|
||||
|
||||
if let Some(legacy) = legacy_path(&config.name)
|
||||
&& owns_legacy_shortcut(&legacy, &config.name)
|
||||
{
|
||||
std::fs::remove_file(legacy)?;
|
||||
}
|
||||
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
@@ -92,9 +210,14 @@ pub fn remove(name: &str) -> std::io::Result<()> {
|
||||
let Some(path) = desktop_path(name) else {
|
||||
return Ok(());
|
||||
};
|
||||
if path.exists() {
|
||||
if owns_legacy_shortcut(&path, name) {
|
||||
std::fs::remove_file(path)?;
|
||||
}
|
||||
if let Some(legacy) = legacy_path(name)
|
||||
&& owns_legacy_shortcut(&legacy, name)
|
||||
{
|
||||
std::fs::remove_file(legacy)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -113,51 +236,101 @@ pub fn toggle(config: &InstanceConfig) -> std::io::Result<bool> {
|
||||
}
|
||||
|
||||
pub fn rename(old_name: &str, new_config: &InstanceConfig) -> std::io::Result<()> {
|
||||
let Some(old_path) = desktop_path(old_name).filter(|path| path.exists()) else {
|
||||
if !exists(old_name) {
|
||||
return Ok(());
|
||||
};
|
||||
}
|
||||
let same_path = desktop_path(old_name) == desktop_path(&new_config.name);
|
||||
if !same_path && let Some(new_path) = desktop_path(&new_config.name) {
|
||||
for old_path in [desktop_path(old_name), legacy_path(old_name)]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
if rename_shortcut_alias(&old_path, &new_path, old_name, || {
|
||||
create(new_config).map(|_| ())
|
||||
})? {
|
||||
remove(old_name)?;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
create(new_config)?;
|
||||
if desktop_path(&new_config.name).as_ref() != Some(&old_path) {
|
||||
std::fs::remove_file(old_path)?;
|
||||
if !same_path {
|
||||
remove(old_name)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn build_content(name: &str, icon: Option<&Path>) -> String {
|
||||
fn rename_shortcut_alias(
|
||||
old_path: &Path,
|
||||
new_path: &Path,
|
||||
old_name: &str,
|
||||
create: impl FnOnce() -> std::io::Result<()>,
|
||||
) -> std::io::Result<bool> {
|
||||
if old_path == new_path
|
||||
|| !owns_legacy_shortcut(old_path, old_name)
|
||||
|| !crate::instance::manager::paths_alias(old_path, new_path)?
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let temporary = tempfile::Builder::new()
|
||||
.prefix(".rmcl-shortcut-")
|
||||
.tempdir_in(
|
||||
old_path
|
||||
.parent()
|
||||
.ok_or_else(|| std::io::Error::other("Shortcut has no parent"))?,
|
||||
)?;
|
||||
let original = temporary.path().join("original");
|
||||
std::fs::rename(old_path, &original)?;
|
||||
if let Err(error) = create() {
|
||||
if let Err(rollback) = std::fs::rename(&original, old_path) {
|
||||
let retained = temporary.keep();
|
||||
return Err(std::io::Error::other(format!(
|
||||
"Could not update shortcut: {error}; rollback failed: {rollback}; original retained at '{}'",
|
||||
retained.join("original").display(),
|
||||
)));
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn build_content(name: &str, icon: Option<&Path>, executable: &str) -> String {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
build_linux_desktop(name, icon)
|
||||
build_linux_desktop(name, icon, executable)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let _ = icon;
|
||||
build_windows_shortcut(name)
|
||||
build_windows_shortcut(name, executable)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let _ = icon;
|
||||
build_macos_command(name)
|
||||
build_macos_command(name, executable)
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
|
||||
{
|
||||
let _ = (name, icon);
|
||||
let _ = (name, icon, executable);
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn build_linux_desktop(name: &str, icon: Option<&Path>) -> String {
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
fn build_linux_desktop(name: &str, icon: Option<&Path>, executable: &str) -> String {
|
||||
let mut out = String::new();
|
||||
out.push_str("[Desktop Entry]\n");
|
||||
out.push_str("Version=0.3.1\n");
|
||||
out.push_str("Version=1.0\n");
|
||||
out.push_str("Type=Application\n");
|
||||
out.push_str(&format!("Name=Minecraft - {name}\n"));
|
||||
out.push_str(&format!("Comment=Launch {name} Minecraft instance\n"));
|
||||
out.push_str(&format!("# rmcl-instance: {}\n", shortcut_name(name)));
|
||||
out.push_str(&format!(
|
||||
"Exec=rmcl instance launch {}\n",
|
||||
"Exec={} instance launch {}\n",
|
||||
quote_desktop_exec_arg(executable),
|
||||
quote_desktop_exec_arg(name)
|
||||
));
|
||||
if let Some(icon) = icon {
|
||||
@@ -168,26 +341,38 @@ fn build_linux_desktop(name: &str, icon: Option<&Path>) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn build_windows_shortcut(name: &str) -> String {
|
||||
let command = format!("rmcl instance launch {}", quote_windows_arg(name));
|
||||
let escaped_command = command.replace('"', "\"\"");
|
||||
|
||||
let mut out = String::new();
|
||||
out.push_str("Set shell = CreateObject(\"WScript.Shell\")\r\n");
|
||||
out.push_str(&format!("shell.Run \"{escaped_command}\", 0, False\r\n"));
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
fn build_windows_shortcut(name: &str, executable: &str) -> String {
|
||||
let arguments = format!("instance launch {}", quote_windows_arg(name));
|
||||
let mut out = format!("' rmcl-instance: {}\r\n", shortcut_name(name));
|
||||
out.push_str(&windows_shell_execute(executable, &arguments));
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn build_macos_command(name: &str) -> String {
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
fn windows_shell_execute(executable: &str, arguments: &str) -> String {
|
||||
// ShellExecute passes parameters literally; WScript.Shell.Run expands %VAR% in them.
|
||||
format!(
|
||||
"Set shell = CreateObject(\"Shell.Application\")\r\nshell.ShellExecute \"{}\", \"{}\", \"\", \"open\", 0\r\n",
|
||||
executable.replace('"', "\"\""),
|
||||
arguments.replace('"', "\"\"")
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
fn build_macos_command(name: &str, executable: &str) -> String {
|
||||
let mut out = String::new();
|
||||
out.push_str("#!/bin/bash\n");
|
||||
out.push_str(&format!("# Launch Minecraft instance: {name}\n"));
|
||||
out.push_str(&format!("rmcl instance launch {}\n", quote_shell_arg(name)));
|
||||
out.push_str(&format!("# rmcl-instance: {}\n", shortcut_name(name)));
|
||||
out.push_str(&format!(
|
||||
"{} instance launch {}\n",
|
||||
quote_shell_arg(executable),
|
||||
quote_shell_arg(name)
|
||||
));
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
fn quote_desktop_exec_arg(value: &str) -> String {
|
||||
let mut escaped = String::with_capacity(value.len() + 2);
|
||||
escaped.push('"');
|
||||
@@ -198,7 +383,7 @@ fn quote_desktop_exec_arg(value: &str) -> String {
|
||||
escaped.push(character);
|
||||
}
|
||||
escaped.push('"');
|
||||
escaped
|
||||
escaped.replace('\\', "\\\\").replace('%', "%%")
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
@@ -229,8 +414,7 @@ fn quote_windows_arg(value: &str) -> String {
|
||||
quoted
|
||||
}
|
||||
|
||||
// replaces anything that isn't alphanumeric, dash, or underscore with _
|
||||
fn sanitize(name: &str) -> String {
|
||||
pub(crate) fn sanitize(name: &str) -> String {
|
||||
name.chars()
|
||||
.map(|c| {
|
||||
if c.is_alphanumeric() || c == '-' || c == '_' {
|
||||
|
||||
@@ -0,0 +1,710 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
mod curseforge;
|
||||
mod mmc;
|
||||
mod mrpack;
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::content::local::current_fingerprint;
|
||||
use super::content::manifest::{
|
||||
ContentLock, ContentManifest, FileFingerprint, fingerprint_metadata, fingerprint_with_check,
|
||||
};
|
||||
pub use super::pack::PackFormat;
|
||||
use super::{InstanceConfig, InstanceManager, ModLoader};
|
||||
use crate::feedback::progress::{ProgressTask, ProgressTaskHandle};
|
||||
|
||||
pub type ExportResult<T> = Result<T, Box<dyn std::error::Error + Send + Sync>>;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExportOptions {
|
||||
pub format: PackFormat,
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub author: String,
|
||||
pub game_version: String,
|
||||
pub loader: ModLoader,
|
||||
pub loader_version: Option<String>,
|
||||
pub include: Vec<PathBuf>,
|
||||
pub bundle_unmatched: bool,
|
||||
}
|
||||
|
||||
impl ExportOptions {
|
||||
pub fn for_instance(instance: &InstanceConfig) -> Self {
|
||||
Self {
|
||||
format: PackFormat::CurseForge,
|
||||
name: instance.name.clone(),
|
||||
version: "1.0.0".to_owned(),
|
||||
author: String::new(),
|
||||
game_version: instance.game_version.clone(),
|
||||
loader: instance.loader,
|
||||
loader_version: instance.loader_version.clone(),
|
||||
include: Vec::new(),
|
||||
bundle_unmatched: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ExportPlan {
|
||||
pub options: ExportOptions,
|
||||
pub unmatched: Vec<PathBuf>,
|
||||
root: PathBuf,
|
||||
files: BTreeMap<PathBuf, FileFingerprint>,
|
||||
archive: ArchiveContents,
|
||||
manifest_path: Option<PathBuf>,
|
||||
_lock: Option<Arc<super::runtime::InstanceLock>>,
|
||||
explicit_selection: bool,
|
||||
}
|
||||
|
||||
impl ExportPlan {
|
||||
pub fn file_count(&self) -> usize {
|
||||
self.files.len()
|
||||
}
|
||||
|
||||
pub fn referenced_count(&self) -> usize {
|
||||
self.archive.referenced.len()
|
||||
}
|
||||
|
||||
pub fn referenced_paths(&self) -> &BTreeSet<PathBuf> {
|
||||
&self.archive.referenced
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ExportScan {
|
||||
config: InstanceConfig,
|
||||
root: PathBuf,
|
||||
files: BTreeMap<PathBuf, FileFingerprint>,
|
||||
manifest_path: PathBuf,
|
||||
pub defaults: BTreeSet<PathBuf>,
|
||||
pub skipped: Vec<PathBuf>,
|
||||
lock: Arc<super::runtime::InstanceLock>,
|
||||
}
|
||||
|
||||
pub enum ExportReferences {
|
||||
CurseForge(BTreeMap<u32, crate::net::modrinth::VersionInfo>),
|
||||
Mrpack(HashMap<String, crate::net::modrinth::VersionInfo>),
|
||||
Bundled,
|
||||
}
|
||||
|
||||
impl ExportReferences {
|
||||
pub fn empty(format: PackFormat) -> Self {
|
||||
match format {
|
||||
PackFormat::CurseForge => Self::CurseForge(BTreeMap::new()),
|
||||
PackFormat::Mrpack => Self::Mrpack(HashMap::new()),
|
||||
PackFormat::Mmc => Self::Bundled,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ExportScan {
|
||||
pub fn paths(&self) -> impl Iterator<Item = &PathBuf> {
|
||||
self.files.keys()
|
||||
}
|
||||
|
||||
pub fn needs_references(&self, format: PackFormat, selected: &BTreeSet<PathBuf>) -> bool {
|
||||
selected
|
||||
.iter()
|
||||
.any(|path| reference_candidate(path, format))
|
||||
}
|
||||
|
||||
pub fn unmatched(
|
||||
&self,
|
||||
format: PackFormat,
|
||||
selected: &BTreeSet<PathBuf>,
|
||||
referenced: &BTreeSet<PathBuf>,
|
||||
) -> Vec<PathBuf> {
|
||||
selected
|
||||
.iter()
|
||||
.filter(|path| {
|
||||
format != PackFormat::Mmc
|
||||
&& content_path(path, format)
|
||||
&& !referenced.contains(*path)
|
||||
})
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn plan(
|
||||
&self,
|
||||
options: &ExportOptions,
|
||||
selected: &BTreeSet<PathBuf>,
|
||||
references: &ExportReferences,
|
||||
) -> ExportResult<ExportPlan> {
|
||||
let mut options = options.clone();
|
||||
options.game_version = self.config.game_version.clone();
|
||||
options.loader = self.config.loader;
|
||||
options.loader_version = self.config.loader_version.clone();
|
||||
validate_options(&options)?;
|
||||
let files = selected
|
||||
.iter()
|
||||
.map(|path| {
|
||||
self.files
|
||||
.get(path)
|
||||
.cloned()
|
||||
.map(|file| (path.clone(), file))
|
||||
.ok_or_else(|| format!("File was not scanned: {}", path.display()).into())
|
||||
})
|
||||
.collect::<ExportResult<BTreeMap<_, _>>>()?;
|
||||
let mut plan = ExportPlan {
|
||||
root: self.root.clone(),
|
||||
files,
|
||||
options,
|
||||
unmatched: Vec::new(),
|
||||
manifest_path: Some(self.manifest_path.clone()),
|
||||
_lock: Some(self.lock.clone()),
|
||||
explicit_selection: true,
|
||||
archive: ArchiveContents {
|
||||
manifests: Vec::new(),
|
||||
referenced: BTreeSet::new(),
|
||||
prefix: "overrides",
|
||||
},
|
||||
};
|
||||
plan.archive = match (plan.options.format, references) {
|
||||
(PackFormat::CurseForge, ExportReferences::CurseForge(files)) => {
|
||||
curseforge::manifest(&plan, files)?
|
||||
}
|
||||
(PackFormat::Mrpack, ExportReferences::Mrpack(files)) => {
|
||||
mrpack::manifest(&plan, files)?
|
||||
}
|
||||
(PackFormat::Mmc, ExportReferences::Bundled) => mmc::prepare(&plan.options)?,
|
||||
_ => return Err("Content identification does not match the export format".into()),
|
||||
};
|
||||
plan.unmatched = self.unmatched(plan.options.format, selected, &plan.archive.referenced);
|
||||
Ok(plan)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn scan_instance_export(
|
||||
manager: &InstanceManager,
|
||||
name: &str,
|
||||
) -> ExportResult<ExportScan> {
|
||||
let lock = Arc::new(super::runtime::lock_instance(&manager.instances_dir, name)?);
|
||||
let config = manager.load_one(name)?;
|
||||
let paths = crate::storage::InstancePaths::new(manager.instances_dir.join(name));
|
||||
let root = paths.minecraft();
|
||||
// Dropping the awaiting future closes this channel, including when the popup aborts it.
|
||||
let (lifetime, receiver) = tokio::sync::oneshot::channel::<()>();
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let check = || -> std::io::Result<()> {
|
||||
if lifetime.is_closed() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::Interrupted,
|
||||
"Export scan cancelled",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
check()?;
|
||||
let progress = ProgressTask::start("Scanning export files");
|
||||
let root = root.canonicalize()?;
|
||||
let manifest_path = paths.content_manifest();
|
||||
let cached = load_fingerprints(&manifest_path);
|
||||
let mut files = BTreeMap::new();
|
||||
let mut skipped = Vec::new();
|
||||
scan_directory(
|
||||
&root,
|
||||
Path::new(""),
|
||||
&mut files,
|
||||
&mut skipped,
|
||||
&cached,
|
||||
&progress,
|
||||
&check,
|
||||
)?;
|
||||
check()?;
|
||||
let defaults = files
|
||||
.keys()
|
||||
.filter(|path| {
|
||||
DEFAULT_PATHS
|
||||
.iter()
|
||||
.any(|directory| path.starts_with(directory))
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
Ok(ExportScan {
|
||||
config,
|
||||
root,
|
||||
files,
|
||||
manifest_path,
|
||||
defaults,
|
||||
skipped,
|
||||
lock,
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
drop(receiver);
|
||||
result
|
||||
}
|
||||
|
||||
fn scan_directory(
|
||||
root: &Path,
|
||||
directory: &Path,
|
||||
files: &mut BTreeMap<PathBuf, FileFingerprint>,
|
||||
skipped: &mut Vec<PathBuf>,
|
||||
cached: &ContentManifest,
|
||||
progress: &ProgressTask,
|
||||
check: &impl Fn() -> std::io::Result<()>,
|
||||
) -> ExportResult<()> {
|
||||
check()?;
|
||||
for entry in std::fs::read_dir(root.join(directory))? {
|
||||
check()?;
|
||||
let entry = entry?;
|
||||
let relative = directory.join(entry.file_name());
|
||||
let metadata = std::fs::symlink_metadata(entry.path())?;
|
||||
if !portable_export_path(&relative)
|
||||
|| metadata.file_type().is_symlink()
|
||||
|| !(metadata.is_dir() || metadata.is_file())
|
||||
|| metadata.is_file() && relative.to_string_lossy().ends_with(".disabled")
|
||||
{
|
||||
skipped.push(relative);
|
||||
continue;
|
||||
}
|
||||
if metadata.is_dir() {
|
||||
scan_directory(root, &relative, files, skipped, cached, progress, check)?;
|
||||
} else {
|
||||
progress.set_sub_action(relative.display().to_string());
|
||||
let full = root.join(&relative);
|
||||
let hash = if reference_candidate(&relative, PackFormat::Mrpack) {
|
||||
export_fingerprint(
|
||||
&full,
|
||||
cached.record(&relative).map(|record| &record.fingerprint),
|
||||
check,
|
||||
)?
|
||||
} else {
|
||||
fingerprint_metadata(&full)?
|
||||
};
|
||||
files.insert(relative, hash);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_fingerprints(path: &Path) -> ContentManifest {
|
||||
ContentManifest::load(path).unwrap_or_else(|error| {
|
||||
tracing::warn!(
|
||||
"Could not read cached export fingerprints '{}': {error}",
|
||||
path.display()
|
||||
);
|
||||
ContentManifest::default()
|
||||
})
|
||||
}
|
||||
|
||||
fn export_fingerprint(
|
||||
path: &Path,
|
||||
cached: Option<&FileFingerprint>,
|
||||
check: impl Fn() -> std::io::Result<()>,
|
||||
) -> std::io::Result<FileFingerprint> {
|
||||
check()?;
|
||||
let metadata = fingerprint_metadata(path)?;
|
||||
if let Some(cached) = cached
|
||||
&& cached.size == metadata.size
|
||||
&& cached.modified_ns == metadata.modified_ns
|
||||
&& ["sha1", "sha512", "curseforge"]
|
||||
.iter()
|
||||
.all(|algorithm| cached.hash(algorithm).is_some())
|
||||
{
|
||||
// Browsing can reuse the index; writing still rehashes every referenced file.
|
||||
return Ok(cached.clone());
|
||||
}
|
||||
fingerprint_with_check(path, check)
|
||||
}
|
||||
|
||||
pub async fn resolve_export_files(
|
||||
scan: &ExportScan,
|
||||
format: PackFormat,
|
||||
) -> ExportResult<ExportReferences> {
|
||||
let progress = ProgressTask::start(format!("Identifying {} export files", format.label()));
|
||||
match format {
|
||||
PackFormat::CurseForge => Ok(ExportReferences::CurseForge(
|
||||
curseforge::resolve(&scan.files, &progress).await?,
|
||||
)),
|
||||
PackFormat::Mrpack => Ok(ExportReferences::Mrpack(
|
||||
mrpack::resolve(&scan.files, &progress).await?,
|
||||
)),
|
||||
PackFormat::Mmc => Ok(ExportReferences::Bundled),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ExportReport {
|
||||
pub output: PathBuf,
|
||||
pub referenced_count: usize,
|
||||
pub bundled_count: usize,
|
||||
pub unmatched: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
struct ArchiveContents {
|
||||
manifests: Vec<(&'static str, Vec<u8>)>,
|
||||
referenced: BTreeSet<PathBuf>,
|
||||
prefix: &'static str,
|
||||
}
|
||||
|
||||
const DEFAULT_PATHS: &[&str] = &[
|
||||
"mods",
|
||||
"config",
|
||||
"defaultconfigs",
|
||||
"kubejs",
|
||||
"scripts",
|
||||
"resourcepacks",
|
||||
"shaderpacks",
|
||||
"datapacks",
|
||||
];
|
||||
|
||||
fn portable_export_path(relative: &Path) -> bool {
|
||||
relative.to_str().is_some_and(|path| {
|
||||
super::import::portable_pack_path(path)
|
||||
.is_ok_and(|normalized| cfg!(windows) || normalized == path)
|
||||
})
|
||||
}
|
||||
|
||||
fn collect(root: &Path, relative: &Path, files: &mut BTreeSet<PathBuf>) -> ExportResult<()> {
|
||||
if !portable_export_path(relative) {
|
||||
return Err(format!("Invalid export path: {}", relative.display()).into());
|
||||
}
|
||||
let mut ancestor = root.to_path_buf();
|
||||
for component in relative.components() {
|
||||
ancestor.push(component);
|
||||
if std::fs::symlink_metadata(&ancestor)?
|
||||
.file_type()
|
||||
.is_symlink()
|
||||
{
|
||||
return Err(format!("Export does not follow symlinks: {}", relative.display()).into());
|
||||
}
|
||||
}
|
||||
let path = root.join(relative);
|
||||
let metadata = std::fs::symlink_metadata(&path)?;
|
||||
if metadata.is_dir() {
|
||||
for entry in std::fs::read_dir(path)? {
|
||||
collect(root, &relative.join(entry?.file_name()), files)?;
|
||||
}
|
||||
} else if metadata.is_file() {
|
||||
if !relative.to_string_lossy().ends_with(".disabled") {
|
||||
files.insert(relative.to_owned());
|
||||
}
|
||||
} else {
|
||||
return Err(format!("Not a regular file: {}", path.display()).into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn selected_files(root: &Path, include: &[PathBuf]) -> ExportResult<BTreeSet<PathBuf>> {
|
||||
let mut files = BTreeSet::new();
|
||||
for name in DEFAULT_PATHS {
|
||||
match std::fs::symlink_metadata(root.join(name)) {
|
||||
Ok(_) => collect(root, Path::new(name), &mut files)?,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
}
|
||||
for path in include {
|
||||
collect(root, path, &mut files)?;
|
||||
}
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn content_path(path: &Path, format: PackFormat) -> bool {
|
||||
path.starts_with("mods")
|
||||
|| format == PackFormat::Mrpack
|
||||
&& ["resourcepacks", "shaderpacks", "datapacks"]
|
||||
.iter()
|
||||
.any(|directory| path.starts_with(directory))
|
||||
}
|
||||
|
||||
fn reference_candidate(path: &Path, format: PackFormat) -> bool {
|
||||
if format == PackFormat::Mmc || !content_path(path, format) {
|
||||
return false;
|
||||
}
|
||||
let extension = if path.starts_with("mods") {
|
||||
"jar"
|
||||
} else {
|
||||
"zip"
|
||||
};
|
||||
path.parent()
|
||||
.is_some_and(|parent| parent.components().count() == 1)
|
||||
&& path
|
||||
.extension()
|
||||
.is_some_and(|value| value.eq_ignore_ascii_case(extension))
|
||||
}
|
||||
|
||||
fn inventory(
|
||||
root: PathBuf,
|
||||
options: ExportOptions,
|
||||
lock: Option<Arc<super::runtime::InstanceLock>>,
|
||||
progress: &ProgressTaskHandle,
|
||||
) -> ExportResult<ExportPlan> {
|
||||
validate_options(&options)?;
|
||||
let root = root.canonicalize()?;
|
||||
if !root.is_dir() {
|
||||
return Err("Game folder must be a directory".into());
|
||||
}
|
||||
let selected = selected_files(&root, &options.include)?;
|
||||
let manifest_path = root
|
||||
.parent()
|
||||
.map(|parent| crate::storage::InstancePaths::new(parent).content_manifest());
|
||||
let cached = manifest_path
|
||||
.as_deref()
|
||||
.map(load_fingerprints)
|
||||
.unwrap_or_default();
|
||||
let mut files = BTreeMap::new();
|
||||
for (index, path) in selected.iter().enumerate() {
|
||||
progress.set_sub_action(path.display().to_string());
|
||||
progress.set_progress(index as u64, selected.len() as u64);
|
||||
let full = root.join(path);
|
||||
let hash = if reference_candidate(path, options.format) {
|
||||
export_fingerprint(
|
||||
&full,
|
||||
cached.record(path).map(|record| &record.fingerprint),
|
||||
|| Ok(()),
|
||||
)?
|
||||
} else {
|
||||
fingerprint_metadata(&full)?
|
||||
};
|
||||
files.insert(path.clone(), hash);
|
||||
}
|
||||
Ok(ExportPlan {
|
||||
options,
|
||||
root,
|
||||
files,
|
||||
unmatched: Vec::new(),
|
||||
manifest_path,
|
||||
_lock: lock,
|
||||
explicit_selection: false,
|
||||
archive: ArchiveContents {
|
||||
manifests: Vec::new(),
|
||||
referenced: BTreeSet::new(),
|
||||
prefix: "overrides",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_options(options: &ExportOptions) -> ExportResult<()> {
|
||||
for (label, value) in [
|
||||
("Pack name", &options.name),
|
||||
("Pack version", &options.version),
|
||||
("Minecraft version", &options.game_version),
|
||||
] {
|
||||
if value.trim().is_empty() || value.chars().any(char::is_control) {
|
||||
return Err(format!("{label} must not be empty or contain control characters").into());
|
||||
}
|
||||
}
|
||||
if options.loader != ModLoader::Vanilla
|
||||
&& options
|
||||
.loader_version
|
||||
.as_ref()
|
||||
.is_none_or(|v| v.trim().is_empty())
|
||||
{
|
||||
return Err("A loader version is required for a modded pack".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn prepare_export(root: &Path, options: &ExportOptions) -> ExportResult<ExportPlan> {
|
||||
prepare(root.to_owned(), options.clone(), None).await
|
||||
}
|
||||
|
||||
pub async fn prepare_instance_export(
|
||||
manager: &InstanceManager,
|
||||
name: &str,
|
||||
options: &ExportOptions,
|
||||
) -> ExportResult<ExportPlan> {
|
||||
let lock = Arc::new(super::runtime::lock_instance(&manager.instances_dir, name)?);
|
||||
let config = manager.load_one(name)?;
|
||||
let mut options = options.clone();
|
||||
options.game_version = config.game_version;
|
||||
options.loader = config.loader;
|
||||
options.loader_version = config.loader_version;
|
||||
let root = crate::storage::InstancePaths::new(manager.instances_dir.join(name)).minecraft();
|
||||
prepare(root, options, Some(lock)).await
|
||||
}
|
||||
|
||||
async fn prepare(
|
||||
root: PathBuf,
|
||||
options: ExportOptions,
|
||||
lock: Option<Arc<super::runtime::InstanceLock>>,
|
||||
) -> ExportResult<ExportPlan> {
|
||||
let progress = ProgressTask::start("Scanning export files");
|
||||
let handle = progress.handle();
|
||||
let mut plan =
|
||||
tokio::task::spawn_blocking(move || inventory(root, options, lock, &handle)).await??;
|
||||
progress.set_action(format!("Preparing {} export", plan.options.format.label()));
|
||||
plan.archive = match plan.options.format {
|
||||
PackFormat::CurseForge => curseforge::prepare(&plan, &progress).await?,
|
||||
PackFormat::Mrpack => mrpack::prepare(&plan, &progress).await?,
|
||||
PackFormat::Mmc => mmc::prepare(&plan.options)?,
|
||||
};
|
||||
if plan.options.format != PackFormat::Mmc {
|
||||
plan.unmatched = plan
|
||||
.files
|
||||
.keys()
|
||||
.filter(|path| {
|
||||
content_path(path, plan.options.format) && !plan.archive.referenced.contains(*path)
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
}
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
pub fn validate_output(root: &Path, output: &Path) -> ExportResult<()> {
|
||||
validate_output_path(root, output)?;
|
||||
if output.try_exists()? {
|
||||
return Err(format!("Output already exists: {}", output.display()).into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_output_path(root: &Path, output: &Path) -> ExportResult<()> {
|
||||
let parent = output
|
||||
.parent()
|
||||
.filter(|path| !path.as_os_str().is_empty())
|
||||
.unwrap_or(Path::new("."));
|
||||
if parent.canonicalize()?.starts_with(root.canonicalize()?) {
|
||||
return Err("Export archive must be outside the game folder".into());
|
||||
}
|
||||
match std::fs::symlink_metadata(output) {
|
||||
Ok(metadata) if !metadata.is_file() => {
|
||||
return Err(format!("Output is not a regular file: {}", output.display()).into());
|
||||
}
|
||||
Err(error) if error.kind() != std::io::ErrorKind::NotFound => return Err(error.into()),
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn write_export(plan: ExportPlan, output: &Path) -> ExportResult<ExportReport> {
|
||||
write_export_with_overwrite(plan, output, false).await
|
||||
}
|
||||
|
||||
pub async fn write_export_with_overwrite(
|
||||
plan: ExportPlan,
|
||||
output: &Path,
|
||||
overwrite: bool,
|
||||
) -> ExportResult<ExportReport> {
|
||||
let output = output.to_owned();
|
||||
tokio::task::spawn_blocking(move || write_archive(plan, &output, overwrite)).await?
|
||||
}
|
||||
|
||||
pub async fn export_pack(
|
||||
root: &Path,
|
||||
output: &Path,
|
||||
options: &ExportOptions,
|
||||
) -> ExportResult<ExportReport> {
|
||||
validate_output(root, output)?;
|
||||
write_export(prepare_export(root, options).await?, output).await
|
||||
}
|
||||
|
||||
fn write_archive(plan: ExportPlan, output: &Path, overwrite: bool) -> ExportResult<ExportReport> {
|
||||
if overwrite {
|
||||
validate_output_path(&plan.root, output)?;
|
||||
} else {
|
||||
validate_output(&plan.root, output)?;
|
||||
}
|
||||
if !plan.options.bundle_unmatched && !plan.unmatched.is_empty() {
|
||||
return Err(format!(
|
||||
"Content without {} matches requires explicit approval to bundle:\n{}",
|
||||
plan.options.format.label(),
|
||||
plan.unmatched
|
||||
.iter()
|
||||
.map(|path| path.display().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
)
|
||||
.into());
|
||||
}
|
||||
let progress = ProgressTask::start("Writing export archive");
|
||||
validate_inventory(&plan)?;
|
||||
let parent = output
|
||||
.parent()
|
||||
.filter(|path| !path.as_os_str().is_empty())
|
||||
.unwrap_or(Path::new("."));
|
||||
let mut temporary = tempfile::NamedTempFile::new_in(parent)?;
|
||||
{
|
||||
let mut zip = zip::ZipWriter::new(temporary.as_file_mut());
|
||||
let zip_options = zip::write::SimpleFileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Deflated);
|
||||
for (name, bytes) in &plan.archive.manifests {
|
||||
zip.start_file(*name, zip_options)?;
|
||||
zip.write_all(bytes)?;
|
||||
}
|
||||
for (index, path) in plan.files.keys().enumerate() {
|
||||
progress.set_progress(index as u64, plan.files.len() as u64);
|
||||
progress.set_sub_action(path.display().to_string());
|
||||
if plan.archive.referenced.contains(path) {
|
||||
continue;
|
||||
}
|
||||
let name = path
|
||||
.to_str()
|
||||
.ok_or("Export paths must be UTF-8")?
|
||||
.replace('\\', "/");
|
||||
zip.start_file(format!("{}/{name}", plan.archive.prefix), zip_options)?;
|
||||
std::io::copy(&mut std::fs::File::open(plan.root.join(path))?, &mut zip)?;
|
||||
}
|
||||
zip.finish()?;
|
||||
}
|
||||
// Standalone folders can change while the archive is being compressed.
|
||||
validate_inventory(&plan)?;
|
||||
temporary.as_file().sync_all()?;
|
||||
if overwrite {
|
||||
validate_output_path(&plan.root, output)?;
|
||||
temporary.persist(output)?;
|
||||
} else {
|
||||
temporary.persist_noclobber(output)?;
|
||||
}
|
||||
Ok(ExportReport {
|
||||
output: output.to_owned(),
|
||||
referenced_count: plan.referenced_count(),
|
||||
bundled_count: plan.file_count() - plan.referenced_count(),
|
||||
unmatched: plan.unmatched,
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_inventory(plan: &ExportPlan) -> ExportResult<()> {
|
||||
let current = if plan.explicit_selection {
|
||||
let mut current = BTreeSet::new();
|
||||
for path in plan.files.keys() {
|
||||
collect(&plan.root, path, &mut current)?;
|
||||
}
|
||||
current
|
||||
} else {
|
||||
selected_files(&plan.root, &plan.options.include)?
|
||||
};
|
||||
if current != plan.files.keys().cloned().collect() {
|
||||
return Err("Export files changed after preparation; prepare the export again".into());
|
||||
}
|
||||
for (path, expected) in &plan.files {
|
||||
let actual = current_fingerprint(&plan.root.join(path), expected)?;
|
||||
if actual != *expected {
|
||||
if let Some(manifest_path) = &plan.manifest_path
|
||||
&& manifest_path.try_exists()?
|
||||
{
|
||||
let lock = match &plan._lock {
|
||||
Some(guard) => {
|
||||
ContentLock::acquire_with_held_instance_lock(manifest_path, guard)
|
||||
}
|
||||
None => ContentLock::acquire(manifest_path),
|
||||
}?;
|
||||
let mut manifest = lock.load()?;
|
||||
if let Some(record) = manifest
|
||||
.files
|
||||
.iter_mut()
|
||||
.find(|record| record.relative_path == *path && record.fingerprint == *expected)
|
||||
{
|
||||
// Force a rescan without discarding ownership or the hashes used for safe mutations.
|
||||
record.fingerprint.modified_ns = u128::MAX;
|
||||
lock.save(&manifest)?;
|
||||
}
|
||||
}
|
||||
return Err(
|
||||
format!("Export file changed after preparation: {}", path.display()).into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests/export.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,116 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use super::*;
|
||||
use crate::instance::import::curseforge::{Manifest, ManifestFile, ManifestLoader, Minecraft};
|
||||
use crate::net::modrinth::VersionInfo;
|
||||
|
||||
pub(super) async fn prepare(
|
||||
plan: &ExportPlan,
|
||||
progress: &ProgressTask,
|
||||
) -> ExportResult<ArchiveContents> {
|
||||
manifest(plan, &resolve(&plan.files, progress).await?)
|
||||
}
|
||||
|
||||
pub(super) async fn resolve(
|
||||
files: &BTreeMap<PathBuf, FileFingerprint>,
|
||||
progress: &ProgressTask,
|
||||
) -> ExportResult<BTreeMap<u32, VersionInfo>> {
|
||||
let fingerprints = files
|
||||
.iter()
|
||||
.filter(|(path, _)| reference_candidate(path, PackFormat::CurseForge))
|
||||
.filter_map(|(_, file)| {
|
||||
file.hash("curseforge")
|
||||
.and_then(|value| value.parse::<u32>().ok())
|
||||
})
|
||||
.collect::<BTreeSet<_>>()
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>();
|
||||
let mut matches = BTreeMap::new();
|
||||
if !fingerprints.is_empty() {
|
||||
let key =
|
||||
crate::net::curseforge::api_key().ok_or("CurseForge API key is not configured")?;
|
||||
let client = crate::net::HttpClient::new();
|
||||
for (index, chunk) in fingerprints.chunks(100).enumerate() {
|
||||
progress.set_sub_action("Identifying CurseForge mods");
|
||||
progress.set_progress((index * 100) as u64, fingerprints.len() as u64);
|
||||
matches.extend(
|
||||
crate::net::curseforge::resolve_fingerprint_versions(&client, key, chunk).await?,
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(matches)
|
||||
}
|
||||
|
||||
pub(super) fn manifest(
|
||||
plan: &ExportPlan,
|
||||
matches: &BTreeMap<u32, VersionInfo>,
|
||||
) -> ExportResult<ArchiveContents> {
|
||||
let mut referenced = BTreeSet::new();
|
||||
let mut ids = BTreeSet::new();
|
||||
for (path, hash) in &plan.files {
|
||||
if !reference_candidate(path, PackFormat::CurseForge) {
|
||||
continue;
|
||||
}
|
||||
let Some(version) = hash
|
||||
.hash("curseforge")
|
||||
.and_then(|hash| hash.parse().ok())
|
||||
.and_then(|hash| matches.get(&hash))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if version.files.iter().any(|file| {
|
||||
file.hashes.get("sha1").is_some_and(|expected| {
|
||||
hash.hash("sha1")
|
||||
.is_some_and(|actual| actual.eq_ignore_ascii_case(expected))
|
||||
})
|
||||
}) {
|
||||
ids.insert((
|
||||
version.project_id.parse::<u64>()?,
|
||||
version.id.parse::<u64>()?,
|
||||
));
|
||||
referenced.insert(path.clone());
|
||||
}
|
||||
}
|
||||
let options = &plan.options;
|
||||
let mod_loaders = if options.loader == ModLoader::Vanilla {
|
||||
Vec::new()
|
||||
} else {
|
||||
vec![ManifestLoader {
|
||||
id: format!(
|
||||
"{}-{}",
|
||||
options.loader.to_string().to_lowercase(),
|
||||
options
|
||||
.loader_version
|
||||
.as_deref()
|
||||
.ok_or("Missing loader version")?
|
||||
),
|
||||
primary: true,
|
||||
}]
|
||||
};
|
||||
let manifest = Manifest {
|
||||
minecraft: Minecraft {
|
||||
version: options.game_version.clone(),
|
||||
mod_loaders,
|
||||
},
|
||||
manifest_type: "minecraftModpack".to_owned(),
|
||||
manifest_version: 1,
|
||||
name: options.name.clone(),
|
||||
version: options.version.clone(),
|
||||
author: options.author.clone(),
|
||||
files: ids
|
||||
.into_iter()
|
||||
.map(|(project_id, file_id)| ManifestFile {
|
||||
project_id,
|
||||
file_id,
|
||||
required: true,
|
||||
})
|
||||
.collect(),
|
||||
overrides: "overrides".to_owned(),
|
||||
};
|
||||
Ok(ArchiveContents {
|
||||
manifests: vec![("manifest.json", serde_json::to_vec_pretty(&manifest)?)],
|
||||
referenced,
|
||||
prefix: "overrides",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) fn prepare(options: &ExportOptions) -> ExportResult<ArchiveContents> {
|
||||
let mut components =
|
||||
vec![serde_json::json!({"uid": "net.minecraft", "version": options.game_version})];
|
||||
let uid = match options.loader {
|
||||
ModLoader::Vanilla => None,
|
||||
ModLoader::Forge => Some("net.minecraftforge"),
|
||||
ModLoader::Fabric => Some("net.fabricmc.fabric-loader"),
|
||||
ModLoader::NeoForge => Some("net.neoforged"),
|
||||
ModLoader::Quilt => Some("org.quiltmc.quilt-loader"),
|
||||
};
|
||||
if let Some(uid) = uid {
|
||||
components.push(serde_json::json!({"uid": uid, "version": options.loader_version}));
|
||||
}
|
||||
let pack = serde_json::json!({"formatVersion": 1, "components": components});
|
||||
let name = if options.name.starts_with('@') {
|
||||
format!("@{}", options.name)
|
||||
} else {
|
||||
options.name.clone()
|
||||
};
|
||||
let cfg = format!(
|
||||
"[General]\nConfigVersion=1.2\nInstanceType=OneSix\nname={}\n",
|
||||
serde_json::to_string(&name)?
|
||||
);
|
||||
Ok(ArchiveContents {
|
||||
manifests: vec![
|
||||
("mmc-pack.json", serde_json::to_vec_pretty(&pack)?),
|
||||
("instance.cfg", cfg.into_bytes()),
|
||||
],
|
||||
referenced: BTreeSet::new(),
|
||||
prefix: ".minecraft",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::*;
|
||||
use crate::instance::import::mrpack::{MrpackFile, MrpackIndex};
|
||||
use crate::net::modrinth::VersionInfo;
|
||||
|
||||
pub(super) async fn prepare(
|
||||
plan: &ExportPlan,
|
||||
progress: &ProgressTask,
|
||||
) -> ExportResult<ArchiveContents> {
|
||||
manifest(plan, &resolve(&plan.files, progress).await?)
|
||||
}
|
||||
|
||||
pub(super) async fn resolve(
|
||||
files: &BTreeMap<PathBuf, FileFingerprint>,
|
||||
progress: &ProgressTask,
|
||||
) -> ExportResult<HashMap<String, VersionInfo>> {
|
||||
let hashes = files
|
||||
.values()
|
||||
.filter_map(|file| file.hash("sha512").map(str::to_owned))
|
||||
.collect::<BTreeSet<_>>()
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>();
|
||||
let client = crate::net::HttpClient::new();
|
||||
let mut matches = HashMap::new();
|
||||
for (index, chunk) in hashes.chunks(100).enumerate() {
|
||||
progress.set_sub_action("Identifying Modrinth content");
|
||||
progress.set_progress((index * 100) as u64, hashes.len() as u64);
|
||||
matches
|
||||
.extend(crate::net::modrinth::resolve_version_files(&client, chunk, "sha512").await?);
|
||||
}
|
||||
Ok(matches)
|
||||
}
|
||||
|
||||
pub(super) fn manifest(
|
||||
plan: &ExportPlan,
|
||||
matches: &HashMap<String, VersionInfo>,
|
||||
) -> ExportResult<ArchiveContents> {
|
||||
let mut referenced = BTreeSet::new();
|
||||
let mut files = Vec::new();
|
||||
for (path, hash) in &plan.files {
|
||||
let Some(sha512) = hash.hash("sha512") else {
|
||||
continue;
|
||||
};
|
||||
let Some(version) = matches.get(sha512) else {
|
||||
continue;
|
||||
};
|
||||
let Some(file) = version.files.iter().find(|file| {
|
||||
file.hashes
|
||||
.get("sha512")
|
||||
.is_some_and(|expected| expected.eq_ignore_ascii_case(sha512))
|
||||
&& file.hashes.get("sha1").is_some_and(|expected| {
|
||||
hash.hash("sha1")
|
||||
.is_some_and(|actual| actual.eq_ignore_ascii_case(expected))
|
||||
})
|
||||
&& file.size == hash.size
|
||||
&& reqwest::Url::parse(&file.url).is_ok_and(|url| {
|
||||
url.scheme() == "https" && url.host_str() == Some("cdn.modrinth.com")
|
||||
})
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
files.push(MrpackFile {
|
||||
path: path
|
||||
.to_str()
|
||||
.ok_or("Export paths must be UTF-8")?
|
||||
.replace('\\', "/"),
|
||||
hashes: ["sha1", "sha512"]
|
||||
.into_iter()
|
||||
.map(|algorithm| {
|
||||
(
|
||||
algorithm.to_owned(),
|
||||
hash.hash(algorithm).unwrap().to_owned(),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
// Installed client content does not establish server compatibility.
|
||||
env: HashMap::from([
|
||||
("client".to_owned(), "required".to_owned()),
|
||||
("server".to_owned(), "unsupported".to_owned()),
|
||||
]),
|
||||
downloads: vec![file.url.clone()],
|
||||
file_size: hash.size,
|
||||
});
|
||||
referenced.insert(path.clone());
|
||||
}
|
||||
let options = &plan.options;
|
||||
let mut dependencies = HashMap::from([("minecraft".to_owned(), options.game_version.clone())]);
|
||||
let loader = match options.loader {
|
||||
ModLoader::Vanilla => None,
|
||||
ModLoader::Forge => Some("forge"),
|
||||
ModLoader::Fabric => Some("fabric-loader"),
|
||||
ModLoader::NeoForge => Some("neoforge"),
|
||||
ModLoader::Quilt => Some("quilt-loader"),
|
||||
};
|
||||
if let Some(loader) = loader {
|
||||
dependencies.insert(
|
||||
loader.to_owned(),
|
||||
options
|
||||
.loader_version
|
||||
.clone()
|
||||
.ok_or("Missing loader version")?,
|
||||
);
|
||||
}
|
||||
let index = MrpackIndex {
|
||||
format_version: 1,
|
||||
game: "minecraft".to_owned(),
|
||||
version_id: options.version.clone(),
|
||||
name: options.name.clone(),
|
||||
dependencies,
|
||||
files,
|
||||
};
|
||||
Ok(ArchiveContents {
|
||||
manifests: vec![("modrinth.index.json", serde_json::to_vec_pretty(&index)?)],
|
||||
referenced,
|
||||
prefix: "client-overrides",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct GlfwInstallation {
|
||||
pub path: PathBuf,
|
||||
pub version: Option<String>,
|
||||
}
|
||||
|
||||
pub(crate) fn bundled_glfw_version(meta_dir: &Path, game_version: &str) -> Option<String> {
|
||||
let path = crate::storage::MetadataPaths::new(meta_dir)
|
||||
.versions()
|
||||
.join(game_version)
|
||||
.join("meta.json");
|
||||
let profile: serde_json::Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
|
||||
profile
|
||||
.get("libraries")?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter_map(|library| library.get("name")?.as_str())
|
||||
.find_map(|coordinate| {
|
||||
let mut parts = coordinate.split(':');
|
||||
match (parts.next(), parts.next(), parts.next()) {
|
||||
(Some("org.lwjgl"), Some("lwjgl-glfw"), Some(version)) => Some(version.to_owned()),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn discover_glfw_installations() -> Vec<GlfwInstallation> {
|
||||
discover_in(&discovery_directories(), std::env::consts::OS)
|
||||
}
|
||||
|
||||
fn discovery_directories() -> Vec<PathBuf> {
|
||||
let mut directories = Vec::<PathBuf>::new();
|
||||
let variables: &[&str] = match std::env::consts::OS {
|
||||
"windows" => &["PATH"],
|
||||
"macos" => &["DYLD_LIBRARY_PATH", "DYLD_FALLBACK_LIBRARY_PATH", "PATH"],
|
||||
_ => &["LD_LIBRARY_PATH", "PATH"],
|
||||
};
|
||||
for variable in variables {
|
||||
if let Some(value) = std::env::var_os(variable) {
|
||||
directories.extend(std::env::split_paths(&value));
|
||||
}
|
||||
}
|
||||
match std::env::consts::OS {
|
||||
"windows" => {
|
||||
if let Some(root) = std::env::var_os("SystemRoot") {
|
||||
let root = PathBuf::from(root);
|
||||
directories.extend([root.join("System32"), root.clone()]);
|
||||
}
|
||||
}
|
||||
"macos" => {
|
||||
directories.extend(
|
||||
[
|
||||
"/usr/lib",
|
||||
"/usr/local/lib",
|
||||
"/opt/homebrew/lib",
|
||||
"/opt/local/lib",
|
||||
]
|
||||
.into_iter()
|
||||
.map(PathBuf::from),
|
||||
);
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
directories.push(home.join("lib"));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
directories.extend(
|
||||
["/usr/lib", "/usr/lib64", "/usr/local/lib", "/lib", "/lib64"]
|
||||
.into_iter()
|
||||
.map(PathBuf::from),
|
||||
);
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
directories.push(home.join(".local/lib"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(executable) = std::env::current_exe()
|
||||
&& let Some(parent) = executable.parent()
|
||||
{
|
||||
directories.push(parent.to_owned());
|
||||
}
|
||||
if let Ok(directory) = std::env::current_dir() {
|
||||
directories.push(directory);
|
||||
}
|
||||
directories.sort();
|
||||
directories.dedup();
|
||||
directories
|
||||
}
|
||||
|
||||
fn discover_in(roots: &[PathBuf], os: &str) -> Vec<GlfwInstallation> {
|
||||
let mut directories = roots.to_vec();
|
||||
let mut nested = Vec::new();
|
||||
for directory in &directories {
|
||||
if let Ok(entries) = std::fs::read_dir(directory) {
|
||||
nested.extend(
|
||||
entries
|
||||
.flatten()
|
||||
.map(|entry| entry.path())
|
||||
.filter(|path| path.is_dir()),
|
||||
);
|
||||
}
|
||||
}
|
||||
directories.extend(nested);
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut installations = Vec::new();
|
||||
for directory in directories {
|
||||
let Ok(entries) = std::fs::read_dir(directory) else {
|
||||
continue;
|
||||
};
|
||||
for path in entries.flatten().map(|entry| entry.path()) {
|
||||
if !path.is_file()
|
||||
|| !path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.is_some_and(|name| is_glfw_library_name(name, os))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let canonical = std::fs::canonicalize(&path).unwrap_or(path);
|
||||
if seen.insert(canonical.clone()) {
|
||||
installations.push(GlfwInstallation {
|
||||
version: glfw_version_from_path(&canonical),
|
||||
path: canonical,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
installations.sort_by(|left, right| left.path.cmp(&right.path));
|
||||
installations
|
||||
}
|
||||
|
||||
fn is_glfw_library_name(name: &str, os: &str) -> bool {
|
||||
let name = name.to_ascii_lowercase();
|
||||
let versioned_so = name.strip_prefix("libglfw.so.").is_some_and(|version| {
|
||||
version.split('.').all(|part| {
|
||||
!part.is_empty() && part.chars().all(|character| character.is_ascii_digit())
|
||||
})
|
||||
});
|
||||
match os {
|
||||
"windows" => name.starts_with("glfw") && name.ends_with(".dll"),
|
||||
"macos" => name.starts_with("libglfw.") && name.ends_with(".dylib"),
|
||||
_ => name == "libglfw.so" || versioned_so,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn glfw_version_from_path(path: &Path) -> Option<String> {
|
||||
let name = path.file_name()?.to_str()?.to_ascii_lowercase();
|
||||
if let Some((_, suffix)) = name.rsplit_once(".so.") {
|
||||
return (!suffix.is_empty()).then(|| suffix.to_owned());
|
||||
}
|
||||
let stem = name
|
||||
.strip_prefix("libglfw.")
|
||||
.and_then(|name| name.strip_suffix(".dylib"))
|
||||
.or_else(|| {
|
||||
name.strip_prefix("glfw")
|
||||
.and_then(|name| name.strip_suffix(".dll"))
|
||||
})?;
|
||||
(!stem.is_empty()).then(|| stem.trim_start_matches(['-', '.']).to_owned())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn library_names_are_recognized() {
|
||||
assert!(is_glfw_library_name("libglfw.so.3", "linux"));
|
||||
assert!(is_glfw_library_name("libglfw.3.dylib", "macos"));
|
||||
assert!(is_glfw_library_name("glfw3.dll", "windows"));
|
||||
assert!(!is_glfw_library_name("libglfw.so.backup", "linux"));
|
||||
assert!(!is_glfw_library_name("libGL.so", "linux"));
|
||||
assert_eq!(
|
||||
glfw_version_from_path(Path::new("/usr/lib/libglfw.so.3.4")).as_deref(),
|
||||
Some("3.4")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_platform_discovers_its_native_libraries_in_environment_and_nested_directories() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let nested = temp.path().join("native");
|
||||
std::fs::create_dir(&nested).unwrap();
|
||||
for name in ["libglfw.so.3.4", "libglfw.3.dylib", "GLFW3.DLL"] {
|
||||
std::fs::write(temp.path().join(name), b"library").unwrap();
|
||||
std::fs::write(nested.join(name), b"library").unwrap();
|
||||
}
|
||||
for (os, expected, version) in [
|
||||
("linux", "libglfw.so.3.4", "3.4"),
|
||||
("macos", "libglfw.3.dylib", "3"),
|
||||
("windows", "GLFW3.DLL", "3"),
|
||||
] {
|
||||
let found = discover_in(&[temp.path().to_owned(), temp.path().to_owned()], os);
|
||||
assert_eq!(found.len(), 2, "{os}");
|
||||
assert!(
|
||||
found
|
||||
.iter()
|
||||
.all(|installation| installation.path.file_name().unwrap() == expected)
|
||||
);
|
||||
assert!(
|
||||
found
|
||||
.iter()
|
||||
.all(|installation| installation.version.as_deref() == Some(version))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const MAX_PACK_MANIFEST_BYTES: u64 = 8 * 1024 * 1024;
|
||||
|
||||
pub(super) fn read_pack_manifest(reader: impl Read) -> Result<Vec<u8>, String> {
|
||||
let mut bytes = Vec::new();
|
||||
reader
|
||||
.take(MAX_PACK_MANIFEST_BYTES + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|error| error.to_string())?;
|
||||
if bytes.len() as u64 > MAX_PACK_MANIFEST_BYTES {
|
||||
return Err("Pack manifest exceeds 8 MiB".to_owned());
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn relative_path(
|
||||
entry: &zip::read::ZipFile<'_, std::fs::File>,
|
||||
root: &str,
|
||||
) -> Result<Option<PathBuf>, String> {
|
||||
let root = root.trim_matches('/');
|
||||
if root.is_empty() || !entry.name().starts_with(&format!("{root}/")) {
|
||||
return Ok(None);
|
||||
}
|
||||
let enclosed = entry
|
||||
.enclosed_name()
|
||||
.ok_or_else(|| format!("Unsafe override path: {}", entry.name()))?;
|
||||
let relative = enclosed
|
||||
.strip_prefix(root)
|
||||
.map_err(|_| format!("Invalid override path: {}", entry.name()))?;
|
||||
if relative.as_os_str().is_empty() {
|
||||
return Ok(Some(relative.to_owned()));
|
||||
}
|
||||
let relative = relative
|
||||
.to_str()
|
||||
.ok_or_else(|| "Override path is not UTF-8".to_owned())?;
|
||||
Ok(Some(PathBuf::from(super::portable_pack_path(relative)?)))
|
||||
}
|
||||
|
||||
pub(super) fn override_files(path: &Path, roots: &[&str]) -> Result<Vec<PathBuf>, String> {
|
||||
let file = std::fs::File::open(path).map_err(|error| error.to_string())?;
|
||||
let mut archive = zip::ZipArchive::new(file).map_err(|error| error.to_string())?;
|
||||
let mut files = Vec::new();
|
||||
for index in 0..archive.len() {
|
||||
let entry = archive.by_index(index).map_err(|error| error.to_string())?;
|
||||
if entry.is_dir() {
|
||||
continue;
|
||||
}
|
||||
for root in roots {
|
||||
if let Some(relative) = relative_path(&entry, root)?
|
||||
&& !relative.as_os_str().is_empty()
|
||||
{
|
||||
files.push(relative);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
pub(super) fn extract_overrides(
|
||||
path: &Path,
|
||||
destination: &Path,
|
||||
roots: &[&str],
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
let file = std::fs::File::open(path)?;
|
||||
let mut archive = zip::ZipArchive::new(file)?;
|
||||
// Later roots override earlier ones, independently of ZIP entry order.
|
||||
for root in roots {
|
||||
for index in 0..archive.len() {
|
||||
let mut entry = archive.by_index(index)?;
|
||||
let Some(relative) = relative_path(&entry, root)? else {
|
||||
continue;
|
||||
};
|
||||
let target = destination.join(relative);
|
||||
if entry.is_dir() {
|
||||
std::fs::create_dir_all(&target)?;
|
||||
continue;
|
||||
}
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let mut file = std::fs::File::create(&target)?;
|
||||
let size = std::io::copy(&mut entry, &mut file)?;
|
||||
tracing::trace!(
|
||||
"Extracted {} to {} ({} bytes)",
|
||||
entry.name(),
|
||||
target.display(),
|
||||
size
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,54 +1,57 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// curseforge modpack archives: manifest.json references provider file ids,
|
||||
// while the overrides directory contains configs and other bundled files.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::feedback::progress;
|
||||
use crate::instance::{InstanceConfig, InstanceManager, ModLoader};
|
||||
|
||||
use super::{ImportSummary, PackFormat};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Manifest {
|
||||
name: String,
|
||||
version: String,
|
||||
minecraft: Minecraft,
|
||||
pub(crate) struct Manifest {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub minecraft: Minecraft,
|
||||
#[serde(default)]
|
||||
files: Vec<ManifestFile>,
|
||||
pub author: String,
|
||||
#[serde(default)]
|
||||
pub manifest_type: String,
|
||||
#[serde(default)]
|
||||
pub manifest_version: u32,
|
||||
#[serde(default)]
|
||||
pub files: Vec<ManifestFile>,
|
||||
#[serde(default = "default_overrides")]
|
||||
overrides: String,
|
||||
pub overrides: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Minecraft {
|
||||
version: String,
|
||||
pub(crate) struct Minecraft {
|
||||
pub version: String,
|
||||
#[serde(default)]
|
||||
mod_loaders: Vec<ManifestLoader>,
|
||||
pub mod_loaders: Vec<ManifestLoader>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ManifestLoader {
|
||||
id: String,
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub(crate) struct ManifestLoader {
|
||||
pub id: String,
|
||||
#[serde(default)]
|
||||
primary: bool,
|
||||
pub primary: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ManifestFile {
|
||||
pub(crate) struct ManifestFile {
|
||||
#[serde(rename = "projectID")]
|
||||
_project_id: u64,
|
||||
pub project_id: u64,
|
||||
#[serde(rename = "fileID")]
|
||||
file_id: u64,
|
||||
pub file_id: u64,
|
||||
#[serde(default = "required_by_default")]
|
||||
required: bool,
|
||||
pub required: bool,
|
||||
}
|
||||
|
||||
fn default_overrides() -> String {
|
||||
@@ -65,7 +68,8 @@ fn parse(path: &Path) -> Result<Manifest, String> {
|
||||
let entry = archive
|
||||
.by_name("manifest.json")
|
||||
.map_err(|_| "Missing manifest.json in CurseForge pack".to_owned())?;
|
||||
serde_json::from_reader(entry).map_err(|error| format!("Invalid CurseForge manifest: {error}"))
|
||||
let raw = super::read_pack_manifest(entry)?;
|
||||
serde_json::from_slice(&raw).map_err(|error| format!("Invalid CurseForge manifest: {error}"))
|
||||
}
|
||||
|
||||
fn loader(manifest: &Manifest) -> (ModLoader, Option<String>) {
|
||||
@@ -96,7 +100,7 @@ fn loader(manifest: &Manifest) -> (ModLoader, Option<String>) {
|
||||
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||
let manifest = parse(path)?;
|
||||
let (loader, loader_version) = loader(&manifest);
|
||||
let override_count = count_overrides(path, &manifest.overrides)?;
|
||||
let override_count = super::override_files(path, &[&manifest.overrides])?.len();
|
||||
Ok(ImportSummary {
|
||||
name: manifest.name,
|
||||
pack_version: manifest.version,
|
||||
@@ -114,51 +118,35 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||
pub async fn execute_import(
|
||||
summary: &ImportSummary,
|
||||
manager: &InstanceManager,
|
||||
) -> Result<InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let name = super::unique_instance_name(&summary.name, &manager.instances_dir);
|
||||
progress::set_action(format!("Importing '{name}'..."));
|
||||
progress::set_sub_action(format!("{} {}", summary.game_version, summary.loader));
|
||||
let config = manager
|
||||
.create(
|
||||
&name,
|
||||
&summary.game_version,
|
||||
summary.loader,
|
||||
summary.loader_version.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| -> Box<dyn std::error::Error + Send + Sync> { Box::new(error) })?;
|
||||
config: &InstanceConfig,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
crate::instance::manager::validate_name(&config.name)?;
|
||||
let minecraft_dir = manager
|
||||
.instances_dir
|
||||
.join(&name)
|
||||
.join(&config.name)
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||
let result = async {
|
||||
let manifest = parse(&summary.archive_path)?;
|
||||
download_files(&manifest, &minecraft_dir).await?;
|
||||
extract_overrides(&summary.archive_path, &minecraft_dir, &manifest.overrides)?;
|
||||
Ok::<(), Box<dyn std::error::Error + Send + Sync>>(())
|
||||
}
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
super::cleanup_failed_import(manager, &name);
|
||||
return Err(error);
|
||||
}
|
||||
progress::clear();
|
||||
Ok(config)
|
||||
let manifest = parse(&summary.archive_path)?;
|
||||
download_files(&manifest, &minecraft_dir).await?;
|
||||
extract_overrides(&summary.archive_path, &minecraft_dir, &manifest.overrides)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn download_files(
|
||||
manifest: &Manifest,
|
||||
minecraft_dir: &Path,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
let api_key =
|
||||
crate::net::curseforge::api_key().ok_or("CurseForge API key is not configured")?;
|
||||
let client = crate::net::HttpClient::new();
|
||||
let ids = manifest
|
||||
.files
|
||||
.iter()
|
||||
.filter(|file| file.required)
|
||||
.map(|file| file.file_id)
|
||||
.collect::<Vec<_>>();
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let api_key =
|
||||
crate::net::curseforge::api_key().ok_or("CurseForge API key is not configured")?;
|
||||
let client = crate::net::HttpClient::new();
|
||||
let versions = crate::net::curseforge::fetch_file_versions(&client, api_key, &ids).await?;
|
||||
if versions.len() != ids.len() {
|
||||
return Err(format!(
|
||||
@@ -198,14 +186,18 @@ async fn download_files(
|
||||
|
||||
pub(super) async fn owned_files(path: &Path) -> Result<Vec<std::path::PathBuf>, String> {
|
||||
let manifest = parse(path)?;
|
||||
let api_key = crate::net::curseforge::api_key()
|
||||
.ok_or_else(|| "CurseForge API key is not configured".to_owned())?;
|
||||
let overrides = super::override_files(path, &[manifest.overrides.trim_matches('/')])?;
|
||||
let ids = manifest
|
||||
.files
|
||||
.iter()
|
||||
.filter(|file| file.required)
|
||||
.map(|file| file.file_id)
|
||||
.collect::<Vec<_>>();
|
||||
if ids.is_empty() {
|
||||
return Ok(overrides);
|
||||
}
|
||||
let api_key = crate::net::curseforge::api_key()
|
||||
.ok_or_else(|| "CurseForge API key is not configured".to_owned())?;
|
||||
let versions =
|
||||
crate::net::curseforge::fetch_file_versions(&crate::net::HttpClient::new(), api_key, &ids)
|
||||
.await
|
||||
@@ -217,7 +209,7 @@ pub(super) async fn owned_files(path: &Path) -> Result<Vec<std::path::PathBuf>,
|
||||
ids.len()
|
||||
));
|
||||
}
|
||||
versions
|
||||
let mut files: Vec<_> = versions
|
||||
.into_iter()
|
||||
.map(|version| {
|
||||
version
|
||||
@@ -225,24 +217,13 @@ pub(super) async fn owned_files(path: &Path) -> Result<Vec<std::path::PathBuf>,
|
||||
.iter()
|
||||
.find(|file| file.primary)
|
||||
.or_else(|| version.files.first())
|
||||
.map(|file| std::path::PathBuf::from("mods").join(&file.filename))
|
||||
.ok_or_else(|| format!("CurseForge file '{}' has no artifact", version.id))
|
||||
.and_then(|file| super::portable_pack_path(&format!("mods/{}", file.filename)))
|
||||
.map(std::path::PathBuf::from)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn count_overrides(path: &Path, root: &str) -> Result<usize, String> {
|
||||
let root = root.trim_matches('/');
|
||||
if root.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let file = std::fs::File::open(path).map_err(|error| error.to_string())?;
|
||||
let archive = zip::ZipArchive::new(file).map_err(|error| error.to_string())?;
|
||||
let prefix = format!("{root}/");
|
||||
Ok(archive
|
||||
.file_names()
|
||||
.filter(|name| name.starts_with(&prefix) && !name.ends_with('/'))
|
||||
.count())
|
||||
.collect::<Result<_, _>>()?;
|
||||
files.extend(overrides);
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn extract_overrides(
|
||||
@@ -251,33 +232,7 @@ fn extract_overrides(
|
||||
root: &str,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
progress::set_action("Extracting overrides...");
|
||||
let file = std::fs::File::open(path)?;
|
||||
let mut archive = zip::ZipArchive::new(file)?;
|
||||
let root = root.trim_matches('/');
|
||||
if root.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
for index in 0..archive.len() {
|
||||
let mut entry = archive.by_index(index)?;
|
||||
let enclosed = entry.enclosed_name().ok_or("Unsafe override path")?;
|
||||
let Ok(relative) = enclosed.strip_prefix(root) else {
|
||||
continue;
|
||||
};
|
||||
if relative.as_os_str().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let destination = minecraft_dir.join(relative);
|
||||
if entry.is_dir() {
|
||||
std::fs::create_dir_all(destination)?;
|
||||
continue;
|
||||
}
|
||||
if let Some(parent) = destination.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let mut destination = std::fs::File::create(destination)?;
|
||||
std::io::copy(&mut entry, &mut destination)?;
|
||||
}
|
||||
Ok(())
|
||||
super::archive::extract_overrides(path, minecraft_dir, &[root])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+34
-48
@@ -1,10 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// multimc / prism launcher instance import: mods and configs are bundled
|
||||
// in the zip. we install the game + loader normally, then extract the
|
||||
// archive contents over it.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use crate::feedback::progress;
|
||||
@@ -97,52 +93,33 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||
pub async fn execute_import(
|
||||
summary: &ImportSummary,
|
||||
manager: &InstanceManager,
|
||||
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let name = super::unique_instance_name(&summary.name, &manager.instances_dir);
|
||||
config: &crate::instance::InstanceConfig,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
crate::instance::manager::validate_name(&config.name)?;
|
||||
tracing::info!(
|
||||
"Importing MultiMC/Prism pack '{}' as instance '{}'",
|
||||
summary.name,
|
||||
name
|
||||
config.name
|
||||
);
|
||||
|
||||
progress::set_action(format!("Importing '{name}'..."));
|
||||
progress::set_sub_action(format!("{} {}", summary.game_version, summary.loader));
|
||||
|
||||
let config = manager
|
||||
.create(
|
||||
&name,
|
||||
&summary.game_version,
|
||||
summary.loader,
|
||||
summary.loader_version.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?;
|
||||
|
||||
let minecraft_dir = manager
|
||||
.instances_dir
|
||||
.join(&name)
|
||||
.join(&config.name)
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||
if let Err(error) = extract_mmc_archive(&summary.archive_path, &minecraft_dir) {
|
||||
super::cleanup_failed_import(manager, &name);
|
||||
return Err(error);
|
||||
}
|
||||
extract_mmc_archive(&summary.archive_path, &minecraft_dir)?;
|
||||
|
||||
progress::clear();
|
||||
tracing::info!(
|
||||
"Imported MultiMC/Prism pack '{}' as '{}'",
|
||||
summary.name,
|
||||
name
|
||||
config.name
|
||||
);
|
||||
Ok(config)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// extracts everything under .minecraft/ from the archive into the instance dir
|
||||
fn extract_mmc_archive(
|
||||
archive_path: &Path,
|
||||
minecraft_dir: &Path,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
use std::io::Read;
|
||||
|
||||
progress::set_action("Extracting pack contents...".to_string());
|
||||
progress::set_sub_action(String::new());
|
||||
|
||||
@@ -183,13 +160,20 @@ fn extract_mmc_archive(
|
||||
)
|
||||
})?;
|
||||
|
||||
let relative = if relative.as_os_str().is_empty() {
|
||||
std::path::PathBuf::new()
|
||||
} else {
|
||||
std::path::PathBuf::from(super::portable_pack_path(
|
||||
relative.to_str().ok_or("Archive path is not UTF-8")?,
|
||||
)?)
|
||||
};
|
||||
if relative.as_os_str().is_empty() || entry_name.ends_with('/') {
|
||||
std::fs::create_dir_all(minecraft_dir.join(relative))?;
|
||||
std::fs::create_dir_all(minecraft_dir.join(&relative))?;
|
||||
dirs += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let dest = minecraft_dir.join(relative);
|
||||
let dest = minecraft_dir.join(&relative);
|
||||
if let Some(parent) = dest.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
@@ -200,15 +184,14 @@ fn extract_mmc_archive(
|
||||
.unwrap_or_default();
|
||||
progress::set_sub_action(filename.to_string());
|
||||
|
||||
let mut buf = Vec::new();
|
||||
entry.read_to_end(&mut buf)?;
|
||||
let mut destination = std::fs::File::create(&dest)?;
|
||||
let size = std::io::copy(&mut entry, &mut destination)?;
|
||||
tracing::trace!(
|
||||
"Extracting MultiMC entry {} to {} ({} bytes)",
|
||||
entry_name,
|
||||
dest.display(),
|
||||
buf.len()
|
||||
size
|
||||
);
|
||||
std::fs::write(&dest, &buf)?;
|
||||
extracted += 1;
|
||||
}
|
||||
|
||||
@@ -232,7 +215,8 @@ fn parse_mmc_pack(path: &Path) -> Result<MmcPack, String> {
|
||||
.by_name(&entry_name)
|
||||
.map_err(|e| format!("Failed to read mmc-pack.json: {e}"))?;
|
||||
|
||||
serde_json::from_reader(entry).map_err(|e| format!("Invalid mmc-pack.json: {e}"))
|
||||
let raw = super::read_pack_manifest(entry)?;
|
||||
serde_json::from_slice(&raw).map_err(|e| format!("Invalid mmc-pack.json: {e}"))
|
||||
}
|
||||
|
||||
fn instance_name_from_cfg(path: &Path) -> Option<String> {
|
||||
@@ -242,11 +226,17 @@ fn instance_name_from_cfg(path: &Path) -> Option<String> {
|
||||
let entry_name = find_entry(&archive, "instance.cfg")?;
|
||||
tracing::trace!("Reading instance name from {}", entry_name);
|
||||
let entry = archive.by_name(&entry_name).ok()?;
|
||||
|
||||
let reader = std::io::BufRead::lines(std::io::BufReader::new(entry));
|
||||
let raw = super::read_pack_manifest(entry).ok()?;
|
||||
let reader = std::io::BufRead::lines(std::io::BufReader::new(raw.as_slice()));
|
||||
for line in reader.map_while(Result::ok) {
|
||||
if let Some(value) = line.strip_prefix("name=") {
|
||||
let name = value.trim().to_string();
|
||||
let value = value.trim();
|
||||
let name = serde_json::from_str::<String>(value).unwrap_or_else(|_| value.to_owned());
|
||||
let name = if name.starts_with("@@") {
|
||||
name[1..].to_owned()
|
||||
} else {
|
||||
name
|
||||
};
|
||||
if !name.is_empty() {
|
||||
tracing::debug!("Read MultiMC instance name '{}' from instance.cfg", name);
|
||||
return Some(name);
|
||||
@@ -256,14 +246,10 @@ fn instance_name_from_cfg(path: &Path) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
// finds the prefix for the archive: empty for flat zips, "DirName/" for nested
|
||||
fn find_archive_prefix(archive: &zip::ZipArchive<std::fs::File>) -> String {
|
||||
for name in archive.file_names() {
|
||||
if name.ends_with("mmc-pack.json") {
|
||||
return name.strip_suffix("mmc-pack.json").unwrap_or("").to_string();
|
||||
}
|
||||
}
|
||||
String::new()
|
||||
find_entry(archive, "mmc-pack.json")
|
||||
.and_then(|name| name.strip_suffix("mmc-pack.json").map(str::to_owned))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
// looks for a file at root or one level deep (some archives nest everything
|
||||
|
||||
+94
-67
@@ -1,9 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// modpack importing: parses user input, detects pack format from zip contents,
|
||||
// builds a summary, and delegates the actual import to format-specific modules.
|
||||
|
||||
mod archive;
|
||||
pub mod curseforge;
|
||||
pub mod mmc;
|
||||
pub mod mrpack;
|
||||
@@ -11,15 +9,12 @@ pub mod refresh;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use archive::{override_files, read_pack_manifest};
|
||||
|
||||
use crate::instance::manager::InstanceManager;
|
||||
use crate::instance::models::ModLoader;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PackFormat {
|
||||
CurseForge,
|
||||
Mrpack,
|
||||
Mmc,
|
||||
}
|
||||
pub use super::pack::PackFormat;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum ImportInput {
|
||||
@@ -28,21 +23,9 @@ pub enum ImportInput {
|
||||
LocalFile(String),
|
||||
}
|
||||
|
||||
// figures out what the user gave us: a modrinth URL, a local pack file,
|
||||
// or just a project slug. accepts a pretty wide range of inputs so users
|
||||
// don't have to think about it.
|
||||
pub fn parse_import_input(input: &str) -> ImportInput {
|
||||
let input = input.trim();
|
||||
|
||||
if input.ends_with(".mrpack")
|
||||
|| input.ends_with(".zip")
|
||||
|| input.starts_with('/')
|
||||
|| input.starts_with("~/")
|
||||
{
|
||||
tracing::debug!("Import input resolved as local file: {}", input);
|
||||
return ImportInput::LocalFile(input.to_string());
|
||||
}
|
||||
|
||||
if let Some(rest) = input
|
||||
.strip_prefix("https://modrinth.com/modpack/")
|
||||
.or_else(|| input.strip_prefix("http://modrinth.com/modpack/"))
|
||||
@@ -60,6 +43,22 @@ pub fn parse_import_input(input: &str) -> ImportInput {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
if input.rsplit_once('.').is_some_and(|(_, extension)| {
|
||||
extension.eq_ignore_ascii_case("mrpack") || extension.eq_ignore_ascii_case("zip")
|
||||
}) || input.starts_with('/')
|
||||
|| input.starts_with("~/")
|
||||
|| input.starts_with("./")
|
||||
|| input.starts_with("../")
|
||||
|| input.contains('\\')
|
||||
|| input
|
||||
.as_bytes()
|
||||
.get(..2)
|
||||
.is_some_and(|prefix| prefix[0].is_ascii_alphabetic() && prefix[1] == b':')
|
||||
{
|
||||
tracing::debug!("Import input resolved as local file: {}", input);
|
||||
return ImportInput::LocalFile(input.to_string());
|
||||
}
|
||||
|
||||
tracing::debug!("Import input resolved as Modrinth project slug: {}", input);
|
||||
ImportInput::ProjectSlug(input.to_string())
|
||||
}
|
||||
@@ -78,8 +77,6 @@ pub struct ImportSummary {
|
||||
pub source: Option<crate::instance::ProviderProject>,
|
||||
}
|
||||
|
||||
// peeks inside a zip to figure out what format it is.
|
||||
// checks provider manifests first, then mmc-pack.json.
|
||||
pub fn detect_format(path: &Path) -> Result<PackFormat, String> {
|
||||
tracing::debug!("Detecting modpack format for {}", path.display());
|
||||
let file =
|
||||
@@ -138,36 +135,30 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
|
||||
pub fn unique_instance_name(
|
||||
base: &str,
|
||||
instances_dir: &Path,
|
||||
) -> Result<String, crate::instance::manager::InstanceError> {
|
||||
crate::instance::manager::validate_name(base)?;
|
||||
let candidate = base.to_string();
|
||||
if !instances_dir
|
||||
.join(&candidate)
|
||||
.join("instance.json")
|
||||
.exists()
|
||||
{
|
||||
if !instances_dir.join(&candidate).exists() {
|
||||
tracing::trace!("Import instance name '{}' is available", candidate);
|
||||
return candidate;
|
||||
return Ok(candidate);
|
||||
}
|
||||
for n in 2..100 {
|
||||
let mut n = 2;
|
||||
loop {
|
||||
let candidate = format!("{base} ({n})");
|
||||
if !instances_dir
|
||||
.join(&candidate)
|
||||
.join("instance.json")
|
||||
.exists()
|
||||
{
|
||||
crate::instance::manager::validate_name(&candidate)?;
|
||||
if !instances_dir.join(&candidate).exists() {
|
||||
tracing::debug!(
|
||||
"Import instance name '{}' collided; using '{}'",
|
||||
base,
|
||||
candidate
|
||||
);
|
||||
return candidate;
|
||||
return Ok(candidate);
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
tracing::warn!(
|
||||
"Import instance name '{}' had many collisions; using fallback suffix",
|
||||
base
|
||||
);
|
||||
format!("{base} (import)")
|
||||
}
|
||||
|
||||
pub async fn execute_import(
|
||||
@@ -180,32 +171,53 @@ pub async fn execute_import(
|
||||
summary.name,
|
||||
summary.archive_path.display()
|
||||
);
|
||||
let mut config = match summary.format {
|
||||
PackFormat::CurseForge => curseforge::execute_import(summary, manager).await,
|
||||
PackFormat::Mrpack => mrpack::execute_import(summary, manager).await,
|
||||
PackFormat::Mmc => mmc::execute_import(summary, manager).await,
|
||||
}?;
|
||||
if summary.source.is_some() {
|
||||
config.modpack_source = summary.source.clone();
|
||||
manager.save(&config)?;
|
||||
let state = match owned_files(summary).await {
|
||||
Ok(files) => refresh::PackState {
|
||||
source: summary.source.clone().expect("source checked above"),
|
||||
files,
|
||||
},
|
||||
Err(error) => {
|
||||
cleanup_failed_import(manager, &config.name);
|
||||
return Err(error.into());
|
||||
}
|
||||
};
|
||||
if let Err(error) = state.save(&crate::storage::InstancePaths::new(
|
||||
manager.instances_dir.join(&config.name),
|
||||
)) {
|
||||
cleanup_failed_import(manager, &config.name);
|
||||
return Err(error.into());
|
||||
let name = unique_instance_name(&summary.name, &manager.instances_dir)
|
||||
.inspect_err(|_| crate::feedback::progress::clear())?;
|
||||
crate::feedback::progress::set_action("Importing instance...");
|
||||
crate::feedback::progress::set_sub_action(format!(
|
||||
"{} {}",
|
||||
summary.game_version, summary.loader
|
||||
));
|
||||
let config = manager
|
||||
.create(
|
||||
&name,
|
||||
&summary.game_version,
|
||||
summary.loader,
|
||||
summary.loader_version.as_deref(),
|
||||
)
|
||||
.await;
|
||||
let mut config = match config {
|
||||
Ok(config) => config,
|
||||
Err(error) => {
|
||||
crate::feedback::progress::clear();
|
||||
return Err(Box::new(error));
|
||||
}
|
||||
};
|
||||
let result = async {
|
||||
match summary.format {
|
||||
PackFormat::CurseForge => curseforge::execute_import(summary, manager, &config).await?,
|
||||
PackFormat::Mrpack => mrpack::execute_import(summary, manager, &config).await?,
|
||||
PackFormat::Mmc => mmc::execute_import(summary, manager, &config).await?,
|
||||
}
|
||||
if let Some(source) = &summary.source {
|
||||
config.modpack_source = Some(source.clone());
|
||||
manager.save(&config)?;
|
||||
let state = refresh::PackState {
|
||||
source: source.clone(),
|
||||
files: owned_files(summary).await?,
|
||||
};
|
||||
state.save(&crate::storage::InstancePaths::new(
|
||||
manager.instances_dir.join(&config.name),
|
||||
))?;
|
||||
}
|
||||
Ok::<_, Box<dyn std::error::Error + Send + Sync>>(config)
|
||||
}
|
||||
Ok(config)
|
||||
.await;
|
||||
crate::feedback::progress::clear();
|
||||
if result.is_err() {
|
||||
cleanup_failed_import(manager, &name);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub async fn provider_versions(
|
||||
@@ -267,7 +279,10 @@ async fn owned_files(summary: &ImportSummary) -> Result<Vec<PathBuf>, String> {
|
||||
}
|
||||
|
||||
fn cleanup_failed_import(manager: &InstanceManager, name: &str) {
|
||||
crate::feedback::progress::clear();
|
||||
if let Err(error) = crate::instance::manager::validate_name(name) {
|
||||
tracing::warn!("Refusing to clean up an invalid imported instance: {error}");
|
||||
return;
|
||||
}
|
||||
let instance_dir = manager.instances_dir.join(name);
|
||||
if let Err(error) = std::fs::remove_dir_all(&instance_dir)
|
||||
&& error.kind() != std::io::ErrorKind::NotFound
|
||||
@@ -280,6 +295,18 @@ fn cleanup_failed_import(manager: &InstanceManager, name: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn portable_pack_path(path: &str) -> Result<String, String> {
|
||||
let normalized = path.replace('\\', "/");
|
||||
if !crate::storage::safe_relative_path(Path::new(&normalized))
|
||||
|| !normalized
|
||||
.split('/')
|
||||
.all(crate::instance::manager::portable_component)
|
||||
{
|
||||
return Err(format!("Unsafe pack-owned path: {path:?}"));
|
||||
}
|
||||
Ok(normalized)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../tests/import/format_detection.rs"]
|
||||
mod tests;
|
||||
+76
-203
@@ -1,13 +1,10 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// modrinth .mrpack import: parse the manifest, download all the mods,
|
||||
// and extract config/resource overrides from the zip
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::feedback::progress;
|
||||
use crate::instance::content::manifest::{
|
||||
@@ -19,7 +16,7 @@ use crate::storage::InstancePaths;
|
||||
|
||||
use super::{ImportSummary, PackFormat};
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct MrpackIndex {
|
||||
#[serde(rename = "formatVersion")]
|
||||
pub format_version: u32,
|
||||
@@ -33,17 +30,28 @@ pub struct MrpackIndex {
|
||||
pub files: Vec<MrpackFile>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct MrpackFile {
|
||||
pub path: String,
|
||||
#[serde(default)]
|
||||
pub hashes: HashMap<String, String>,
|
||||
#[serde(default)]
|
||||
pub env: HashMap<String, String>,
|
||||
pub downloads: Vec<String>,
|
||||
#[serde(rename = "fileSize")]
|
||||
pub file_size: u64,
|
||||
}
|
||||
|
||||
// .mrpack is just a zip with modrinth.index.json at the root
|
||||
impl MrpackIndex {
|
||||
fn client_files(&self) -> impl Iterator<Item = &MrpackFile> {
|
||||
self.files.iter().filter(|file| {
|
||||
file.env
|
||||
.get("client")
|
||||
.is_none_or(|support| support != "unsupported")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_mrpack(path: &Path) -> Result<MrpackIndex, String> {
|
||||
tracing::debug!("Parsing .mrpack manifest from {}", path.display());
|
||||
let file = std::fs::File::open(path).map_err(|e| format!("Cannot open .mrpack: {e}"))?;
|
||||
@@ -51,8 +59,15 @@ pub fn parse_mrpack(path: &Path) -> Result<MrpackIndex, String> {
|
||||
let entry = archive
|
||||
.by_name("modrinth.index.json")
|
||||
.map_err(|_| "Missing modrinth.index.json in .mrpack".to_string())?;
|
||||
let raw = super::read_pack_manifest(entry)?;
|
||||
let index: MrpackIndex =
|
||||
serde_json::from_reader(entry).map_err(|e| format!("Invalid manifest JSON: {e}"))?;
|
||||
serde_json::from_slice(&raw).map_err(|e| format!("Invalid manifest JSON: {e}"))?;
|
||||
if index.format_version != 1 || index.game != "minecraft" {
|
||||
return Err(format!(
|
||||
"Unsupported .mrpack format {} for game '{}'",
|
||||
index.format_version, index.game
|
||||
));
|
||||
}
|
||||
tracing::debug!(
|
||||
"Parsed .mrpack '{}' version_id={} files={} deps={}",
|
||||
index.name,
|
||||
@@ -63,8 +78,6 @@ pub fn parse_mrpack(path: &Path) -> Result<MrpackIndex, String> {
|
||||
Ok(index)
|
||||
}
|
||||
|
||||
// mrpack dependencies use keys like "fabric-loader", "forge", etc.
|
||||
// checks in priority order and returns the first match.
|
||||
pub fn loader_from_dependencies(
|
||||
deps: &HashMap<String, String>,
|
||||
) -> (Option<ModLoader>, Option<String>) {
|
||||
@@ -109,7 +122,7 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||
let (loader_opt, loader_version) = loader_from_dependencies(&index.dependencies);
|
||||
let loader = loader_opt.unwrap_or(ModLoader::Vanilla);
|
||||
|
||||
let override_count = count_overrides(path).unwrap_or(0);
|
||||
let override_count = super::override_files(path, &["overrides", "client-overrides"])?.len();
|
||||
tracing::trace!(
|
||||
".mrpack summary: game_version={} loader={:?} loader_version={:?} overrides={}",
|
||||
game_version,
|
||||
@@ -124,7 +137,7 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||
game_version,
|
||||
loader,
|
||||
loader_version,
|
||||
mod_count: index.files.len(),
|
||||
mod_count: index.client_files().count(),
|
||||
override_count,
|
||||
format: PackFormat::Mrpack,
|
||||
archive_path: path.to_path_buf(),
|
||||
@@ -132,73 +145,40 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||
})
|
||||
}
|
||||
|
||||
// peek into the zip to count files under overrides/ and client-overrides/
|
||||
fn count_overrides(mrpack_path: &Path) -> Result<usize, String> {
|
||||
let file = std::fs::File::open(mrpack_path).map_err(|e| e.to_string())?;
|
||||
let archive = zip::ZipArchive::new(file).map_err(|e| e.to_string())?;
|
||||
let count = archive
|
||||
.file_names()
|
||||
.filter(|name| {
|
||||
(name.starts_with("overrides/") || name.starts_with("client-overrides/"))
|
||||
&& !name.ends_with('/')
|
||||
})
|
||||
.count();
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
pub async fn execute_import(
|
||||
summary: &ImportSummary,
|
||||
manager: &InstanceManager,
|
||||
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let name = super::unique_instance_name(&summary.name, &manager.instances_dir);
|
||||
config: &crate::instance::InstanceConfig,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
crate::instance::manager::validate_name(&config.name)?;
|
||||
tracing::info!(
|
||||
"Importing Modrinth pack '{}' as instance '{}'",
|
||||
summary.name,
|
||||
name
|
||||
config.name
|
||||
);
|
||||
|
||||
progress::set_action(format!("Importing '{name}'..."));
|
||||
progress::set_sub_action(format!("{} {}", summary.game_version, summary.loader));
|
||||
|
||||
let config = manager
|
||||
.create(
|
||||
&name,
|
||||
&summary.game_version,
|
||||
summary.loader,
|
||||
summary.loader_version.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?;
|
||||
|
||||
let minecraft_dir = manager
|
||||
.instances_dir
|
||||
.join(&name)
|
||||
.join(&config.name)
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||
|
||||
let result: Result<(), Box<dyn std::error::Error + Send + Sync>> = async {
|
||||
let index = parse_mrpack(&summary.archive_path)
|
||||
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { e.into() })?;
|
||||
download_mod_files(&index, &minecraft_dir).await?;
|
||||
extract_overrides(&summary.archive_path, &minecraft_dir)?;
|
||||
seed_content_manifest(
|
||||
&index,
|
||||
&InstancePaths::new(manager.instances_dir.join(&name)),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
super::cleanup_failed_import(manager, &name);
|
||||
return Err(error);
|
||||
}
|
||||
let index = parse_mrpack(&summary.archive_path)
|
||||
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { e.into() })?;
|
||||
download_mod_files(&index, &minecraft_dir).await?;
|
||||
extract_overrides(&summary.archive_path, &minecraft_dir)?;
|
||||
seed_content_manifest(
|
||||
&index,
|
||||
&InstancePaths::new(manager.instances_dir.join(&config.name)),
|
||||
)?;
|
||||
|
||||
progress::clear();
|
||||
tracing::info!("Imported Modrinth pack '{}' as '{}'", summary.name, name);
|
||||
Ok(config)
|
||||
tracing::info!(
|
||||
"Imported Modrinth pack '{}' as '{}'",
|
||||
summary.name,
|
||||
config.name
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// downloads all mod files listed in the mrpack index, capped at 10 concurrent
|
||||
// downloads to avoid getting rate-limited into oblivion
|
||||
async fn download_mod_files(
|
||||
index: &MrpackIndex,
|
||||
minecraft_dir: &Path,
|
||||
@@ -207,7 +187,7 @@ async fn download_mod_files(
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
let client = crate::net::HttpClient::new();
|
||||
let total = index.files.len();
|
||||
let total = index.client_files().count();
|
||||
let completed = Arc::new(AtomicUsize::new(0));
|
||||
tracing::debug!(
|
||||
"Downloading {} file(s) from .mrpack '{}' into {}",
|
||||
@@ -218,60 +198,14 @@ async fn download_mod_files(
|
||||
|
||||
progress::set_action(format!("Downloading mods... 0/{total}"));
|
||||
|
||||
// bounded concurrency via manual JoinSet draining: seed with max_concurrent
|
||||
// tasks, then spawn a new one each time one finishes
|
||||
let mut tasks = tokio::task::JoinSet::new();
|
||||
let max_concurrent = 10;
|
||||
let mut file_iter = index.files.iter();
|
||||
|
||||
for _ in 0..max_concurrent {
|
||||
if let Some(file) = file_iter.next() {
|
||||
let client = client.clone();
|
||||
let relative = safe_mrpack_path(&file.path)?;
|
||||
let dest = minecraft_dir.join(relative);
|
||||
let url = file.downloads.first().cloned().ok_or_else(|| {
|
||||
crate::net::NetError::Parse(format!(
|
||||
".mrpack file '{}' has no download URL",
|
||||
file.path
|
||||
))
|
||||
})?;
|
||||
let filename = file
|
||||
.path
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or(&file.path)
|
||||
.to_string();
|
||||
let hashes = file.hashes.clone();
|
||||
let file_size = file.file_size;
|
||||
let completed = completed.clone();
|
||||
tasks.spawn(async move {
|
||||
if let Some(parent) = dest.parent()
|
||||
&& let Err(error) = tokio::fs::create_dir_all(parent).await
|
||||
{
|
||||
return Err(crate::net::NetError::from(error));
|
||||
}
|
||||
progress::set_sub_action(filename);
|
||||
tracing::trace!("Downloading .mrpack file to {}", dest.display());
|
||||
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
|
||||
if !verify_mrpack_file(&dest, file_size, &hashes)? {
|
||||
let _ = tokio::fs::remove_file(&dest).await;
|
||||
return Err(crate::net::NetError::Parse(format!(
|
||||
"Downloaded .mrpack file '{}' failed its size or hash verification",
|
||||
dest.display()
|
||||
)));
|
||||
}
|
||||
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
progress::set_action(format!("Downloading mods... {done}/{total}"));
|
||||
Ok::<(), crate::net::NetError>(())
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for file in file_iter {
|
||||
if let Some(result) = tasks.join_next().await {
|
||||
result
|
||||
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?
|
||||
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?;
|
||||
for file in index.client_files() {
|
||||
// Keep at most ten downloads in flight to avoid provider rate limits.
|
||||
if tasks.len() == 10
|
||||
&& let Some(result) = tasks.join_next().await
|
||||
{
|
||||
result??;
|
||||
}
|
||||
let client = client.clone();
|
||||
let relative = safe_mrpack_path(&file.path)?;
|
||||
@@ -311,35 +245,31 @@ async fn download_mod_files(
|
||||
}
|
||||
|
||||
while let Some(result) = tasks.join_next().await {
|
||||
result
|
||||
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?
|
||||
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?;
|
||||
result??;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn safe_mrpack_path(path: &str) -> Result<PathBuf, crate::net::NetError> {
|
||||
let path = Path::new(path);
|
||||
if path.as_os_str().is_empty()
|
||||
|| path
|
||||
.components()
|
||||
.any(|component| !matches!(component, std::path::Component::Normal(_)))
|
||||
{
|
||||
return Err(crate::net::NetError::Parse(format!(
|
||||
"Unsafe .mrpack file path '{}'",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
Ok(path.to_owned())
|
||||
super::portable_pack_path(path)
|
||||
.map(PathBuf::from)
|
||||
.map_err(|error| {
|
||||
crate::net::NetError::Parse(format!("Unsafe .mrpack file path '{path}': {error}"))
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn owned_files(path: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
parse_mrpack(path)?
|
||||
.files
|
||||
.into_iter()
|
||||
let index = parse_mrpack(path)?;
|
||||
let mut files: Vec<_> = index
|
||||
.client_files()
|
||||
.map(|file| safe_mrpack_path(&file.path).map_err(|error| error.to_string()))
|
||||
.collect()
|
||||
.collect::<Result<_, _>>()?;
|
||||
files.extend(super::override_files(
|
||||
path,
|
||||
&["overrides", "client-overrides"],
|
||||
)?);
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn verify_mrpack_file(
|
||||
@@ -365,9 +295,9 @@ fn seed_content_manifest(
|
||||
paths: &InstancePaths,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
let mut manifest = ContentManifest::default();
|
||||
for file in &index.files {
|
||||
let relative_path = Path::new(&file.path);
|
||||
let Some(kind) = mrpack_content_kind(relative_path) else {
|
||||
for file in index.client_files() {
|
||||
let relative_path = safe_mrpack_path(&file.path)?;
|
||||
let Some(kind) = mrpack_content_kind(&relative_path) else {
|
||||
continue;
|
||||
};
|
||||
let Some((project_id, version_id)) = file.downloads.iter().find_map(|url| {
|
||||
@@ -382,7 +312,7 @@ fn seed_content_manifest(
|
||||
let Some(expected_sha512) = file.hashes.get("sha512") else {
|
||||
continue;
|
||||
};
|
||||
let file_fingerprint = fingerprint(&paths.minecraft().join(relative_path))?;
|
||||
let file_fingerprint = fingerprint(&paths.minecraft().join(&relative_path))?;
|
||||
if file_fingerprint
|
||||
.hash("sha512")
|
||||
.is_none_or(|actual| !actual.eq_ignore_ascii_case(expected_sha512))
|
||||
@@ -394,7 +324,7 @@ fn seed_content_manifest(
|
||||
continue;
|
||||
}
|
||||
manifest.upsert(ContentFileRecord {
|
||||
relative_path: relative_path.to_owned(),
|
||||
relative_path,
|
||||
kind,
|
||||
enabled: true,
|
||||
fingerprint: file_fingerprint,
|
||||
@@ -445,71 +375,14 @@ fn extract_overrides(
|
||||
mrpack_path: &Path,
|
||||
minecraft_dir: &Path,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
use std::io::Read;
|
||||
|
||||
progress::set_action("Extracting overrides...".to_string());
|
||||
progress::set_sub_action(String::new());
|
||||
|
||||
let file = std::fs::File::open(mrpack_path)?;
|
||||
let mut archive = zip::ZipArchive::new(file)?;
|
||||
let mut extracted = 0usize;
|
||||
let mut dirs = 0usize;
|
||||
|
||||
for i in 0..archive.len() {
|
||||
let mut entry = archive.by_index(i)?;
|
||||
let entry_name = entry.name().to_string();
|
||||
|
||||
let root = if entry_name.starts_with("overrides/") {
|
||||
"overrides"
|
||||
} else if entry_name.starts_with("client-overrides/") {
|
||||
"client-overrides"
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let enclosed = entry.enclosed_name().ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
format!("Unsafe override path: {entry_name}"),
|
||||
)
|
||||
})?;
|
||||
let relative = enclosed.strip_prefix(root).map_err(|_| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
format!("Invalid override path: {entry_name}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
if relative.as_os_str().is_empty() || entry_name.ends_with('/') {
|
||||
let dir = minecraft_dir.join(relative);
|
||||
std::fs::create_dir_all(dir)?;
|
||||
dirs += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let dest = minecraft_dir.join(relative);
|
||||
if let Some(parent) = dest.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
|
||||
let mut buf = Vec::new();
|
||||
entry.read_to_end(&mut buf)?;
|
||||
tracing::trace!(
|
||||
"Extracting .mrpack override {} to {} ({} bytes)",
|
||||
entry_name,
|
||||
dest.display(),
|
||||
buf.len()
|
||||
);
|
||||
std::fs::write(&dest, &buf)?;
|
||||
extracted += 1;
|
||||
}
|
||||
|
||||
tracing::debug!(
|
||||
"Extracted {} override files and {} directories from {}",
|
||||
extracted,
|
||||
dirs,
|
||||
mrpack_path.display()
|
||||
);
|
||||
Ok(())
|
||||
super::archive::extract_overrides(
|
||||
mrpack_path,
|
||||
minecraft_dir,
|
||||
&["overrides", "client-overrides"],
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+1127
-92
File diff suppressed because it is too large.
Load diff
+457
-56
@@ -1,12 +1,9 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// java runtime discovery shared by launching, loader installation, and settings.
|
||||
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
collections::{BTreeMap, HashSet},
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -17,34 +14,177 @@ pub struct JavaInstallation {
|
||||
pub version: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct JavaRuntime {
|
||||
pub major_version: u32,
|
||||
pub platform: crate::launch_profile::system::JavaPlatform,
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn resolve_java_path(instance_java: Option<&str>) -> String {
|
||||
let settings = crate::config::SETTINGS.read().clone();
|
||||
let environment = merge_environment(&settings.defaults.environment, &BTreeMap::new());
|
||||
resolve_java_path_in(
|
||||
instance_java.or(settings.paths.effective_java_path()),
|
||||
&std::env::current_dir().unwrap_or_default(),
|
||||
&environment,
|
||||
)
|
||||
}
|
||||
|
||||
/// Command uses the platform's environment-key comparison, including Windows Unicode casing.
|
||||
pub fn merge_environment(
|
||||
global: &BTreeMap<String, String>,
|
||||
instance: &BTreeMap<String, String>,
|
||||
) -> BTreeMap<String, String> {
|
||||
let mut command = std::process::Command::new("java");
|
||||
command.envs(global).envs(instance);
|
||||
command
|
||||
.get_envs()
|
||||
.map(|(name, value)| {
|
||||
(
|
||||
name.to_str()
|
||||
.expect("environment names originate from strings")
|
||||
.to_owned(),
|
||||
value
|
||||
.expect("only environment additions were configured")
|
||||
.to_str()
|
||||
.expect("environment values originate from strings")
|
||||
.to_owned(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// These lookups are for the ASCII variable names PATH, JAVA_HOME and JDK_HOME.
|
||||
fn environment_value(
|
||||
environment: &BTreeMap<String, String>,
|
||||
name: &str,
|
||||
) -> Option<std::ffi::OsString> {
|
||||
environment
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|(key, _)| {
|
||||
if cfg!(windows) {
|
||||
key.eq_ignore_ascii_case(name)
|
||||
} else {
|
||||
key.as_str() == name
|
||||
}
|
||||
})
|
||||
.map(|(_, value)| std::ffi::OsString::from(value))
|
||||
.or_else(|| std::env::var_os(name))
|
||||
}
|
||||
|
||||
pub fn resolve_java_path_in(
|
||||
configured: Option<&str>,
|
||||
cwd: &Path,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> String {
|
||||
let search_path = environment_value(environment, "PATH");
|
||||
let find = |name: &str| {
|
||||
if Path::new(name).components().count() > 1 {
|
||||
return which::which_in(name, None::<&std::ffi::OsStr>, cwd).ok();
|
||||
}
|
||||
search_path.as_deref().and_then(|path| {
|
||||
std::env::split_paths(path)
|
||||
.filter(|directory| !cfg!(windows) || !directory.as_os_str().is_empty())
|
||||
.find_map(|directory| {
|
||||
which::which_in(
|
||||
cwd.join(directory).join(name),
|
||||
None::<&std::ffi::OsStr>,
|
||||
cwd,
|
||||
)
|
||||
.ok()
|
||||
})
|
||||
})
|
||||
};
|
||||
if let Some(configured) = configured.filter(|path| !path.is_empty()) {
|
||||
return find(configured)
|
||||
.map(|path| path.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| configured.to_owned());
|
||||
}
|
||||
if let Some(home) = environment_value(environment, "JAVA_HOME") {
|
||||
let bin = cwd
|
||||
.join(home)
|
||||
.join("bin")
|
||||
.join(if cfg!(windows) { "java.exe" } else { "java" });
|
||||
if bin.is_file() {
|
||||
return bin.to_string_lossy().into_owned();
|
||||
}
|
||||
}
|
||||
find("java")
|
||||
.map(|path| path.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| "java".to_owned())
|
||||
}
|
||||
|
||||
/// Probe the selected executable, rather than inferring its architecture from rmcl.
|
||||
pub async fn probe_java(path: &Path) -> std::io::Result<JavaRuntime> {
|
||||
let (cwd, environment) = default_probe_context()?;
|
||||
probe_java_in(path, &cwd, &environment).await
|
||||
}
|
||||
|
||||
pub async fn probe_java_in(
|
||||
path: &Path,
|
||||
cwd: &Path,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> std::io::Result<JavaRuntime> {
|
||||
let output = java_version_output_in(path, cwd, environment).await?;
|
||||
if !output.status.success() {
|
||||
return Err(std::io::Error::other(format!(
|
||||
"Java settings probe exited with {}",
|
||||
output.status
|
||||
)));
|
||||
}
|
||||
parse_runtime_properties(&format!(
|
||||
"{}\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
))
|
||||
}
|
||||
|
||||
fn default_probe_context() -> std::io::Result<(PathBuf, BTreeMap<String, String>)> {
|
||||
Ok((
|
||||
std::env::current_dir()?,
|
||||
merge_environment(
|
||||
&crate::config::SETTINGS.read().defaults.environment,
|
||||
&BTreeMap::new(),
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
fn parse_runtime_properties(output: &str) -> std::io::Result<JavaRuntime> {
|
||||
let property = |name: &str| -> std::io::Result<&str> {
|
||||
output
|
||||
.lines()
|
||||
.filter_map(|line| line.trim().split_once(" = "))
|
||||
.find_map(|(key, value)| (key == name).then_some(value.trim()))
|
||||
.filter(|value| !value.is_empty())
|
||||
.ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
format!("Java probe did not report {name}"),
|
||||
)
|
||||
})
|
||||
};
|
||||
let major_version = parse_java_major_version(property("java.version")?).ok_or_else(|| {
|
||||
std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid Java java.version")
|
||||
})?;
|
||||
Ok(JavaRuntime {
|
||||
major_version,
|
||||
platform: crate::launch_profile::system::JavaPlatform::from_java_properties(
|
||||
property("os.name")?,
|
||||
property("os.arch")?,
|
||||
property("sun.arch.data.model")?,
|
||||
property("os.version")?,
|
||||
)?,
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn detect_java_path() -> String {
|
||||
if let Ok(java_home) = std::env::var("JAVA_HOME") {
|
||||
let java_name = if cfg!(windows) { "java.exe" } else { "java" };
|
||||
let bin = std::path::Path::new(&java_home).join("bin").join(java_name);
|
||||
if bin.exists() {
|
||||
tracing::trace!("Detected Java from JAVA_HOME: {}", bin.display());
|
||||
return bin.to_string_lossy().to_string();
|
||||
}
|
||||
tracing::warn!(
|
||||
"JAVA_HOME is set to {}, but {} does not exist",
|
||||
java_home,
|
||||
bin.display()
|
||||
);
|
||||
}
|
||||
match which::which("java") {
|
||||
Ok(path) => {
|
||||
tracing::trace!("Detected Java from PATH: {}", path.display());
|
||||
path.to_string_lossy().to_string()
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"Could not find java on PATH, falling back to literal 'java': {}",
|
||||
e
|
||||
);
|
||||
"java".to_string()
|
||||
}
|
||||
}
|
||||
let Ok((cwd, environment)) = default_probe_context() else {
|
||||
return "java".to_owned();
|
||||
};
|
||||
resolve_java_path_in(None, &cwd, &environment)
|
||||
}
|
||||
|
||||
/// Finds Java executables in the environment and the conventional installation
|
||||
@@ -52,23 +192,39 @@ pub fn detect_java_path() -> String {
|
||||
/// opening the selector never walks an entire drive.
|
||||
#[must_use]
|
||||
pub fn discover_installations() -> Vec<JavaInstallation> {
|
||||
let Ok((cwd, environment)) = default_probe_context() else {
|
||||
return Vec::new();
|
||||
};
|
||||
discover_installations_in(&cwd, &environment)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn discover_installations_in(
|
||||
cwd: &Path,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> Vec<JavaInstallation> {
|
||||
let mut candidates = Vec::new();
|
||||
for variable in ["JAVA_HOME", "JDK_HOME"] {
|
||||
if let Ok(java_home) = std::env::var(variable) {
|
||||
add_java_home(Path::new(&java_home), &mut candidates);
|
||||
if let Some(java_home) = environment_value(environment, variable) {
|
||||
add_java_home(&cwd.join(java_home), &mut candidates);
|
||||
}
|
||||
}
|
||||
if let Ok(path) = which::which("java") {
|
||||
let search_path = environment_value(environment, "PATH");
|
||||
if let Ok(path) = which::which_in(
|
||||
resolve_java_path_in(None, cwd, environment),
|
||||
None::<&std::ffi::OsStr>,
|
||||
cwd,
|
||||
) {
|
||||
candidates.push(path);
|
||||
}
|
||||
if let Some(path) = std::env::var_os("PATH") {
|
||||
if let Some(path) = search_path {
|
||||
for directory in std::env::split_paths(&path) {
|
||||
let executable = if cfg!(target_os = "windows") {
|
||||
"java.exe"
|
||||
} else {
|
||||
"java"
|
||||
};
|
||||
candidates.push(directory.join(executable));
|
||||
candidates.push(cwd.join(directory).join(executable));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,7 +239,7 @@ pub fn discover_installations() -> Vec<JavaInstallation> {
|
||||
.filter_map(|path| {
|
||||
let identity = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
|
||||
seen.insert(identity)
|
||||
.then(|| inspect_installation(&path))
|
||||
.then(|| inspect_installation_in(&path, cwd, environment))
|
||||
.flatten()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -98,25 +254,96 @@ pub fn discover_installations() -> Vec<JavaInstallation> {
|
||||
/// Reads the version reported by one Java executable.
|
||||
#[must_use]
|
||||
pub fn inspect_installation(path: &Path) -> Option<JavaInstallation> {
|
||||
let (cwd, environment) = default_probe_context().ok()?;
|
||||
inspect_installation_in(path, &cwd, &environment)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn inspect_installation_in(
|
||||
path: &Path,
|
||||
cwd: &Path,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> Option<JavaInstallation> {
|
||||
let resolved = path
|
||||
.to_str()
|
||||
.map(|path| resolve_java_path_in(Some(path), cwd, environment));
|
||||
let path = resolved.as_deref().map_or(path, Path::new);
|
||||
path.is_file().then(|| JavaInstallation {
|
||||
version: java_version(path),
|
||||
version: java_version_in(path, cwd, environment),
|
||||
path: path.to_path_buf(),
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn load_installation_cache(path: &Path) -> Option<Vec<JavaInstallation>> {
|
||||
let mut installations =
|
||||
serde_json::from_slice::<Vec<JavaInstallation>>(&std::fs::read(path).ok()?).ok()?;
|
||||
installations.retain(|installation| installation.path.is_file());
|
||||
(!installations.is_empty()).then_some(installations)
|
||||
let (cwd, environment) = default_probe_context().ok()?;
|
||||
load_installation_cache_in(path, &cwd, &environment)
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct InstallationCache {
|
||||
context: String,
|
||||
installations: Vec<JavaInstallation>,
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn probe_context_key(cwd: &Path, environment: &BTreeMap<String, String>) -> String {
|
||||
use sha2::Digest;
|
||||
let mut hash = sha2::Sha256::new();
|
||||
let mut add = |bytes: &[u8]| {
|
||||
hash.update((bytes.len() as u64).to_le_bytes());
|
||||
hash.update(bytes);
|
||||
};
|
||||
add(cwd.as_os_str().as_encoded_bytes());
|
||||
let mut ambient: Vec<_> = std::env::vars_os().collect();
|
||||
ambient.sort();
|
||||
for (key, value) in &ambient {
|
||||
add(key.as_encoded_bytes());
|
||||
add(value.as_encoded_bytes());
|
||||
}
|
||||
// Store a digest only; configured environment values may contain credentials.
|
||||
for (key, value) in merge_environment(environment, &BTreeMap::new()) {
|
||||
add(key.as_bytes());
|
||||
add(value.as_bytes());
|
||||
}
|
||||
format!("{:x}", hash.finalize())
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn load_installation_cache_in(
|
||||
path: &Path,
|
||||
cwd: &Path,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> Option<Vec<JavaInstallation>> {
|
||||
let mut cache: InstallationCache = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
|
||||
if cache.context != probe_context_key(cwd, environment) {
|
||||
return None;
|
||||
}
|
||||
cache
|
||||
.installations
|
||||
.retain(|installation| installation.path.is_file());
|
||||
(!cache.installations.is_empty()).then_some(cache.installations)
|
||||
}
|
||||
|
||||
pub fn save_installation_cache(
|
||||
path: &Path,
|
||||
installations: &[JavaInstallation],
|
||||
) -> std::io::Result<()> {
|
||||
let bytes = serde_json::to_vec_pretty(installations).map_err(std::io::Error::other)?;
|
||||
let (cwd, environment) = default_probe_context()?;
|
||||
save_installation_cache_in(path, installations, &cwd, &environment)
|
||||
}
|
||||
|
||||
pub fn save_installation_cache_in(
|
||||
path: &Path,
|
||||
installations: &[JavaInstallation],
|
||||
cwd: &Path,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> std::io::Result<()> {
|
||||
let cache = InstallationCache {
|
||||
context: probe_context_key(cwd, environment),
|
||||
installations: installations.to_vec(),
|
||||
};
|
||||
let bytes = serde_json::to_vec_pretty(&cache).map_err(std::io::Error::other)?;
|
||||
crate::storage::write_atomic(path, &bytes)
|
||||
}
|
||||
|
||||
@@ -151,7 +378,7 @@ fn java_roots() -> Vec<PathBuf> {
|
||||
roots.push(PathBuf::from(prefix).join(formula));
|
||||
}
|
||||
}
|
||||
if let Some(home) = dirs_next::home_dir() {
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
roots.push(home.join("Library/Java/JavaVirtualMachines"));
|
||||
roots.push(home.join(".sdkman/candidates/java"));
|
||||
roots.push(home.join(".asdf/installs/java"));
|
||||
@@ -164,7 +391,7 @@ fn java_roots() -> Vec<PathBuf> {
|
||||
PathBuf::from("/opt/java"),
|
||||
PathBuf::from("/opt/jdk"),
|
||||
]);
|
||||
if let Some(home) = dirs_next::home_dir() {
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
roots.push(home.join(".sdkman/candidates/java"));
|
||||
roots.push(home.join(".jdks"));
|
||||
roots.push(home.join(".asdf/installs/java"));
|
||||
@@ -205,8 +432,18 @@ fn add_java_home(home: &Path, candidates: &mut Vec<PathBuf>) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn java_version(path: &Path) -> Option<String> {
|
||||
let output = Command::new(path).arg("-version").output().ok()?;
|
||||
pub fn java_version_in(
|
||||
path: &Path,
|
||||
cwd: &Path,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> Option<String> {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.ok()?;
|
||||
let output = runtime
|
||||
.block_on(java_version_output_in(path, cwd, environment))
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
@@ -218,8 +455,36 @@ pub(crate) fn java_version(path: &Path) -> Option<String> {
|
||||
parse_java_version(&text)
|
||||
}
|
||||
|
||||
async fn java_version_output_in(
|
||||
path: &Path,
|
||||
cwd: &Path,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> std::io::Result<std::process::Output> {
|
||||
let java = path
|
||||
.to_str()
|
||||
.map(|path| resolve_java_path_in(Some(path), cwd, environment));
|
||||
let mut command = tokio::process::Command::new(java.as_deref().map_or(path, Path::new));
|
||||
command
|
||||
.args(["-XshowSettings:properties", "-version"])
|
||||
.current_dir(cwd)
|
||||
.envs(environment)
|
||||
.kill_on_drop(true);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), command.output())
|
||||
.await
|
||||
.map_err(|_| {
|
||||
std::io::Error::new(std::io::ErrorKind::TimedOut, "Java version check timed out")
|
||||
})?
|
||||
}
|
||||
|
||||
fn parse_java_version(output: &str) -> Option<String> {
|
||||
output.lines().find_map(|line| {
|
||||
let line = line.trim();
|
||||
if let Some(version) = line.strip_prefix("java.version = ") {
|
||||
return Some(version.trim().to_owned());
|
||||
}
|
||||
if !line.starts_with("java version ") && !line.starts_with("openjdk version ") {
|
||||
return None;
|
||||
}
|
||||
line.split_once('"')
|
||||
.and_then(|(_, rest)| rest.split_once('"'))
|
||||
.map(|(version, _)| version.to_owned())
|
||||
@@ -248,16 +513,7 @@ pub(crate) fn parse_java_major_version(output: &str) -> Option<u32> {
|
||||
}
|
||||
|
||||
let start = output.find(|character: char| character.is_ascii_digit())?;
|
||||
let parts = output[start..]
|
||||
.split(|character: char| !character.is_ascii_digit())
|
||||
.filter(|part| !part.is_empty())
|
||||
.filter_map(|part| part.parse::<u32>().ok())
|
||||
.collect::<Vec<_>>();
|
||||
match parts.as_slice() {
|
||||
[1, legacy_major, ..] => Some(*legacy_major),
|
||||
[major, ..] => Some(*major),
|
||||
[] => None,
|
||||
}
|
||||
Some(java_major(Some(&output[start..]))).filter(|major| *major > 0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -301,4 +557,149 @@ mod tests {
|
||||
std::fs::remove_file(executable).unwrap();
|
||||
assert_eq!(load_installation_cache(&cache), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_properties_report_selected_java_architecture_and_os_version() {
|
||||
for (os, arch, bits, name, normalized) in [
|
||||
("Windows 10", "x86", "32", "windows", "x86"),
|
||||
("Windows 11", "amd64", "64", "windows", "x86_64"),
|
||||
("Mac OS X", "x86_64", "64", "osx", "x86_64"),
|
||||
("Mac OS X", "aarch64", "64", "osx", "arm64"),
|
||||
("Linux", "amd64", "64", "linux", "x86_64"),
|
||||
] {
|
||||
let properties = format!(
|
||||
"Property settings:\r\n java.version = 1.8.0_412\r\n os.name = {os}\r\n os.arch = {arch}\r\n sun.arch.data.model = {bits}\r\n os.version = 10.0\r\n"
|
||||
);
|
||||
let runtime = parse_runtime_properties(&properties).unwrap();
|
||||
assert_eq!(runtime.major_version, 8);
|
||||
assert_eq!(runtime.platform.os_name, name);
|
||||
assert_eq!(runtime.platform.arch, normalized);
|
||||
assert_eq!(runtime.platform.bitness.to_string(), bits);
|
||||
assert_eq!(runtime.platform.os_version, "10.0");
|
||||
assert!(
|
||||
parse_runtime_properties(&properties.replace("sun.arch.data.model =", "unknown ="))
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("sun.arch.data.model")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incomplete_runtime_properties_do_not_fall_back_to_the_launcher_architecture() {
|
||||
assert!(parse_runtime_properties("openjdk version \"25.0.1\"").is_err());
|
||||
assert!(
|
||||
crate::launch_profile::system::JavaPlatform::from_java_properties(
|
||||
"Windows 10",
|
||||
"../x86",
|
||||
"32",
|
||||
"10.0"
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
crate::launch_profile::system::JavaPlatform::from_java_properties(
|
||||
"Mac OS X", "aarch64", "unknown", "15.0"
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn relative_java_search_paths_are_bound_to_the_execution_directory() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let temp =
|
||||
tempfile::tempdir_in(Path::new(env!("CARGO_MANIFEST_DIR")).join("target")).unwrap();
|
||||
let cwd = temp.path().join("minecraft");
|
||||
let java = cwd.join("bin/java");
|
||||
std::fs::create_dir_all(java.parent().unwrap()).unwrap();
|
||||
std::fs::write(&java, "#!/bin/sh\nexit 0\n").unwrap();
|
||||
std::fs::set_permissions(&java, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let environment = BTreeMap::from([
|
||||
("PATH".to_owned(), "bin".to_owned()),
|
||||
("JAVA_HOME".to_owned(), "missing-home".to_owned()),
|
||||
]);
|
||||
for configured in [None, Some("java"), Some("bin/java")] {
|
||||
assert_eq!(
|
||||
Path::new(&resolve_java_path_in(configured, &cwd, &environment)),
|
||||
java
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn installed_jdk_reports_runtime_properties_on_the_native_platform() {
|
||||
let cwd = std::env::current_dir().unwrap();
|
||||
let environment = BTreeMap::new();
|
||||
let java = resolve_java_path_in(None, &cwd, &environment);
|
||||
let runtime = probe_java_in(Path::new(&java), &cwd, &environment)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(runtime.major_version >= 8);
|
||||
assert_eq!(
|
||||
runtime.platform.os_name,
|
||||
crate::launch_profile::system::mojang_os_name()
|
||||
);
|
||||
assert!(matches!(runtime.platform.bitness, 32 | 64));
|
||||
assert!(!runtime.platform.os_version.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn environment_overrides_follow_native_case_rules_and_are_deterministic() {
|
||||
let global = BTreeMap::from([
|
||||
("PATH".into(), "global".into()),
|
||||
("TÊST".into(), "global".into()),
|
||||
]);
|
||||
let instance = BTreeMap::from([
|
||||
("PATH".into(), "first".into()),
|
||||
("path".into(), "last".into()),
|
||||
("têst".into(), "instance".into()),
|
||||
]);
|
||||
let merged = merge_environment(&global, &instance);
|
||||
assert_eq!(
|
||||
environment_value(&instance, "PATH").unwrap(),
|
||||
std::ffi::OsString::from(if cfg!(windows) { "last" } else { "first" })
|
||||
);
|
||||
if cfg!(windows) {
|
||||
assert_eq!(merged.len(), 2);
|
||||
assert_eq!(merged["PATH"], "last");
|
||||
assert_eq!(merged["TÊST"], "instance");
|
||||
} else {
|
||||
assert_eq!(merged.len(), 4);
|
||||
assert_eq!(merged["PATH"], "first");
|
||||
assert_eq!(merged["path"], "last");
|
||||
assert_eq!(merged["TÊST"], "global");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installation_cache_is_bound_to_the_probe_context_without_storing_environment_values() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let executable = temp.path().join("java");
|
||||
std::fs::write(&executable, b"java").unwrap();
|
||||
let cache = temp.path().join("installations.json");
|
||||
let installations = vec![JavaInstallation {
|
||||
path: executable,
|
||||
version: Some("25.0.1".into()),
|
||||
}];
|
||||
let environment =
|
||||
BTreeMap::from([("PRIVATE_TEST_VALUE".into(), "sensitive-cache-value".into())]);
|
||||
save_installation_cache_in(&cache, &installations, temp.path(), &environment).unwrap();
|
||||
assert_eq!(
|
||||
load_installation_cache_in(&cache, temp.path(), &environment),
|
||||
Some(installations)
|
||||
);
|
||||
assert!(
|
||||
!std::fs::read_to_string(&cache)
|
||||
.unwrap()
|
||||
.contains("sensitive-cache-value")
|
||||
);
|
||||
let changed = BTreeMap::from([("PRIVATE_TEST_VALUE".into(), "another-value".into())]);
|
||||
assert!(load_installation_cache_in(&cache, temp.path(), &changed).is_none());
|
||||
assert!(
|
||||
load_installation_cache_in(&cache, &temp.path().join("other-cwd"), &environment)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
+315
-301
@@ -1,10 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// builds the full java command line and spawns minecraft as a child process.
|
||||
// handles classpath assembly, auth token injection, and log capture.
|
||||
// loader-specific patches live in submodules (e.g. patches.rs for lwjgl3ify).
|
||||
|
||||
mod output;
|
||||
pub(crate) mod parser;
|
||||
mod patches;
|
||||
|
||||
@@ -12,12 +9,14 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
use super::process;
|
||||
use crate::auth::AccountType;
|
||||
use crate::instance::java::JavaRuntime;
|
||||
use crate::instance::models::{InstanceConfig, LaunchCommand, ModLoader, WindowMode};
|
||||
use crate::launch_profile::model::{Argument, LaunchProfile};
|
||||
use crate::launch_profile::rules::{self, FeatureSet, RuleAction, RuleContext};
|
||||
use crate::launch_profile::templates::TemplateContext;
|
||||
use crate::launch_profile::{render, resolve, system};
|
||||
use crate::launch_profile::{render, resolve};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum LaunchError {
|
||||
@@ -37,18 +36,44 @@ pub enum LaunchError {
|
||||
required: u32,
|
||||
detected: u32,
|
||||
},
|
||||
#[error("This instance requires Java {required}, but rmcl could not check {java}: {reason}")]
|
||||
#[error("Could not inspect Java runtime {java}: {reason}")]
|
||||
JavaCheckFailed {
|
||||
java: String,
|
||||
required: u32,
|
||||
reason: String,
|
||||
},
|
||||
#[error("Download error: {0}")]
|
||||
Download(#[from] crate::net::NetError),
|
||||
#[error("{0}")]
|
||||
Auth(String),
|
||||
#[error("{phase} command failed: {reason}")]
|
||||
Command { phase: &'static str, reason: String },
|
||||
#[error("Config sync error: {0}")]
|
||||
ConfigSync(#[from] crate::instance::config_sync::ConfigSyncError),
|
||||
#[error("Launch cancelled")]
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
struct LaunchCleanup(String);
|
||||
|
||||
impl Drop for LaunchCleanup {
|
||||
fn drop(&mut self) {
|
||||
crate::instance::runtime::cleanup_kill_sender(&self.0);
|
||||
if crate::instance::runtime::is_active(&self.0) {
|
||||
crate::instance::runtime::remove(&self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_kill(receiver: &mut Option<tokio::sync::oneshot::Receiver<()>>) {
|
||||
if let Some(pending) = receiver {
|
||||
let result = pending.await;
|
||||
*receiver = None;
|
||||
if result.is_ok() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
|
||||
fn build_game_args(
|
||||
@@ -81,49 +106,16 @@ fn apply_window_mode(game_args: &mut Vec<String>, window_mode: WindowMode) {
|
||||
}
|
||||
}
|
||||
|
||||
async fn check_java_version(java: &str, required: Option<u32>) -> Result<(), LaunchError> {
|
||||
fn check_java_version(
|
||||
java: &str,
|
||||
runtime: &JavaRuntime,
|
||||
required: Option<u32>,
|
||||
) -> Result<(), LaunchError> {
|
||||
let Some(required) = required.filter(|major| *major > 0) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let mut command = tokio::process::Command::new(java);
|
||||
command.arg("-version").kill_on_drop(true);
|
||||
let output = tokio::time::timeout(std::time::Duration::from_secs(10), command.output())
|
||||
.await
|
||||
.map_err(|_| LaunchError::JavaCheckFailed {
|
||||
java: java.to_owned(),
|
||||
required,
|
||||
reason: "version check timed out".to_owned(),
|
||||
})?
|
||||
.map_err(|e| LaunchError::JavaCheckFailed {
|
||||
java: java.to_owned(),
|
||||
required,
|
||||
reason: e.to_string(),
|
||||
})?;
|
||||
|
||||
if !output.status.success() {
|
||||
return Err(LaunchError::JavaCheckFailed {
|
||||
java: java.to_owned(),
|
||||
required,
|
||||
reason: format!("`java -version` exited with {}", output.status),
|
||||
});
|
||||
}
|
||||
|
||||
let version_text = format!(
|
||||
"{}{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
|
||||
let detected =
|
||||
crate::instance::java::parse_java_major_version(&version_text).ok_or_else(|| {
|
||||
LaunchError::JavaCheckFailed {
|
||||
java: java.to_owned(),
|
||||
required,
|
||||
reason: format!("could not parse `java -version` output: {version_text:?}"),
|
||||
}
|
||||
})?;
|
||||
|
||||
let detected = runtime.major_version;
|
||||
if detected < required {
|
||||
return Err(LaunchError::JavaTooOld {
|
||||
java: java.to_owned(),
|
||||
@@ -135,11 +127,7 @@ async fn check_java_version(java: &str, required: Option<u32>) -> Result<(), Lau
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// existing installs from rmcl <= 0.3.0 have meta.json files in the
|
||||
// stripped legacy format (no `arguments`, no `minecraftArguments`). every
|
||||
// real upstream profile has at least one of those fields. on detecting the
|
||||
// stripped format, re-fetch the version metadata from mojang's manifest
|
||||
// and overwrite the file with the raw upstream bytes.
|
||||
// rmcl <= 0.3.0 stripped upstream arguments from cached metadata.
|
||||
async fn migrate_legacy_meta_if_needed(
|
||||
meta_path: &Path,
|
||||
profile: &LaunchProfile,
|
||||
@@ -197,9 +185,6 @@ async fn migrate_legacy_meta_if_needed(
|
||||
Ok(Some(refreshed))
|
||||
}
|
||||
|
||||
// the forge/neoforge installer writes its version JSON to a path that's
|
||||
// loader-specific. encode the naming convention here so migration code
|
||||
// can find the original file when it needs to rebuild our cache.
|
||||
fn installer_version_dir_name(
|
||||
loader: ModLoader,
|
||||
game_version: &str,
|
||||
@@ -212,35 +197,19 @@ fn installer_version_dir_name(
|
||||
}
|
||||
}
|
||||
|
||||
// loader profiles installed by rmcl <= 0.3.0 are in our stripped
|
||||
// `{mainClass, libraries[, gameArguments]}` format, which silently drops
|
||||
// `inheritsFrom`, `arguments.jvm`, and conditional rules from upstream.
|
||||
// detect that shape (no inheritsFrom AND no arguments AND no
|
||||
// minecraftArguments - every real upstream profile has at least one) and
|
||||
// rebuild from the installer's original JSON if it's still on disk.
|
||||
// Recover JVM arguments and rules stripped by rmcl <= 0.3.0 from the installer original.
|
||||
async fn migrate_legacy_loader_profile_if_needed(
|
||||
profile_path: &Path,
|
||||
profile: &LaunchProfile,
|
||||
config: &InstanceConfig,
|
||||
instance_dir: &Path,
|
||||
) -> Result<Option<LaunchProfile>, LaunchError> {
|
||||
// Fabric and Quilt fetch their profiles from a network endpoint at
|
||||
// install time; there's no installer-written JSON on disk to recover
|
||||
// from. their upstream profiles also happen to match the "legacy
|
||||
// stripped" predicate (no inheritsFrom, no arguments), so without this
|
||||
// early return every Fabric/Quilt launch would incorrectly fail
|
||||
// migration. resolve() handles their lack of inheritsFrom via the
|
||||
// implicit fallback in the launch flow.
|
||||
// Fabric/Quilt profiles can omit these fields and have no installer original.
|
||||
if matches!(config.loader, ModLoader::Fabric | ModLoader::Quilt) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// tightened predicate per the spec: only treat a profile as "legacy
|
||||
// stripped" when our old `gameArguments` field is present. that field
|
||||
// is unique to rmcl <= 0.3.0's custom shape; no upstream profile
|
||||
// emits it. without this gate, an upstream profile that happens to
|
||||
// omit inheritsFrom/arguments/minecraftArguments would be mistakenly
|
||||
// re-extracted from the installer JSON.
|
||||
// gameArguments identifies rmcl's old shape, avoiding false positives on upstream profiles.
|
||||
let is_legacy = profile.inherits_from.is_none()
|
||||
&& profile.arguments.is_none()
|
||||
&& profile.minecraft_arguments.is_none()
|
||||
@@ -260,9 +229,6 @@ async fn migrate_legacy_loader_profile_if_needed(
|
||||
let Some(version_dir) =
|
||||
installer_version_dir_name(config.loader, &config.game_version, loader_version)
|
||||
else {
|
||||
// unreachable today: only Vanilla/Fabric/Quilt return None, and
|
||||
// Vanilla doesn't pass this code path (no loader profile to
|
||||
// migrate) while Fabric/Quilt are filtered above.
|
||||
return Err(LaunchError::Parse(format!(
|
||||
"Loader profile at {} is in an outdated format. Reinstall {} for this instance.",
|
||||
profile_path.display(),
|
||||
@@ -300,9 +266,6 @@ async fn migrate_legacy_loader_profile_if_needed(
|
||||
Ok(Some(refreshed))
|
||||
}
|
||||
|
||||
// resolved auth credentials passed into the launch-invocation builder.
|
||||
// keeping these as borrowed strs lets callers pass owned strings or string
|
||||
// slices without forcing allocation.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LaunchAuth<'a> {
|
||||
pub username: &'a str,
|
||||
@@ -312,9 +275,7 @@ pub struct LaunchAuth<'a> {
|
||||
pub user_type: &'a str,
|
||||
}
|
||||
|
||||
// everything the spawner needs to construct the java command. assembled by
|
||||
// build_launch_invocation, consumed by launch(). exposed so integration tests
|
||||
// can assert on the rendered invocation without spawning a real process.
|
||||
// Exposed so integration tests can inspect the invocation without spawning Java.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LaunchInvocation {
|
||||
pub java: String,
|
||||
@@ -368,11 +329,6 @@ fn validate_quick_play_world(minecraft_dir: &Path, world: &str) -> Result<(), La
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// builds a fully-resolved java invocation for the given instance. reads
|
||||
// meta.json and the loader profile from disk, migrates legacy formats if
|
||||
// needed (may hit Mojang to refetch), resolves inheritsFrom, applies
|
||||
// loader-specific patches, and renders all template arguments. all I/O
|
||||
// except auth resolution and process spawning happens here.
|
||||
pub async fn build_launch_invocation(
|
||||
config: &InstanceConfig,
|
||||
instances_dir: &Path,
|
||||
@@ -380,10 +336,32 @@ pub async fn build_launch_invocation(
|
||||
auth: &LaunchAuth<'_>,
|
||||
quick_play_world: Option<&str>,
|
||||
) -> Result<LaunchInvocation, LaunchError> {
|
||||
let instance_dir = instances_dir.join(&config.name);
|
||||
let settings = crate::config::SETTINGS.read().clone();
|
||||
build_launch_invocation_with_settings(
|
||||
config,
|
||||
instances_dir,
|
||||
meta_dir,
|
||||
auth,
|
||||
quick_play_world,
|
||||
&settings,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn build_launch_invocation_with_settings(
|
||||
config: &InstanceConfig,
|
||||
instances_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
auth: &LaunchAuth<'_>,
|
||||
quick_play_world: Option<&str>,
|
||||
settings: &crate::config::Config,
|
||||
) -> Result<LaunchInvocation, LaunchError> {
|
||||
let meta_dir = std::path::absolute(meta_dir)?;
|
||||
let meta_dir = meta_dir.as_path();
|
||||
let instance_dir = std::path::absolute(instances_dir.join(&config.name))?;
|
||||
let minecraft_dir = instance_dir.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||
let (window_mode, resolution) = {
|
||||
let defaults = &crate::config::SETTINGS.read().defaults;
|
||||
let defaults = &settings.defaults;
|
||||
(
|
||||
config.effective_window_mode(defaults.window_mode),
|
||||
config.effective_resolution(defaults.resolution),
|
||||
@@ -413,20 +391,6 @@ pub async fn build_launch_invocation(
|
||||
has_custom_resolution: resolution.map(|_| true),
|
||||
..Default::default()
|
||||
};
|
||||
let host_os_version = system::mojang_os_version();
|
||||
let rule_ctx = RuleContext {
|
||||
os_name: system::mojang_os_name(),
|
||||
os_version: &host_os_version,
|
||||
arch: system::mojang_arch_name(),
|
||||
features: ¤t_features,
|
||||
};
|
||||
|
||||
let asset_index_id = meta
|
||||
.asset_index
|
||||
.as_ref()
|
||||
.map(|ai| ai.id.clone())
|
||||
.unwrap_or_default();
|
||||
|
||||
let lib_dir = metadata_paths.libraries();
|
||||
|
||||
let lv = config.loader_version.as_deref().unwrap_or("unknown");
|
||||
@@ -437,7 +401,7 @@ pub async fn build_launch_invocation(
|
||||
// if needed, and resolve `inheritsFrom` against the vanilla parent (which
|
||||
// the vanilla meta migration above ensured is fresh on disk). when no
|
||||
// loader is configured we use the already-loaded vanilla meta directly.
|
||||
let merged_profile: LaunchProfile = if let Some(filename) = &profile_filename {
|
||||
let mut merged_profile: LaunchProfile = if let Some(filename) = &profile_filename {
|
||||
let profile_path = metadata_paths.loader_profiles().join(filename);
|
||||
if !profile_path.exists() {
|
||||
return Err(LaunchError::MetaNotFound(
|
||||
@@ -472,7 +436,7 @@ pub async fn build_launch_invocation(
|
||||
meta.clone()
|
||||
};
|
||||
|
||||
let main_class = merged_profile
|
||||
let mut main_class = merged_profile
|
||||
.main_class
|
||||
.clone()
|
||||
.ok_or_else(|| LaunchError::Parse("merged profile missing mainClass".into()))?;
|
||||
@@ -481,12 +445,71 @@ pub async fn build_launch_invocation(
|
||||
return Err(LaunchError::NotSupported("Quick Play".to_owned()));
|
||||
}
|
||||
|
||||
// rebuild the classpath from the merged profile. vanilla-style libraries
|
||||
// have `downloads.artifact.path` set and live in meta_dir/libraries/.
|
||||
// loader-style libraries only have a maven coordinate; for forge/neoforge,
|
||||
// the installer drops some of them into <instance>/.minecraft/libraries/
|
||||
// so we check there first.
|
||||
let has_local_libs = matches!(config.loader, ModLoader::Forge | ModLoader::NeoForge);
|
||||
let environment = crate::instance::java::merge_environment(
|
||||
&settings.defaults.environment,
|
||||
&config.environment,
|
||||
);
|
||||
let java = crate::instance::java::resolve_java_path_in(
|
||||
config
|
||||
.java_path
|
||||
.as_deref()
|
||||
.or(settings.paths.effective_java_path()),
|
||||
&minecraft_dir,
|
||||
&environment,
|
||||
);
|
||||
let runtime =
|
||||
crate::instance::java::probe_java_in(Path::new(&java), &minecraft_dir, &environment)
|
||||
.await
|
||||
.map_err(|error| LaunchError::JavaCheckFailed {
|
||||
java: java.clone(),
|
||||
required: merged_profile
|
||||
.java_version
|
||||
.as_ref()
|
||||
.map_or(0, |version| version.major_version),
|
||||
reason: error.to_string(),
|
||||
})?;
|
||||
let platform = &runtime.platform;
|
||||
let patches = if config.loader == ModLoader::Forge {
|
||||
patches::load(&minecraft_dir, platform)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(patches) = &patches {
|
||||
merged_profile = resolve::merge_into(patches.profile.clone(), merged_profile);
|
||||
// The embedded version.json is a complete client profile. Appending
|
||||
// the old Forge arguments would run its tweakers a second time.
|
||||
merged_profile.arguments = patches.profile.arguments.clone();
|
||||
merged_profile.inherits_from = None;
|
||||
patches::strip_replaced_libs(&mut merged_profile);
|
||||
main_class = merged_profile
|
||||
.main_class
|
||||
.clone()
|
||||
.expect("validated patch main class");
|
||||
}
|
||||
check_java_version(
|
||||
&java,
|
||||
&runtime,
|
||||
merged_profile
|
||||
.java_version
|
||||
.as_ref()
|
||||
.map(|version| version.major_version),
|
||||
)?;
|
||||
let rule_ctx = RuleContext {
|
||||
os_name: platform.os_name,
|
||||
os_version: &platform.os_version,
|
||||
arch: &platform.arch,
|
||||
features: ¤t_features,
|
||||
};
|
||||
let asset_index_id = merged_profile
|
||||
.asset_index
|
||||
.as_ref()
|
||||
.map(|index| index.id.clone())
|
||||
.unwrap_or_default();
|
||||
let natives_dir = platform.natives_directory(meta_dir, &config.game_version);
|
||||
|
||||
// Forge installers can place libraries in the instance instead of the shared cache.
|
||||
let has_local_libs =
|
||||
matches!(config.loader, ModLoader::Forge | ModLoader::NeoForge) && patches.is_none();
|
||||
let local_lib_dir = minecraft_dir.join("libraries");
|
||||
let library_directory = if has_local_libs {
|
||||
&local_lib_dir
|
||||
@@ -494,6 +517,35 @@ pub async fn build_launch_invocation(
|
||||
&lib_dir
|
||||
};
|
||||
|
||||
let mut to_download = Vec::new();
|
||||
for library in &merged_profile.libraries {
|
||||
if library
|
||||
.rules
|
||||
.as_ref()
|
||||
.is_some_and(|conditions| !rules::evaluate(conditions, &rule_ctx))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// Installer-owned artifacts are already in the instance's library directory.
|
||||
let local = has_local_libs
|
||||
&& crate::net::mojang::library_artifact_path(library)?
|
||||
.is_some_and(|path| local_lib_dir.join(path).is_file());
|
||||
let mut library = library.clone();
|
||||
if local && let Some(downloads) = &mut library.downloads {
|
||||
downloads.artifact = None;
|
||||
}
|
||||
to_download.push(library);
|
||||
}
|
||||
crate::net::mojang::download_profile_libraries(
|
||||
&crate::net::HttpClient::new(),
|
||||
&to_download,
|
||||
&lib_dir,
|
||||
&natives_dir,
|
||||
platform,
|
||||
¤t_features,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let mut classpath: Vec<PathBuf> = Vec::new();
|
||||
for lib in &merged_profile.libraries {
|
||||
if let Some(rules) = &lib.rules
|
||||
@@ -502,25 +554,10 @@ pub async fn build_launch_invocation(
|
||||
continue;
|
||||
}
|
||||
|
||||
// resolve a relative path for this library. prefer downloads.artifact.path
|
||||
// when present (vanilla-style), fall back to maven_coord_to_path(name)
|
||||
// for loader-style entries that only have a coord.
|
||||
let rel: PathBuf = match lib
|
||||
.downloads
|
||||
.as_ref()
|
||||
.and_then(|d| d.artifact.as_ref())
|
||||
.map(|a| PathBuf::from(&a.path))
|
||||
.or_else(|| {
|
||||
crate::instance::loader::maven::maven_coord_to_path(&lib.name).map(PathBuf::from)
|
||||
}) {
|
||||
Some(p) => p,
|
||||
None => continue,
|
||||
let Some(rel) = crate::net::mojang::library_artifact_path(lib)? else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// for forge/neoforge, the installer drops some libs (notably the
|
||||
// bootstrap library) into <instance>/.minecraft/libraries/ rather
|
||||
// than the shared meta cache. check there first regardless of
|
||||
// whether the lib has a downloads.artifact entry.
|
||||
if has_local_libs {
|
||||
let in_local = local_lib_dir.join(&rel);
|
||||
if in_local.exists() {
|
||||
@@ -538,14 +575,10 @@ pub async fn build_launch_invocation(
|
||||
.join(format!("{}.jar", config.game_version)),
|
||||
);
|
||||
|
||||
// apply loader-specific patches (lwjgl3ify for old forge on java 9+)
|
||||
let (patch_jvm_args, main_class, extra_args) = if matches!(config.loader, ModLoader::Forge) {
|
||||
match patches::apply(&minecraft_dir, &lib_dir, &mut classpath).await {
|
||||
Some(p) => (p.jvm_args, p.main_class, p.extra_args),
|
||||
None => (Vec::new(), main_class, Vec::new()),
|
||||
}
|
||||
let (main_class, extra_args, patch_jvm_args) = if let Some(patches) = patches {
|
||||
patches::apply(patches, &minecraft_dir, &lib_dir, &mut classpath).await?
|
||||
} else {
|
||||
(Vec::new(), main_class, Vec::new())
|
||||
(main_class, Vec::new(), Vec::new())
|
||||
};
|
||||
|
||||
let sep = if cfg!(windows) { ";" } else { ":" };
|
||||
@@ -555,33 +588,7 @@ pub async fn build_launch_invocation(
|
||||
.collect::<Vec<_>>()
|
||||
.join(sep);
|
||||
|
||||
// java resolution: instance override > global setting > auto-detect
|
||||
let java = config
|
||||
.java_path
|
||||
.clone()
|
||||
.or_else(|| {
|
||||
crate::config::SETTINGS
|
||||
.read()
|
||||
.paths
|
||||
.effective_java_path()
|
||||
.map(str::to_owned)
|
||||
})
|
||||
.unwrap_or_else(crate::instance::java::detect_java_path);
|
||||
|
||||
check_java_version(
|
||||
&java,
|
||||
merged_profile
|
||||
.java_version
|
||||
.as_ref()
|
||||
.map(|version| version.major_version),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let assets_root = metadata_paths.assets();
|
||||
let natives_dir = metadata_paths
|
||||
.versions()
|
||||
.join(&config.game_version)
|
||||
.join("natives");
|
||||
let version_type = merged_profile.type_.as_deref().unwrap_or("release");
|
||||
let resolution_width = resolution.map(|(width, _)| width.to_string());
|
||||
let resolution_height = resolution.map(|(_, height)| height.to_string());
|
||||
@@ -616,8 +623,7 @@ pub async fn build_launch_invocation(
|
||||
apply_custom_resolution(&mut game_args, resolution);
|
||||
apply_window_mode(&mut game_args, window_mode);
|
||||
|
||||
let (memory_min, memory_max, global_jvm_args, global_environment) = {
|
||||
let settings = crate::config::SETTINGS.read();
|
||||
let (memory_min, memory_max, global_jvm_args) = {
|
||||
(
|
||||
config
|
||||
.memory_min
|
||||
@@ -628,10 +634,12 @@ pub async fn build_launch_invocation(
|
||||
.clone()
|
||||
.unwrap_or_else(|| settings.defaults.memory_max.clone()),
|
||||
settings.defaults.jvm_args.clone(),
|
||||
settings.defaults.environment.clone(),
|
||||
)
|
||||
};
|
||||
let mut jvm_args: Vec<String> = vec![format!("-Xms{memory_min}"), format!("-Xmx{memory_max}")];
|
||||
if merged_profile.arguments.is_none() {
|
||||
jvm_args.push(format!("-Djava.library.path={}", natives_dir.display()));
|
||||
}
|
||||
jvm_args.extend(patch_jvm_args);
|
||||
jvm_args.extend(upstream_jvm_args);
|
||||
jvm_args.extend(global_jvm_args);
|
||||
@@ -640,9 +648,6 @@ pub async fn build_launch_invocation(
|
||||
jvm_args.push(format!("-Dorg.lwjgl.glfw.libname={glfw_path}"));
|
||||
}
|
||||
|
||||
let mut environment = global_environment;
|
||||
environment.extend(config.environment.clone());
|
||||
|
||||
Ok(LaunchInvocation {
|
||||
java,
|
||||
jvm_args,
|
||||
@@ -659,8 +664,12 @@ pub async fn build_launch_invocation(
|
||||
fn command_process(command: &str) -> tokio::process::Command {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let mut process = tokio::process::Command::new("cmd");
|
||||
process.args(["/C", command]);
|
||||
let mut process = tokio::process::Command::new("cmd.exe");
|
||||
// cmd parses shell text rather than CRT argv. /S removes this outer pair
|
||||
// of quotes; raw_arg preserves all quotes and metacharacters inside it.
|
||||
process
|
||||
.args(["/D", "/S", "/C"])
|
||||
.raw_arg(format!("\"{command}\""));
|
||||
process
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
@@ -698,51 +707,82 @@ async fn run_launch_command(
|
||||
.envs(&invocation.environment)
|
||||
.env("INST_NAME", &config.name)
|
||||
.env("INST_ID", &config.name)
|
||||
.env("INST_DIR", instance_dir)
|
||||
.env("INST_DIR", std::path::absolute(instance_dir)?)
|
||||
.env("INST_MC_DIR", &invocation.working_dir)
|
||||
.env("INST_JAVA", &invocation.java)
|
||||
.env("INST_JAVA_ARGS", invocation.jvm_args.join(" "));
|
||||
let output = process
|
||||
.output()
|
||||
.await
|
||||
.map_err(|error| LaunchError::Command {
|
||||
.env("INST_JAVA_ARGS", invocation.jvm_args.join(" "))
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped());
|
||||
let (mut child, tree) =
|
||||
process::spawn_owned(&mut process).map_err(|error| LaunchError::Command {
|
||||
phase,
|
||||
reason: error.to_string(),
|
||||
})?;
|
||||
for line in String::from_utf8_lossy(&output.stdout).lines() {
|
||||
tracing::info!("[{}] [{}] {}", config.name, phase, line);
|
||||
let (sender, mut receiver) = tokio::sync::mpsc::channel(64);
|
||||
let mut readers = tokio::task::JoinSet::new();
|
||||
if let Some(stdout) = child.stdout.take() {
|
||||
readers.spawn(output::capture(
|
||||
stdout,
|
||||
parser::LogStream::Stdout,
|
||||
sender.clone(),
|
||||
Default::default(),
|
||||
));
|
||||
}
|
||||
for line in String::from_utf8_lossy(&output.stderr).lines() {
|
||||
tracing::warn!("[{}] [{}] {}", config.name, phase, line);
|
||||
if let Some(stderr) = child.stderr.take() {
|
||||
readers.spawn(output::capture(
|
||||
stderr,
|
||||
parser::LogStream::Stderr,
|
||||
sender.clone(),
|
||||
Default::default(),
|
||||
));
|
||||
}
|
||||
if output.status.success() {
|
||||
drop(sender);
|
||||
let log = |stream, line| match stream {
|
||||
parser::LogStream::Stdout => tracing::info!("[{}] [{}] {}", config.name, phase, line),
|
||||
parser::LogStream::Stderr => tracing::warn!("[{}] [{}] {}", config.name, phase, line),
|
||||
};
|
||||
let status = loop {
|
||||
tokio::select! {
|
||||
status = child.wait() => break status?,
|
||||
Some((stream, line)) = receiver.recv() => log(stream, line),
|
||||
}
|
||||
};
|
||||
let drain_deadline = tokio::time::sleep(std::time::Duration::from_secs(1));
|
||||
tokio::pin!(drain_deadline);
|
||||
loop {
|
||||
tokio::select! {
|
||||
line = receiver.recv() => match line { Some((stream, line)) => log(stream, line), None => break },
|
||||
_ = &mut drain_deadline => { tracing::warn!("[{phase}] Output pipes remained open after command exit"); break; },
|
||||
}
|
||||
}
|
||||
// Normal completion can intentionally leave a background command running.
|
||||
// Cancellation before this point still drops the armed process-tree guard.
|
||||
tree.detach().map_err(|error| LaunchError::Command {
|
||||
phase,
|
||||
reason: error.to_string(),
|
||||
})?;
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(LaunchError::Command {
|
||||
phase,
|
||||
reason: output.status.to_string(),
|
||||
reason: status.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_config_sync(
|
||||
active: bool,
|
||||
profile: Option<&str>,
|
||||
meta_dir: &Path,
|
||||
lock: Option<crate::instance::config_sync::ConfigSyncLock>,
|
||||
minecraft_dir: &Path,
|
||||
instance: &str,
|
||||
) {
|
||||
if active
|
||||
&& let Err(error) = crate::instance::config_sync::finish(profile, meta_dir, minecraft_dir)
|
||||
if let Some(lock) = lock
|
||||
&& let Err(error) = crate::instance::config_sync::finish_launch(lock, minecraft_dir)
|
||||
{
|
||||
tracing::warn!("Failed to sync config for '{}': {}", instance, error);
|
||||
}
|
||||
}
|
||||
|
||||
// resolves auth credentials, then builds the launch invocation and spawns
|
||||
// the java process. only thin wrapper logic lives here: token refresh,
|
||||
// process spawn, child supervision. all the heavy lifting (profile loading,
|
||||
// classpath assembly, template rendering) sits behind build_launch_invocation.
|
||||
pub async fn launch(
|
||||
config: &InstanceConfig,
|
||||
instances_dir: &Path,
|
||||
@@ -750,9 +790,18 @@ pub async fn launch(
|
||||
quick_play_world: Option<&str>,
|
||||
) -> Result<(), LaunchError> {
|
||||
let name = config.name.clone();
|
||||
let mut instance_lock = crate::instance::runtime::lock_instance(instances_dir, &name)
|
||||
.map_err(|error| LaunchError::Parse(error.to_string()))?;
|
||||
let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>();
|
||||
let mut kill_rx = Some(kill_rx);
|
||||
crate::instance::runtime::register_kill(&name, kill_tx);
|
||||
let launch_cleanup = LaunchCleanup(name.clone());
|
||||
crate::instance::runtime::set_state(&name, crate::instance::runtime::RunState::Authenticating);
|
||||
|
||||
// resolve auth credentials, refreshing the microsoft token if needed.
|
||||
let mut account_store = crate::auth::AccountStore::load();
|
||||
account_store
|
||||
.check_loaded()
|
||||
.map_err(|error| LaunchError::Auth(error.to_string()))?;
|
||||
let account =
|
||||
select_launch_account(&account_store.accounts, config.preferred_account.as_deref());
|
||||
let Some(acc) = account.cloned() else {
|
||||
@@ -768,32 +817,17 @@ pub async fn launch(
|
||||
}
|
||||
|
||||
let (token, new_refresh, new_expires) = match acc.account_type {
|
||||
AccountType::Microsoft => match crate::auth::refresh_and_get_token(&acc).await {
|
||||
AccountType::Microsoft => match tokio::select! {
|
||||
result = crate::auth::refresh_and_get_token(&acc) => result,
|
||||
_ = wait_for_kill(&mut kill_rx) => return Err(LaunchError::Cancelled),
|
||||
} {
|
||||
Ok(triple) => triple,
|
||||
Err(e) => return Err(LaunchError::Auth(format!("Authentication failed: {e}"))),
|
||||
},
|
||||
AccountType::Offline => ("0".to_string(), None, None),
|
||||
};
|
||||
|
||||
if let Some(stored) = account_store
|
||||
.accounts
|
||||
.iter_mut()
|
||||
.find(|a| a.uuid == acc.uuid)
|
||||
{
|
||||
let mut changed = false;
|
||||
if let Some(new_rt) = new_refresh {
|
||||
stored.refresh_token = Some(new_rt);
|
||||
changed = true;
|
||||
}
|
||||
if let Some(expires) = new_expires {
|
||||
stored.cached_mc_token = Some(token.clone());
|
||||
stored.cached_mc_token_expires_at = Some(expires);
|
||||
changed = true;
|
||||
}
|
||||
if changed {
|
||||
account_store.save();
|
||||
}
|
||||
}
|
||||
account_store.update_credentials(&acc.uuid, new_refresh, &token, new_expires)?;
|
||||
|
||||
let user_type = match acc.account_type {
|
||||
AccountType::Microsoft => "msa",
|
||||
@@ -807,8 +841,10 @@ pub async fn launch(
|
||||
user_type,
|
||||
};
|
||||
|
||||
let invocation =
|
||||
build_launch_invocation(config, instances_dir, meta_dir, &auth, quick_play_world).await?;
|
||||
let invocation = tokio::select! {
|
||||
result = build_launch_invocation(config, instances_dir, meta_dir, &auth, quick_play_world) => result?,
|
||||
_ = wait_for_kill(&mut kill_rx) => return Err(LaunchError::Cancelled),
|
||||
};
|
||||
let instance_dir = instances_dir.join(&config.name);
|
||||
tracing::debug!(
|
||||
"[{}] Prepared launch invocation: working_dir={} classpath_entries={} jvm_args={} extra_args={} game_args={} main_class={}",
|
||||
@@ -820,33 +856,25 @@ pub async fn launch(
|
||||
invocation.game_args.len(),
|
||||
invocation.main_class
|
||||
);
|
||||
let config_sync_profile = config.config_sync_profile.clone();
|
||||
let config_sync_active = crate::instance::config_sync::prepare(
|
||||
config_sync_profile.as_deref(),
|
||||
let config_sync_lock = crate::instance::config_sync::prepare_for_launch(
|
||||
config.config_sync_profile.as_deref(),
|
||||
meta_dir,
|
||||
&invocation.working_dir,
|
||||
)?;
|
||||
if let Err(error) = run_launch_command(
|
||||
if let Err(error) = tokio::select! {
|
||||
result = run_launch_command(
|
||||
"Pre-launch",
|
||||
&config.pre_launch_command,
|
||||
config,
|
||||
&invocation,
|
||||
&instance_dir,
|
||||
)
|
||||
.await
|
||||
{
|
||||
finish_config_sync(
|
||||
config_sync_active,
|
||||
config_sync_profile.as_deref(),
|
||||
meta_dir,
|
||||
&invocation.working_dir,
|
||||
&name,
|
||||
);
|
||||
) => result,
|
||||
_ = wait_for_kill(&mut kill_rx) => Err(LaunchError::Cancelled),
|
||||
} {
|
||||
finish_config_sync(config_sync_lock, &invocation.working_dir, &name);
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>();
|
||||
crate::instance::runtime::register_kill(&name, kill_tx);
|
||||
crate::instance::runtime::set_state(&name, crate::instance::runtime::RunState::Starting);
|
||||
tracing::info!(
|
||||
"[{}] Starting Minecraft ({} {})",
|
||||
@@ -879,25 +907,24 @@ pub async fn launch(
|
||||
cmd.envs(&invocation.environment);
|
||||
cmd.stdout(std::process::Stdio::piped());
|
||||
cmd.stderr(std::process::Stdio::piped());
|
||||
cmd.kill_on_drop(true);
|
||||
|
||||
let mut child = match cmd.spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
crate::instance::runtime::cleanup_kill_sender(&name);
|
||||
crate::instance::runtime::remove(&name);
|
||||
finish_config_sync(
|
||||
config_sync_active,
|
||||
config_sync_profile.as_deref(),
|
||||
meta_dir,
|
||||
&invocation.working_dir,
|
||||
&name,
|
||||
);
|
||||
finish_config_sync(config_sync_lock, &invocation.working_dir, &name);
|
||||
tracing::error!("[{}] Failed to spawn Minecraft process: {}", name, e);
|
||||
return Err(LaunchError::Io(e));
|
||||
}
|
||||
};
|
||||
tracing::debug!("[{}] Spawned Minecraft process", name);
|
||||
|
||||
if let Err(error) = instance_lock.allow_content_changes() {
|
||||
finish_config_sync(config_sync_lock, &invocation.working_dir, &name);
|
||||
return Err(error.into());
|
||||
}
|
||||
crate::instance::runtime::set_state(&name, crate::instance::runtime::RunState::Running);
|
||||
|
||||
let log_file_path = crate::instance::logs::files::create_log_file(instances_dir, &name);
|
||||
@@ -919,14 +946,12 @@ pub async fn launch(
|
||||
let config_for_post_exit = config.clone();
|
||||
let invocation_for_post_exit = invocation.clone();
|
||||
|
||||
// spawn a background task to babysit the child process: capture stdout/stderr
|
||||
// into both the TUI log viewer and a timestamped log file on disk
|
||||
tokio::spawn(async move {
|
||||
use std::io::Write;
|
||||
let _instance_lock = instance_lock;
|
||||
let _launch_cleanup = launch_cleanup;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::{Duration, sleep};
|
||||
use tokio::time::Duration;
|
||||
|
||||
use crate::instance::launch::parser::{LogStream, MinecraftLogParser};
|
||||
|
||||
@@ -939,6 +964,9 @@ pub async fn launch(
|
||||
let parser_task = tokio::spawn(async move {
|
||||
let mut parser = MinecraftLogParser::new();
|
||||
let idle_flush = Duration::from_millis(150);
|
||||
let mut flush_interval = tokio::time::interval(idle_flush);
|
||||
flush_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
flush_interval.tick().await;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
@@ -952,7 +980,7 @@ pub async fn launch(
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
_ = sleep(idle_flush), if parser.has_pending() => {
|
||||
_ = flush_interval.tick(), if parser.has_pending() => {
|
||||
if let Some(event) = parser.flush() {
|
||||
emit_parsed_instance_log(&parser_name, event);
|
||||
}
|
||||
@@ -965,48 +993,28 @@ pub async fn launch(
|
||||
}
|
||||
});
|
||||
|
||||
let mut readers = tokio::task::JoinSet::new();
|
||||
if let Some(stdout) = child.stdout.take() {
|
||||
let w = log_writer.clone();
|
||||
let tx = log_tx.clone();
|
||||
let mut lines = tokio::io::BufReader::new(stdout).lines();
|
||||
tokio::spawn(async move {
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
if let Ok(mut f) = w.lock()
|
||||
&& let Some(f) = f.as_mut()
|
||||
{
|
||||
let _ = writeln!(f, "{}", line);
|
||||
}
|
||||
if tx.send((LogStream::Stdout, line)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
tracing::trace!("Minecraft stdout capture task ended");
|
||||
});
|
||||
readers.spawn(output::capture(
|
||||
stdout,
|
||||
LogStream::Stdout,
|
||||
log_tx.clone(),
|
||||
log_writer.clone(),
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(stderr) = child.stderr.take() {
|
||||
let w = log_writer.clone();
|
||||
let tx = log_tx.clone();
|
||||
let mut lines = tokio::io::BufReader::new(stderr).lines();
|
||||
tokio::spawn(async move {
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
if let Ok(mut f) = w.lock()
|
||||
&& let Some(f) = f.as_mut()
|
||||
{
|
||||
let _ = writeln!(f, "{}", line);
|
||||
}
|
||||
if tx.send((LogStream::Stderr, line)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
tracing::trace!("Minecraft stderr capture task ended");
|
||||
});
|
||||
readers.spawn(output::capture(
|
||||
stderr,
|
||||
LogStream::Stderr,
|
||||
log_tx.clone(),
|
||||
log_writer.clone(),
|
||||
));
|
||||
}
|
||||
drop(log_tx);
|
||||
|
||||
// wait for either the process to exit naturally or a kill signal from the TUI
|
||||
let (code, killed_by_user) = tokio::select! {
|
||||
_ = kill_rx => {
|
||||
_ = wait_for_kill(&mut kill_rx) => {
|
||||
tracing::info!("[{}] Kill requested, terminating process", name_for_task);
|
||||
let _ = child.kill().await;
|
||||
let _ = child.wait().await;
|
||||
@@ -1016,29 +1024,46 @@ pub async fn launch(
|
||||
(result.ok().and_then(|s| s.code()), false)
|
||||
}
|
||||
};
|
||||
if tokio::time::timeout(Duration::from_secs(1), async {
|
||||
while readers.join_next().await.is_some() {}
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!("Minecraft output pipes remained open after process exit");
|
||||
readers.abort_all();
|
||||
while readers.join_next().await.is_some() {}
|
||||
}
|
||||
let _ = parser_task.await;
|
||||
tracing::info!("[{}] Exited with code {:?}", name_for_task, code);
|
||||
|
||||
if let Err(error) = run_launch_command(
|
||||
"Post-exit",
|
||||
&post_exit_command,
|
||||
&config_for_post_exit,
|
||||
&invocation_for_post_exit,
|
||||
&instance_dir_owned,
|
||||
)
|
||||
.await
|
||||
if !killed_by_user
|
||||
&& let Err(error) = tokio::select! {
|
||||
result = run_launch_command(
|
||||
"Post-exit",
|
||||
&post_exit_command,
|
||||
&config_for_post_exit,
|
||||
&invocation_for_post_exit,
|
||||
&instance_dir_owned,
|
||||
) => result,
|
||||
_ = wait_for_kill(&mut kill_rx) => Err(LaunchError::Cancelled),
|
||||
}
|
||||
{
|
||||
tracing::warn!("[{}] {}", name_for_task, error);
|
||||
crate::feedback::errors::push_message(tracing::Level::WARN, error.to_string());
|
||||
}
|
||||
|
||||
finish_config_sync(
|
||||
config_sync_active,
|
||||
config_sync_profile.as_deref(),
|
||||
&meta_dir_owned,
|
||||
&minecraft_dir_owned,
|
||||
&name_for_task,
|
||||
);
|
||||
finish_config_sync(config_sync_lock, &minecraft_dir_owned, &name_for_task);
|
||||
let manager = crate::instance::InstanceManager::new(instances_dir_owned, meta_dir_owned);
|
||||
if let Err(e) = manager.touch_last_played(&name_for_task) {
|
||||
tracing::warn!(
|
||||
"Failed to update last_played for '{}': {}",
|
||||
name_for_task,
|
||||
e
|
||||
);
|
||||
}
|
||||
crate::instance::runtime::push_last_played(&name_for_task, chrono::Utc::now());
|
||||
crate::instance::runtime::cleanup_kill_sender(&name_for_task);
|
||||
if code == Some(0) || killed_by_user {
|
||||
crate::instance::runtime::remove(&name_for_task);
|
||||
tracing::debug!(
|
||||
@@ -1063,17 +1088,6 @@ pub async fn launch(
|
||||
pushed_at: std::time::Instant::now(),
|
||||
});
|
||||
}
|
||||
|
||||
let manager = crate::instance::InstanceManager::new(instances_dir_owned, meta_dir_owned);
|
||||
if let Err(e) = manager.touch_last_played(&name_for_task) {
|
||||
tracing::warn!(
|
||||
"Failed to update last_played for '{}': {}",
|
||||
name_for_task,
|
||||
e
|
||||
);
|
||||
}
|
||||
crate::instance::runtime::push_last_played(&name_for_task, chrono::Utc::now());
|
||||
crate::instance::runtime::cleanup_kill_sender(&name_for_task);
|
||||
});
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt};
|
||||
|
||||
use super::parser::LogStream;
|
||||
|
||||
pub(super) type LogWriter = Arc<Mutex<Option<std::fs::File>>>;
|
||||
|
||||
pub(super) async fn capture(
|
||||
reader: impl tokio::io::AsyncRead + Unpin,
|
||||
stream: LogStream,
|
||||
sender: tokio::sync::mpsc::Sender<(LogStream, String)>,
|
||||
writer: LogWriter,
|
||||
) {
|
||||
use std::io::Write;
|
||||
let mut reader = tokio::io::BufReader::new(reader);
|
||||
loop {
|
||||
let mut bytes = Vec::new();
|
||||
match (&mut reader)
|
||||
.take(64 * 1024)
|
||||
.read_until(b'\n', &mut bytes)
|
||||
.await
|
||||
{
|
||||
Ok(0) => break,
|
||||
Ok(_) => {}
|
||||
Err(error) => {
|
||||
tracing::warn!("Minecraft output read failed: {error}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let Ok(mut file) = writer.lock()
|
||||
&& let Some(file) = file.as_mut()
|
||||
&& let Err(error) = file.write_all(&bytes)
|
||||
{
|
||||
tracing::warn!("Minecraft log write failed: {error}");
|
||||
}
|
||||
let line = String::from_utf8_lossy(&bytes)
|
||||
.trim_end_matches(['\r', '\n'])
|
||||
.to_owned();
|
||||
if sender.send((stream, line)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_utf8_and_long_lines_keep_following_output() {
|
||||
let mut bytes = vec![b'x'; 128 * 1024];
|
||||
bytes.extend_from_slice(b"\ninvalid \xff\nlast\n");
|
||||
let (sender, mut receiver) = tokio::sync::mpsc::channel(8);
|
||||
capture(
|
||||
bytes.as_slice(),
|
||||
LogStream::Stdout,
|
||||
sender,
|
||||
Default::default(),
|
||||
)
|
||||
.await;
|
||||
let mut lines = Vec::new();
|
||||
while let Some((_, line)) = receiver.recv().await {
|
||||
lines.push(line);
|
||||
}
|
||||
assert!(lines.iter().all(|line| line.len() <= 64 * 1024));
|
||||
assert!(lines.iter().any(|line| line == "invalid �"));
|
||||
assert_eq!(lines.last().unwrap(), "last");
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// live minecraft process log parser.
|
||||
//
|
||||
// disk launch logs stay raw, but the tui needs enough structure to color and
|
||||
// group output sanely. this parser keeps stdout/stderr as a hint, frames
|
||||
// multiline java/jvm/native bursts into events, then assigns a semantic level.
|
||||
@@ -123,7 +121,10 @@ impl MinecraftLogParser {
|
||||
|
||||
// only hard starts split events. this keeps stacktraces and native
|
||||
// loader bursts together even when they arrive one line at a time.
|
||||
if should_split(current.kind, analysis.kind) {
|
||||
if should_split(current.kind, analysis.kind)
|
||||
|| current.lines.len() >= 128
|
||||
|| current.lines.iter().map(String::len).sum::<usize>() >= 64 * 1024
|
||||
{
|
||||
let finished = self.current.take().map(finish_event);
|
||||
self.current = Some(PendingEvent::new(stream, line, normalized, analysis));
|
||||
finished.into_iter().collect()
|
||||
|
||||
+213
-176
@@ -1,69 +1,130 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// classpath and jvm patches for legacy forge on java 9+.
|
||||
// lwjgl3ify ships a patched launchwrapper and retrofuturabootstrap that
|
||||
// replace the old URLClassLoader-based launcher with one that works on
|
||||
// modern java. this module handles extracting those patches, building
|
||||
// the right --add-opens flags, and swapping out the broken log4j jars.
|
||||
// modern java.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::LaunchError;
|
||||
use crate::launch_profile::{model::LaunchProfile, system::JavaPlatform};
|
||||
|
||||
const LOG4J_FIXED_BASE: &str = "https://files.prismlauncher.org/maven/org/apache/logging/log4j";
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct LwjglifyPatches {
|
||||
pub jvm_args: Vec<String>,
|
||||
pub main_class: String,
|
||||
// extra args inserted before game args (used by the shim to pass
|
||||
// the real main class name)
|
||||
pub extra_args: Vec<String>,
|
||||
pub profile: LaunchProfile,
|
||||
patches_path: PathBuf,
|
||||
}
|
||||
|
||||
// checks if lwjgl3ify is present in the mods folder, and if so:
|
||||
// 1. extracts forge patches from the lwjgl3ify jar
|
||||
// 2. prepends them to the classpath so they shadow vanilla launchwrapper
|
||||
// 3. parses --add-opens from the patches manifest
|
||||
// 4. replaces log4j 2.0-beta9 with prism's patched builds
|
||||
// 5. returns the jvm args and overridden main class
|
||||
pub async fn apply(
|
||||
pub fn load(
|
||||
minecraft_dir: &Path,
|
||||
lib_dir: &Path,
|
||||
classpath: &mut Vec<PathBuf>,
|
||||
) -> Option<LwjglifyPatches> {
|
||||
platform: &JavaPlatform,
|
||||
) -> Result<Option<LwjglifyPatches>, LaunchError> {
|
||||
use sha1::Digest;
|
||||
use std::io::Read;
|
||||
|
||||
let mods_dir = minecraft_dir.join("mods");
|
||||
let lwjgl3ify_jar = find_lwjgl3ify_jar(&mods_dir)?;
|
||||
let Some(lwjgl3ify_jar) = find_lwjgl3ify_jar(&mods_dir)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let file = std::fs::File::open(&lwjgl3ify_jar)?;
|
||||
let mut archive = zip::ZipArchive::new(file).map_err(|error| {
|
||||
LaunchError::Parse(format!(
|
||||
"Invalid lwjgl3ify jar {}: {error}",
|
||||
lwjgl3ify_jar.display()
|
||||
))
|
||||
})?;
|
||||
let entry = archive
|
||||
.by_name("me/eigenraven/lwjgl3ify/relauncher/version.json")
|
||||
.map_err(|error| {
|
||||
LaunchError::Parse(format!(
|
||||
"lwjgl3ify bundled client profile is missing in {}: {error}",
|
||||
lwjgl3ify_jar.display()
|
||||
))
|
||||
})?;
|
||||
let mut profile: LaunchProfile = serde_json::from_reader(entry)?;
|
||||
if profile
|
||||
.main_class
|
||||
.as_deref()
|
||||
.is_none_or(|main| main.trim().is_empty())
|
||||
|| profile.arguments.is_none()
|
||||
|| profile
|
||||
.java_version
|
||||
.as_ref()
|
||||
.is_none_or(|version| version.major_version == 0)
|
||||
{
|
||||
return Err(LaunchError::Parse(
|
||||
"lwjgl3ify bundled client profile is missing mainClass, arguments or javaVersion"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
for lib in &profile.libraries {
|
||||
if lib
|
||||
.downloads
|
||||
.as_ref()
|
||||
.is_none_or(|downloads| downloads.artifact.is_none() && lib.natives.is_none())
|
||||
{
|
||||
return Err(LaunchError::Parse(format!(
|
||||
"lwjgl3ify bundled library {} is missing download metadata",
|
||||
lib.name
|
||||
)));
|
||||
}
|
||||
}
|
||||
select_lwjgl_natives(&mut profile, platform)?;
|
||||
|
||||
let patch_artifact = profile
|
||||
.libraries
|
||||
.iter()
|
||||
.find(|lib| lib.name.ends_with(":forgePatches"))
|
||||
.and_then(|lib| lib.downloads.as_ref())
|
||||
.and_then(|downloads| downloads.artifact.as_ref())
|
||||
.ok_or_else(|| {
|
||||
LaunchError::Parse(
|
||||
"lwjgl3ify bundled profile is missing the forgePatches artifact".into(),
|
||||
)
|
||||
})?;
|
||||
let mut payload = Vec::new();
|
||||
archive
|
||||
.by_name("me/eigenraven/lwjgl3ify/relauncher/forgePatches.zip")
|
||||
.map_err(|error| {
|
||||
LaunchError::Parse(format!(
|
||||
"lwjgl3ify forgePatches payload is missing: {error}"
|
||||
))
|
||||
})?
|
||||
.read_to_end(&mut payload)?;
|
||||
if payload.len() as u64 != patch_artifact.size
|
||||
|| !format!("{:x}", sha1::Sha1::digest(&payload)).eq_ignore_ascii_case(&patch_artifact.sha1)
|
||||
{
|
||||
return Err(LaunchError::Parse(
|
||||
"lwjgl3ify embedded forgePatches does not match its bundled profile".into(),
|
||||
));
|
||||
}
|
||||
profile
|
||||
.libraries
|
||||
.retain(|lib| !lib.name.ends_with(":forgePatches"));
|
||||
|
||||
// rfb only scans jars for plugin metadata. keeping the extracted
|
||||
// forgePatches payload as a zip makes it skip rfb-asm-safety and
|
||||
// rfb-modern-java, which GTNH needs on modern Java.
|
||||
let patches_dest = minecraft_dir.join(".forge-patches.jar");
|
||||
let patches_path = minecraft_dir.join(".forge-patches.jar");
|
||||
crate::storage::write_atomic(&patches_path, &payload)?;
|
||||
Ok(Some(LwjglifyPatches {
|
||||
profile,
|
||||
patches_path,
|
||||
}))
|
||||
}
|
||||
|
||||
if let Err(e) = extract_forge_patches(&lwjgl3ify_jar, &patches_dest) {
|
||||
tracing::warn!("Failed to extract lwjgl3ify forge patches: {e}");
|
||||
return None;
|
||||
}
|
||||
|
||||
// prepend so patched classes shadow vanilla launchwrapper
|
||||
classpath.insert(0, patches_dest.clone());
|
||||
|
||||
let mut jvm_args = parse_add_opens(&patches_dest).unwrap_or_default();
|
||||
|
||||
// RFB requires its own classloader to be the system classloader, and
|
||||
// its Main class handles bootstrapping into launchwrapper.
|
||||
// the other flags match lwjgl3ify's java9args.txt.
|
||||
jvm_args.extend([
|
||||
"-Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader"
|
||||
.to_string(),
|
||||
"-Dfile.encoding=UTF-8".to_string(),
|
||||
]);
|
||||
|
||||
// forge patches replace launchwrapper, asm, and old lwjgl2.
|
||||
// lwjgl3ify redirects lwjgl2 calls to lwjgl3 at runtime, so lwjgl3
|
||||
// must be on the classpath (matching what prism does).
|
||||
strip_replaced_libs(classpath);
|
||||
add_lwjgl3(lib_dir, classpath);
|
||||
|
||||
replace_log4j_fixed(lib_dir, classpath).await;
|
||||
pub async fn apply(
|
||||
patches: LwjglifyPatches,
|
||||
minecraft_dir: &Path,
|
||||
lib_dir: &Path,
|
||||
classpath: &mut Vec<PathBuf>,
|
||||
) -> Result<(String, Vec<String>, Vec<String>), LaunchError> {
|
||||
classpath.insert(0, patches.patches_path);
|
||||
replace_log4j_fixed(lib_dir, classpath).await?;
|
||||
let mut jvm_args = Vec::new();
|
||||
|
||||
// on java 24+, SecurityManager.getClassContext() was reimplemented to use
|
||||
// StackWalker. log4j 2.0-beta9's ThrowableProxy calls getClassContext() to
|
||||
@@ -72,7 +133,7 @@ pub async fn apply(
|
||||
// ThrowableProxy... infinite recursion. we break the loop by providing a
|
||||
// log4j config that sets the root level to INFO, so the debug() call in
|
||||
// LaunchClassLoader is a no-op and never creates a ThrowableProxy.
|
||||
write_log4j_config(minecraft_dir, &mut jvm_args);
|
||||
write_log4j_config(minecraft_dir, &mut jvm_args)?;
|
||||
|
||||
// RfbSystemClassLoader discovers plugins differently depending on whether
|
||||
// the main class is loaded by the JVM directly or through the system
|
||||
@@ -81,81 +142,57 @@ pub async fn apply(
|
||||
// ClassCircularityErrors. we use a tiny shim jar that loads the real main
|
||||
// class through ClassLoader.getSystemClassLoader().loadClass(), matching
|
||||
// how prism's EntryPoint does it.
|
||||
let shim_path = deploy_shim(minecraft_dir);
|
||||
let shim_path = deploy_shim(minecraft_dir)?;
|
||||
classpath.insert(0, shim_path);
|
||||
|
||||
Some(LwjglifyPatches {
|
||||
Ok((
|
||||
"RmclShim".to_owned(),
|
||||
vec![
|
||||
patches
|
||||
.profile
|
||||
.main_class
|
||||
.expect("validated client main class"),
|
||||
],
|
||||
jvm_args,
|
||||
main_class: "RmclShim".to_string(),
|
||||
extra_args: vec!["com.gtnewhorizons.retrofuturabootstrap.Main".to_string()],
|
||||
})
|
||||
))
|
||||
}
|
||||
|
||||
const SHIM_JAR: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/rmcl-shim.jar"));
|
||||
|
||||
fn deploy_shim(minecraft_dir: &Path) -> PathBuf {
|
||||
fn deploy_shim(minecraft_dir: &Path) -> std::io::Result<PathBuf> {
|
||||
let dest = minecraft_dir.join(".rmcl-shim.jar");
|
||||
if let Err(e) = std::fs::write(&dest, SHIM_JAR) {
|
||||
tracing::warn!("Failed to write rmcl-shim.jar: {e}");
|
||||
}
|
||||
dest
|
||||
crate::storage::write_atomic(&dest, SHIM_JAR)?;
|
||||
Ok(dest)
|
||||
}
|
||||
|
||||
fn find_lwjgl3ify_jar(mods_dir: &Path) -> Option<PathBuf> {
|
||||
let entries = std::fs::read_dir(mods_dir).ok()?;
|
||||
for entry in entries.flatten() {
|
||||
fn find_lwjgl3ify_jar(mods_dir: &Path) -> std::io::Result<Option<PathBuf>> {
|
||||
let entries = match std::fs::read_dir(mods_dir) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let mut found = None;
|
||||
for entry in entries {
|
||||
let entry = entry?;
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
if name.starts_with("lwjgl3ify") && name.ends_with(".jar") {
|
||||
return Some(entry.path());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn extract_forge_patches(lwjgl3ify_jar: &Path, dest: &Path) -> Result<(), std::io::Error> {
|
||||
use std::io::Read;
|
||||
|
||||
let file = std::fs::File::open(lwjgl3ify_jar)?;
|
||||
let mut archive = zip::ZipArchive::new(file)
|
||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
|
||||
let mut entry = archive
|
||||
.by_name("me/eigenraven/lwjgl3ify/relauncher/forgePatches.zip")
|
||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::NotFound, e))?;
|
||||
let mut buf = Vec::new();
|
||||
entry.read_to_end(&mut buf)?;
|
||||
std::fs::write(dest, &buf)
|
||||
}
|
||||
|
||||
fn parse_add_opens(patches_archive: &Path) -> Option<Vec<String>> {
|
||||
use std::io::Read;
|
||||
|
||||
let file = std::fs::File::open(patches_archive).ok()?;
|
||||
let mut archive = zip::ZipArchive::new(file).ok()?;
|
||||
let mut entry = archive.by_name("META-INF/MANIFEST.MF").ok()?;
|
||||
let mut manifest = String::new();
|
||||
entry.read_to_string(&mut manifest).ok()?;
|
||||
|
||||
// manifest continuation lines start with a single space
|
||||
let manifest = manifest.replace("\r\n ", "").replace("\n ", "");
|
||||
|
||||
let mut args = Vec::new();
|
||||
for line in manifest.lines() {
|
||||
if let Some(value) = line.strip_prefix("Add-Opens: ") {
|
||||
for module_package in value.split_whitespace() {
|
||||
args.push("--add-opens".to_string());
|
||||
args.push(format!("{module_package}=ALL-UNNAMED"));
|
||||
if found.is_some() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"Multiple lwjgl3ify jars found in mods",
|
||||
));
|
||||
}
|
||||
found = Some(entry.path());
|
||||
}
|
||||
}
|
||||
|
||||
Some(args)
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
// strips libraries from the classpath that are replaced by forge patches
|
||||
// or not needed with lwjgl3ify. matches what prism's component system does:
|
||||
// no old lwjgl2, no vanilla launchwrapper/asm, no extra vanilla-only libs.
|
||||
fn strip_replaced_libs(classpath: &mut Vec<PathBuf>) {
|
||||
pub fn strip_replaced_libs(profile: &mut LaunchProfile) {
|
||||
let replaced = [
|
||||
"launchwrapper-",
|
||||
"asm-all-",
|
||||
@@ -166,80 +203,83 @@ fn strip_replaced_libs(classpath: &mut Vec<PathBuf>) {
|
||||
"guava-15.",
|
||||
];
|
||||
|
||||
classpath.retain(|entry| {
|
||||
let name = entry
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy())
|
||||
.unwrap_or_default();
|
||||
let dominated = replaced.iter().any(|prefix| name.starts_with(prefix));
|
||||
profile.libraries.retain(|lib| {
|
||||
if lib.name.starts_with("org.lwjgl.lwjgl:") {
|
||||
return false;
|
||||
}
|
||||
let name = lib.name.split(':').collect::<Vec<_>>();
|
||||
let filename = match name.as_slice() {
|
||||
[_, artifact, version, ..] => format!("{artifact}-{version}"),
|
||||
_ => return true,
|
||||
};
|
||||
let dominated = replaced.iter().any(|prefix| filename.starts_with(prefix));
|
||||
if dominated {
|
||||
tracing::info!("Stripping {name} from classpath (replaced by forge-patches)");
|
||||
tracing::info!("Stripping {} (replaced by forge-patches)", lib.name);
|
||||
}
|
||||
!dominated
|
||||
});
|
||||
}
|
||||
|
||||
// adds lwjgl 3.3.3 to the classpath. lwjgl3ify redirects old lwjgl2 calls
|
||||
// to lwjgl3 at runtime, but the lwjgl3 jars need to be on the system
|
||||
// classpath for this to work. prism includes these via its org.lwjgl3
|
||||
// component; we add them from the meta library cache.
|
||||
fn add_lwjgl3(lib_dir: &Path, classpath: &mut Vec<PathBuf>) {
|
||||
let lwjgl3_modules = [
|
||||
"lwjgl",
|
||||
"lwjgl-freetype",
|
||||
"lwjgl-glfw",
|
||||
"lwjgl-jemalloc",
|
||||
"lwjgl-openal",
|
||||
"lwjgl-opengl",
|
||||
"lwjgl-stb",
|
||||
"lwjgl-tinyfd",
|
||||
];
|
||||
|
||||
let os_classifier = match std::env::consts::OS {
|
||||
"macos" => "natives-macos",
|
||||
"windows" => "natives-windows",
|
||||
_ => "natives-linux",
|
||||
// The bundled profile names natives as separate Maven artifacts and uses
|
||||
// OS-only rules for multiple CPU variants. Select exactly the selected JVM's variant.
|
||||
fn select_lwjgl_natives(
|
||||
profile: &mut LaunchProfile,
|
||||
platform: &JavaPlatform,
|
||||
) -> Result<(), LaunchError> {
|
||||
let classifier = match (platform.os_name, platform.arch.as_str(), platform.bitness) {
|
||||
("osx", "arm64", 64) => "natives-macos-arm64",
|
||||
("osx", "x86_64", 64) => "natives-macos",
|
||||
("windows", "arm64", 64) => "natives-windows-arm64",
|
||||
("windows", "x86", 32) => "natives-windows-x86",
|
||||
("windows", "x86_64", 64) => "natives-windows",
|
||||
("linux", "arm64", 64) => "natives-linux-arm64",
|
||||
("linux", "arm", 32) => "natives-linux-arm32",
|
||||
("linux", "ppc64le", 64) => "natives-linux-ppc64le",
|
||||
("linux", "x86_64", 64) => "natives-linux",
|
||||
_ => {
|
||||
return Err(LaunchError::Parse(format!(
|
||||
"lwjgl3ify does not support Java {} {} ({}-bit)",
|
||||
platform.os_name, platform.arch, platform.bitness
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
// insert lwjgl3 jars right after forge patches (position 1+)
|
||||
let mut insert_pos = 1.min(classpath.len());
|
||||
for module in &lwjgl3_modules {
|
||||
let base = if *module == "lwjgl" {
|
||||
lib_dir.join("org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3.jar")
|
||||
} else {
|
||||
lib_dir.join(format!("org/lwjgl/{0}/3.3.3/{0}-3.3.3.jar", module))
|
||||
};
|
||||
if base.exists() {
|
||||
classpath.insert(insert_pos, base);
|
||||
insert_pos += 1;
|
||||
let native = |name: &str| -> Option<(String, String)> {
|
||||
let parts: Vec<_> = name.split(':').collect();
|
||||
match parts.as_slice() {
|
||||
["org.lwjgl", artifact, _, variant] if variant.starts_with("natives-") => {
|
||||
Some(((*artifact).to_owned(), (*variant).to_owned()))
|
||||
}
|
||||
["org.lwjgl", artifact, _] => artifact
|
||||
.split_once("-natives-")
|
||||
.map(|(module, variant)| (module.to_owned(), format!("natives-{variant}"))),
|
||||
_ => None,
|
||||
}
|
||||
|
||||
// natives
|
||||
let natives = if *module == "lwjgl" {
|
||||
lib_dir.join(format!(
|
||||
"org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3-{os_classifier}.jar"
|
||||
))
|
||||
} else {
|
||||
lib_dir.join(format!(
|
||||
"org/lwjgl/{0}/3.3.3/{0}-3.3.3-{1}.jar",
|
||||
module, os_classifier
|
||||
))
|
||||
};
|
||||
let mut native_modules = std::collections::HashSet::new();
|
||||
let mut selected = std::collections::HashSet::new();
|
||||
profile.libraries.retain(|lib| {
|
||||
let Some((module, variant)) = native(&lib.name) else {
|
||||
return true;
|
||||
};
|
||||
if natives.exists() {
|
||||
classpath.insert(insert_pos, natives);
|
||||
insert_pos += 1;
|
||||
native_modules.insert(module.clone());
|
||||
if variant == classifier {
|
||||
selected.insert(module);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
if let Some(missing) = native_modules.difference(&selected).next() {
|
||||
return Err(LaunchError::Parse(format!(
|
||||
"lwjgl3ify bundled profile has no {classifier} for {missing}"
|
||||
)));
|
||||
}
|
||||
|
||||
tracing::info!("Added {} LWJGL 3.3.3 jars to classpath", insert_pos - 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// writes a log4j2.xml config that sets the root logger to INFO. this
|
||||
// prevents LaunchClassLoader's debug() call from ever firing, which
|
||||
// avoids the ThrowableProxy -> SecurityManager -> StackWalker infinite
|
||||
// recursion on java 24+. the config is written to .minecraft/ and
|
||||
// pointed to via -Dlog4j.configurationFile.
|
||||
fn write_log4j_config(minecraft_dir: &Path, jvm_args: &mut Vec<String>) {
|
||||
// Suppresses LaunchClassLoader's debug() call to avoid the
|
||||
// ThrowableProxy -> SecurityManager -> StackWalker recursion on Java 24+.
|
||||
fn write_log4j_config(minecraft_dir: &Path, jvm_args: &mut Vec<String>) -> std::io::Result<()> {
|
||||
let config_path = minecraft_dir.join(".rmcl-log4j2.xml");
|
||||
let config = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="WARN">
|
||||
@@ -268,15 +308,13 @@ fn write_log4j_config(minecraft_dir: &Path, jvm_args: &mut Vec<String>) {
|
||||
</Configuration>
|
||||
"#;
|
||||
|
||||
if let Err(e) = std::fs::write(&config_path, config) {
|
||||
tracing::warn!("Failed to write log4j2 config: {e}");
|
||||
return;
|
||||
}
|
||||
crate::storage::write_atomic(&config_path, config.as_bytes())?;
|
||||
|
||||
jvm_args.push(format!(
|
||||
"-Dlog4j.configurationFile={}",
|
||||
config_path.display()
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// replaces log4j-api and log4j-core 2.0-beta9 in the classpath with
|
||||
@@ -285,7 +323,7 @@ fn write_log4j_config(minecraft_dir: &Path, jvm_args: &mut Vec<String>) {
|
||||
// on java 24+ uses StackWalker internally, triggering class loading
|
||||
// through LaunchClassLoader, which triggers more logging, infinite
|
||||
// recursion, stack overflow. the fixed builds patch this out.
|
||||
async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) {
|
||||
async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) -> Result<(), LaunchError> {
|
||||
let replacements = [
|
||||
(
|
||||
"log4j-api-2.0-beta9.jar",
|
||||
@@ -300,20 +338,18 @@ async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) {
|
||||
];
|
||||
|
||||
for (old_name, fixed_rel, url) in &replacements {
|
||||
if !classpath
|
||||
.iter()
|
||||
.any(|entry| entry.file_name().is_some_and(|name| name == *old_name))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let fixed_path = lib_dir.join(fixed_rel);
|
||||
|
||||
if !fixed_path.exists() {
|
||||
tracing::info!("Downloading patched {old_name}...");
|
||||
if let Some(parent) = fixed_path.parent() {
|
||||
let _ = tokio::fs::create_dir_all(parent).await;
|
||||
}
|
||||
let client = crate::net::HttpClient::new();
|
||||
if let Err(e) = crate::net::download_file(&client, url, &fixed_path, |_, _| {}).await {
|
||||
tracing::error!(
|
||||
"Failed to download patched {old_name}: {e}, continuing with unpatched version"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
crate::net::download_file(&client, url, &fixed_path, |_, _| {}).await?;
|
||||
}
|
||||
|
||||
for entry in classpath.iter_mut() {
|
||||
@@ -326,6 +362,7 @@ async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) {
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// fabric installation. the nice one: just fetch a profile json and download
|
||||
// the libraries. no java installer nonsense required.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// forge installation. modern forge runs a java installer, old forge (pre-1.13)
|
||||
// can't run headless so we extract the profile and libraries from the jar
|
||||
// directly. the installer jar gets cleaned up either way.
|
||||
// Old Forge installers cannot run headless, so their profiles and libraries
|
||||
// must be extracted from the jar instead.
|
||||
|
||||
use std::path::Path;
|
||||
use std::{collections::BTreeMap, path::Path};
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
@@ -49,17 +48,24 @@ impl ModLoaderInstaller for ForgeInstaller {
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), InstallError> {
|
||||
let settings = crate::config::SETTINGS.read().clone();
|
||||
let environment = crate::instance::java::merge_environment(
|
||||
&settings.defaults.environment,
|
||||
&Default::default(),
|
||||
);
|
||||
self.install_with_java(
|
||||
client,
|
||||
game_version,
|
||||
loader_version,
|
||||
instance_dir,
|
||||
meta_dir,
|
||||
None,
|
||||
settings.paths.effective_java_path(),
|
||||
&environment,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn install_with_java(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
@@ -68,6 +74,7 @@ impl ModLoaderInstaller for ForgeInstaller {
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
java_path: Option<&str>,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> Result<(), InstallError> {
|
||||
let installer_jar = instance_dir
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
@@ -85,7 +92,6 @@ impl ModLoaderInstaller for ForgeInstaller {
|
||||
let profile_filename = format!("forge-{game_version}-{loader_version}.json");
|
||||
|
||||
if has_legacy_install_profile(&installer_jar) {
|
||||
// old forge: no --installClient support, extract directly from jar
|
||||
tracing::debug!("Forge installer uses legacy install_profile.json path");
|
||||
if let Err(e) =
|
||||
install_forge_from_profile(client, &installer_jar, meta_dir, &profile_filename)
|
||||
@@ -95,22 +101,13 @@ impl ModLoaderInstaller for ForgeInstaller {
|
||||
return Err(e);
|
||||
}
|
||||
} else {
|
||||
// modern forge: run the java installer
|
||||
let java_path = java_path.map(str::to_owned).unwrap_or_else(|| {
|
||||
crate::config::SETTINGS
|
||||
.read()
|
||||
.paths
|
||||
.effective_java_path()
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(crate::instance::java::detect_java_path)
|
||||
});
|
||||
tracing::debug!("Running Forge installer with Java {}", java_path);
|
||||
if let Err(e) = run_forge_installer(&installer_jar, instance_dir, &java_path).await {
|
||||
if let Err(e) =
|
||||
run_forge_installer(&installer_jar, instance_dir, java_path, environment).await
|
||||
{
|
||||
let _ = tokio::fs::remove_file(&installer_jar).await;
|
||||
return Err(InstallError::Installer(e));
|
||||
}
|
||||
|
||||
// extract the profile from what the installer just wrote to disk
|
||||
save_forge_profile(instance_dir, meta_dir, game_version, loader_version)
|
||||
.map_err(InstallError::Installer)?;
|
||||
}
|
||||
@@ -131,19 +128,26 @@ impl ModLoaderInstaller for ForgeInstaller {
|
||||
pub async fn run_forge_installer(
|
||||
installer_path: &Path,
|
||||
instance_dir: &Path,
|
||||
java_path: &str,
|
||||
java_path: Option<&str>,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> Result<(), InstallerError> {
|
||||
use tokio::process::Command;
|
||||
|
||||
set_action("Running Forge installer...");
|
||||
let minecraft_dir = std::path::absolute(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME))?;
|
||||
let java_path =
|
||||
crate::instance::java::resolve_java_path_in(java_path, &minecraft_dir, environment);
|
||||
tracing::debug!("Running Forge installer with Java {}", java_path);
|
||||
|
||||
let output = match Command::new(java_path)
|
||||
.arg("-jar")
|
||||
.arg(installer_path)
|
||||
.arg("--installClient")
|
||||
.current_dir(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME))
|
||||
.output()
|
||||
.await
|
||||
let output = match crate::instance::process::output(
|
||||
Command::new(&java_path)
|
||||
.arg("-jar")
|
||||
.arg(std::path::absolute(installer_path)?)
|
||||
.arg("--installClient")
|
||||
.current_dir(&minecraft_dir)
|
||||
.envs(environment),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
@@ -271,7 +275,6 @@ pub(crate) async fn install_forge_from_profile(
|
||||
InstallError::Installer(InstallerError::Profile("missing install.path".into()))
|
||||
})?;
|
||||
|
||||
// extract the universal jar to the correct maven location
|
||||
let universal_maven_path = crate::instance::loader::maven::maven_coord_to_path(
|
||||
install_path_coord,
|
||||
)
|
||||
@@ -352,12 +355,7 @@ pub(crate) async fn install_forge_from_profile(
|
||||
// inheritsFrom field - implicitly inherits from the configured game
|
||||
// version so vanilla libraries layer in via resolve().
|
||||
//
|
||||
// we use serde_json::to_vec (not the pretty-print variant via
|
||||
// save_profile_json) so the written file is content-faithful: every
|
||||
// field present in the installer's versionInfo round-trips. key order
|
||||
// and whitespace may differ from the original installer JSON because
|
||||
// the source is a serde_json::Value (which doesn't preserve order),
|
||||
// but no field is silently dropped.
|
||||
// Keep unknown installer fields instead of round-tripping a stripped profile model.
|
||||
let serialized = serde_json::to_vec(version_info).map_err(|e| {
|
||||
InstallError::Installer(InstallerError::Profile(format!(
|
||||
"Failed to serialize Forge profile: {e}"
|
||||
|
||||
@@ -1,28 +1,27 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// maven coordinate handling shared by loader installation and launch profiles.
|
||||
|
||||
#[must_use]
|
||||
pub fn maven_coord_to_path(coord: &str) -> Option<String> {
|
||||
let parts: Vec<&str> = coord.split(':').collect();
|
||||
match parts.as_slice() {
|
||||
let path = match parts.as_slice() {
|
||||
[group, artifact, version] => {
|
||||
let group_path = group.replace('.', "/");
|
||||
Some(format!(
|
||||
format!(
|
||||
"{}/{}/{}/{}-{}.jar",
|
||||
group_path, artifact, version, artifact, version
|
||||
))
|
||||
)
|
||||
}
|
||||
[group, artifact, version, classifier] => {
|
||||
let group_path = group.replace('.', "/");
|
||||
Some(format!(
|
||||
format!(
|
||||
"{}/{}/{}/{}-{}-{}.jar",
|
||||
group_path, artifact, version, artifact, version, classifier
|
||||
))
|
||||
)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
crate::storage::safe_relative_path(std::path::Path::new(&path)).then_some(path)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// mod loader installation. each loader (fabric, forge, neoforge, quilt, vanilla)
|
||||
// implements the same trait so the UI can treat them uniformly: pick game version,
|
||||
// pick loader version, install. the actual installation strategies differ wildly
|
||||
// though (fabric/quilt just download jars, forge/neoforge run a whole java installer).
|
||||
|
||||
mod fabric;
|
||||
pub mod forge;
|
||||
pub mod maven;
|
||||
@@ -13,7 +8,7 @@ pub mod neoforge;
|
||||
mod quilt;
|
||||
mod vanilla;
|
||||
|
||||
use std::path::Path;
|
||||
use std::{collections::BTreeMap, path::Path};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use thiserror::Error;
|
||||
@@ -47,6 +42,10 @@ pub struct GameVersion {
|
||||
pub stable: bool,
|
||||
}
|
||||
|
||||
#[allow(
|
||||
clippy::double_must_use,
|
||||
reason = "async_trait adds #[must_use] to generated futures"
|
||||
)]
|
||||
#[async_trait]
|
||||
pub trait ModLoaderInstaller: Send + Sync {
|
||||
fn loader_type(&self) -> ModLoader;
|
||||
@@ -68,6 +67,7 @@ pub trait ModLoaderInstaller: Send + Sync {
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), InstallError>;
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn install_with_java(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
@@ -75,16 +75,15 @@ pub trait ModLoaderInstaller: Send + Sync {
|
||||
loader_version: &str,
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
java_path: Option<&str>,
|
||||
_java_path: Option<&str>,
|
||||
_environment: &BTreeMap<String, String>,
|
||||
) -> Result<(), InstallError> {
|
||||
let _ = java_path;
|
||||
self.install(client, game_version, loader_version, instance_dir, meta_dir)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
// writes raw profile JSON bytes to meta_dir/loader-profiles/<filename>.
|
||||
// callers that already have the upstream bytes (fabric/quilt http fetch,
|
||||
// Callers that already have the upstream bytes (fabric/quilt http fetch,
|
||||
// legacy forge versionInfo extract) use this directly to keep the on-disk
|
||||
// file byte-for-byte identical to the source.
|
||||
pub(crate) fn save_profile_bytes(
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// neoforge installation. same java installer dance as forge (they forked from it,
|
||||
// after all), just with different URLs and version naming.
|
||||
|
||||
use std::path::Path;
|
||||
use std::{collections::BTreeMap, path::Path};
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
@@ -48,17 +45,24 @@ impl ModLoaderInstaller for NeoForgeInstaller {
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), InstallError> {
|
||||
let settings = crate::config::SETTINGS.read().clone();
|
||||
let environment = crate::instance::java::merge_environment(
|
||||
&settings.defaults.environment,
|
||||
&Default::default(),
|
||||
);
|
||||
self.install_with_java(
|
||||
client,
|
||||
game_version,
|
||||
loader_version,
|
||||
instance_dir,
|
||||
meta_dir,
|
||||
None,
|
||||
settings.paths.effective_java_path(),
|
||||
&environment,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn install_with_java(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
@@ -67,6 +71,7 @@ impl ModLoaderInstaller for NeoForgeInstaller {
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
java_path: Option<&str>,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> Result<(), InstallError> {
|
||||
let installer_jar = instance_dir
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
@@ -76,16 +81,9 @@ impl ModLoaderInstaller for NeoForgeInstaller {
|
||||
|
||||
neoforge_api::download_neoforge_installer(client, loader_version, &installer_jar).await?;
|
||||
|
||||
let java_path = java_path.map(str::to_owned).unwrap_or_else(|| {
|
||||
crate::config::SETTINGS
|
||||
.read()
|
||||
.paths
|
||||
.effective_java_path()
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(crate::instance::java::detect_java_path)
|
||||
});
|
||||
tracing::debug!("Running NeoForge installer with Java {}", java_path);
|
||||
if let Err(e) = run_neoforge_installer(&installer_jar, instance_dir, &java_path).await {
|
||||
if let Err(e) =
|
||||
run_neoforge_installer(&installer_jar, instance_dir, java_path, environment).await
|
||||
{
|
||||
let _ = tokio::fs::remove_file(&installer_jar).await;
|
||||
return Err(InstallError::Installer(e));
|
||||
}
|
||||
@@ -105,20 +103,27 @@ impl ModLoaderInstaller for NeoForgeInstaller {
|
||||
pub async fn run_neoforge_installer(
|
||||
installer_path: &Path,
|
||||
instance_dir: &Path,
|
||||
java_path: &str,
|
||||
java_path: Option<&str>,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> Result<(), InstallerError> {
|
||||
use tokio::process::Command;
|
||||
|
||||
set_action("Running NeoForge installer...");
|
||||
let minecraft_dir = std::path::absolute(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME))?;
|
||||
let java_path =
|
||||
crate::instance::java::resolve_java_path_in(java_path, &minecraft_dir, environment);
|
||||
tracing::debug!("Running NeoForge installer with Java {}", java_path);
|
||||
|
||||
let output = match Command::new(java_path)
|
||||
.arg(format!("-Duser.home={}", instance_dir.display()))
|
||||
.arg("-jar")
|
||||
.arg(installer_path)
|
||||
.arg("--installClient")
|
||||
.current_dir(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME))
|
||||
.output()
|
||||
.await
|
||||
let output = match crate::instance::process::output(
|
||||
Command::new(&java_path)
|
||||
.arg("-jar")
|
||||
.arg(std::path::absolute(installer_path)?)
|
||||
.arg("--installClient")
|
||||
.arg(&minecraft_dir)
|
||||
.current_dir(&minecraft_dir)
|
||||
.envs(environment),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// quilt installation. same clean approach as fabric (profile json + library
|
||||
// downloads). they're basically fabric's cooler sibling.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// vanilla "installer". doesn't actually install anything since the launch
|
||||
// process already handles downloading vanilla assets/libraries. this just
|
||||
// exists so vanilla fits the same ModLoaderInstaller trait as everyone else.
|
||||
// InstanceManager prepares vanilla artifacts; this implements the shared loader contract.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// per-launch log files stored under minecraft/logs/launches/
|
||||
// each launch gets its own timestamped file so you can go back and see what
|
||||
// crashed last tuesday at 3am
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// in-memory ring buffer for stdout/stderr from running mc instances.
|
||||
// capped at 2000 lines per instance so it doesn't eat all the RAM
|
||||
// if someone leaves a server running for a week. you're welcome.
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
+262
-46
@@ -1,10 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// CRUD for instances: create, delete, rename, load, save.
|
||||
// creation is the heavy one since it downloads the game, assets, and libraries.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use chrono::Utc;
|
||||
use thiserror::Error;
|
||||
@@ -19,6 +16,8 @@ pub enum InstanceError {
|
||||
AlreadyExists(String),
|
||||
#[error("Instance '{0}' not found")]
|
||||
NotFound(String),
|
||||
#[error("Stop instance '{0}' before renaming or deleting it")]
|
||||
InstanceRunning(String),
|
||||
#[error("IO error: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("JSON error: {0}")]
|
||||
@@ -63,7 +62,6 @@ impl InstanceManager {
|
||||
validate_name(name)?;
|
||||
|
||||
let instance_dir = self.instances_dir.join(name);
|
||||
let instance_json = instance_dir.join("instance.json");
|
||||
tracing::info!(
|
||||
"Creating instance '{}' (Minecraft {}, loader {}, loader_version={})",
|
||||
name,
|
||||
@@ -73,32 +71,28 @@ impl InstanceManager {
|
||||
);
|
||||
tracing::debug!("Instance directory: {}", instance_dir.display());
|
||||
|
||||
if instance_json.exists() {
|
||||
if instance_dir.exists() {
|
||||
tracing::warn!(
|
||||
"Cannot create instance '{}': {} already exists",
|
||||
name,
|
||||
instance_json.display()
|
||||
instance_dir.display()
|
||||
);
|
||||
return Err(InstanceError::AlreadyExists(name.to_string()));
|
||||
}
|
||||
|
||||
// leftover directory without config = botched previous creation, nuke it
|
||||
if instance_dir.exists() && !instance_json.exists() {
|
||||
tracing::warn!(
|
||||
"Removing incomplete instance directory before recreating '{}': {}",
|
||||
name,
|
||||
instance_dir.display()
|
||||
);
|
||||
std::fs::remove_dir_all(&instance_dir)?;
|
||||
std::fs::create_dir_all(&self.instances_dir)?;
|
||||
match std::fs::create_dir(&instance_dir) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
|
||||
return Err(InstanceError::AlreadyExists(name.to_owned()));
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
|
||||
std::fs::create_dir_all(&instance_dir)?;
|
||||
|
||||
let result = self
|
||||
.create_inner(name, game_version, loader, loader_version, &instance_dir)
|
||||
.await;
|
||||
|
||||
// clean up on failure so there's no half-baked instance left around
|
||||
if result.is_err() {
|
||||
tracing::debug!(
|
||||
"Cleaning up incomplete instance '{}' after creation failed",
|
||||
@@ -129,7 +123,13 @@ impl InstanceManager {
|
||||
loader_version: Option<&str>,
|
||||
instance_dir: &std::path::Path,
|
||||
) -> Result<InstanceConfig, InstanceError> {
|
||||
let settings = crate::config::SETTINGS.read().clone();
|
||||
let instance_dir = std::path::absolute(instance_dir)?;
|
||||
let minecraft_dir = instance_dir.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||
let environment = crate::instance::java::merge_environment(
|
||||
&settings.defaults.environment,
|
||||
&Default::default(),
|
||||
);
|
||||
tracing::debug!(
|
||||
"Preparing Minecraft directory for '{}': {}",
|
||||
name,
|
||||
@@ -140,6 +140,11 @@ impl InstanceManager {
|
||||
std::fs::create_dir_all(&path)?;
|
||||
tracing::trace!("Ensured instance subdirectory {}", path.display());
|
||||
}
|
||||
let java_path = crate::instance::java::resolve_java_path_in(
|
||||
settings.paths.effective_java_path(),
|
||||
&minecraft_dir,
|
||||
&environment,
|
||||
);
|
||||
|
||||
// forge insists on this file existing, even if it's empty json. thanks forge.
|
||||
let launcher_profiles_path = minecraft_dir.join("launcher_profiles.json");
|
||||
@@ -209,7 +214,19 @@ impl InstanceManager {
|
||||
crate::storage::write_atomic(&meta_json_path, &raw_meta_bytes)?;
|
||||
tracing::debug!("Saved version meta to {}", meta_json_path.display());
|
||||
|
||||
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?;
|
||||
let runtime = crate::instance::java::probe_java_in(
|
||||
Path::new(&java_path),
|
||||
&minecraft_dir,
|
||||
&environment,
|
||||
)
|
||||
.await?;
|
||||
crate::net::mojang::download_libraries_for_platform(
|
||||
&self.client,
|
||||
&version_meta,
|
||||
&self.meta_dir,
|
||||
&runtime.platform,
|
||||
)
|
||||
.await?;
|
||||
|
||||
crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await?;
|
||||
|
||||
@@ -231,12 +248,14 @@ impl InstanceManager {
|
||||
name
|
||||
);
|
||||
installer
|
||||
.install(
|
||||
.install_with_java(
|
||||
&self.client,
|
||||
game_version,
|
||||
effective_loader_version,
|
||||
instance_dir,
|
||||
&instance_dir,
|
||||
&self.meta_dir,
|
||||
Some(&java_path),
|
||||
&environment,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| match e {
|
||||
@@ -246,7 +265,7 @@ impl InstanceManager {
|
||||
}
|
||||
})?;
|
||||
|
||||
let defaults = crate::config::SETTINGS.read().defaults.clone();
|
||||
let defaults = &settings.defaults;
|
||||
let config = InstanceConfig {
|
||||
name: name.to_string(),
|
||||
game_version: game_version.to_string(),
|
||||
@@ -279,10 +298,24 @@ impl InstanceManager {
|
||||
}
|
||||
|
||||
pub async fn repair_runtime_cache(&self, config: &InstanceConfig) -> Result<(), InstanceError> {
|
||||
let task = crate::feedback::progress::ProgressTask::start(format!(
|
||||
"Rebuilding runtime for '{}'",
|
||||
config.name
|
||||
));
|
||||
validate_name(&config.name)?;
|
||||
let settings = crate::config::SETTINGS.read().clone();
|
||||
let instance_dir = std::path::absolute(self.instances_dir.join(&config.name))?;
|
||||
let minecraft_dir = instance_dir.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||
std::fs::create_dir_all(&minecraft_dir)?;
|
||||
let environment = crate::instance::java::merge_environment(
|
||||
&settings.defaults.environment,
|
||||
&config.environment,
|
||||
);
|
||||
let java_path = crate::instance::java::resolve_java_path_in(
|
||||
config
|
||||
.java_path
|
||||
.as_deref()
|
||||
.or(settings.paths.effective_java_path()),
|
||||
&minecraft_dir,
|
||||
&environment,
|
||||
);
|
||||
let task = crate::feedback::progress::ProgressTask::start("Rebuilding runtime");
|
||||
task.set_sub_action(format!("Minecraft {}", config.game_version));
|
||||
let metadata_paths = crate::storage::MetadataPaths::new(&self.meta_dir);
|
||||
for directory in [
|
||||
@@ -358,7 +391,19 @@ impl InstanceManager {
|
||||
if fetched_meta {
|
||||
crate::storage::write_atomic(&meta_path, &raw_meta)?;
|
||||
}
|
||||
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?;
|
||||
let runtime = crate::instance::java::probe_java_in(
|
||||
Path::new(&java_path),
|
||||
&minecraft_dir,
|
||||
&environment,
|
||||
)
|
||||
.await?;
|
||||
crate::net::mojang::download_libraries_for_platform(
|
||||
&self.client,
|
||||
&version_meta,
|
||||
&self.meta_dir,
|
||||
&runtime.platform,
|
||||
)
|
||||
.await?;
|
||||
crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await?;
|
||||
|
||||
if config.loader != ModLoader::Vanilla {
|
||||
@@ -374,9 +419,10 @@ impl InstanceManager {
|
||||
&self.client,
|
||||
&config.game_version,
|
||||
loader_version,
|
||||
&self.instances_dir.join(&config.name),
|
||||
&instance_dir,
|
||||
&self.meta_dir,
|
||||
config.java_path.as_deref(),
|
||||
Some(&java_path),
|
||||
&environment,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
@@ -413,6 +459,11 @@ impl InstanceManager {
|
||||
|
||||
pub fn delete(&self, name: &str) -> Result<(), InstanceError> {
|
||||
validate_name(name)?;
|
||||
if crate::instance::runtime::is_active(name) {
|
||||
return Err(InstanceError::InstanceRunning(name.to_owned()));
|
||||
}
|
||||
let _lock = crate::instance::runtime::lock_instance(&self.instances_dir, name)?;
|
||||
let _config_lock = self.config_lock(name)?;
|
||||
let instance_dir = self.instances_dir.join(name);
|
||||
if !instance_dir.exists() {
|
||||
tracing::warn!(
|
||||
@@ -439,6 +490,9 @@ impl InstanceManager {
|
||||
|
||||
pub fn rename(&self, old_name: &str, new_name: &str) -> Result<(), InstanceError> {
|
||||
validate_name(old_name)?;
|
||||
if crate::instance::runtime::is_active(old_name) {
|
||||
return Err(InstanceError::InstanceRunning(old_name.to_owned()));
|
||||
}
|
||||
let new_name = new_name.trim();
|
||||
if new_name.is_empty() {
|
||||
tracing::warn!("Cannot rename instance '{}': new name is empty", old_name);
|
||||
@@ -450,10 +504,8 @@ impl InstanceManager {
|
||||
tracing::debug!("Ignoring no-op instance rename '{}'", old_name);
|
||||
return Ok(());
|
||||
}
|
||||
// same path-traversal guards as create: without this, "../x" or ".x"
|
||||
// would move the instance directory out of (or hide it inside) the
|
||||
// instances root.
|
||||
validate_name(new_name)?;
|
||||
let _old_lock = crate::instance::runtime::lock_instance(&self.instances_dir, old_name)?;
|
||||
let old_dir = self.instances_dir.join(old_name);
|
||||
let new_dir = self.instances_dir.join(new_name);
|
||||
if !old_dir.exists() {
|
||||
@@ -464,7 +516,16 @@ impl InstanceManager {
|
||||
);
|
||||
return Err(InstanceError::NotFound(old_name.to_string()));
|
||||
}
|
||||
if new_dir.exists() {
|
||||
let aliases_source = paths_alias(&old_dir, &new_dir)?;
|
||||
let _new_lock = if aliases_source {
|
||||
None
|
||||
} else {
|
||||
Some(crate::instance::runtime::lock_instance(
|
||||
&self.instances_dir,
|
||||
new_name,
|
||||
)?)
|
||||
};
|
||||
if std::fs::symlink_metadata(&new_dir).is_ok() && !aliases_source {
|
||||
tracing::warn!(
|
||||
"Cannot rename instance '{}' to '{}': destination exists at {}",
|
||||
old_name,
|
||||
@@ -473,11 +534,17 @@ impl InstanceManager {
|
||||
);
|
||||
return Err(InstanceError::AlreadyExists(new_name.to_string()));
|
||||
}
|
||||
let _old_config_lock = self.config_lock(old_name)?;
|
||||
let _new_config_lock = if aliases_source {
|
||||
None
|
||||
} else {
|
||||
Some(self.config_lock(new_name)?)
|
||||
};
|
||||
let mut config = self.load_one(old_name)?;
|
||||
config.name = new_name.to_owned();
|
||||
let json = serde_json::to_vec_pretty(&config)?;
|
||||
tracing::info!("Renaming instance '{}' to '{}'", old_name, new_name);
|
||||
if let Err(e) = std::fs::rename(&old_dir, &new_dir) {
|
||||
if let Err(e) = rename_path(&old_dir, &new_dir, aliases_source) {
|
||||
tracing::error!(
|
||||
"Failed to rename instance directory {} to {}: {}",
|
||||
old_dir.display(),
|
||||
@@ -489,7 +556,7 @@ impl InstanceManager {
|
||||
|
||||
let config_path = new_dir.join("instance.json");
|
||||
if let Err(error) = crate::storage::write_atomic(&config_path, &json) {
|
||||
if let Err(rollback_error) = std::fs::rename(&new_dir, &old_dir) {
|
||||
if let Err(rollback_error) = rename_path(&new_dir, &old_dir, aliases_source) {
|
||||
tracing::error!(
|
||||
"Failed to roll back instance rename from {} to {}: {}",
|
||||
new_dir.display(),
|
||||
@@ -528,6 +595,12 @@ impl InstanceManager {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Some(directory_name) = entry.file_name().to_str().map(str::to_owned) else {
|
||||
continue;
|
||||
};
|
||||
if validate_name(&directory_name).is_err() {
|
||||
continue;
|
||||
}
|
||||
let config_path = entry.path().join("instance.json");
|
||||
if !config_path.exists() {
|
||||
tracing::trace!("Skipping non-instance directory {}", entry.path().display());
|
||||
@@ -541,7 +614,10 @@ impl InstanceManager {
|
||||
}
|
||||
};
|
||||
match serde_json::from_str::<InstanceConfig>(&contents) {
|
||||
Ok(config) => instances.push(config),
|
||||
Ok(mut config) => {
|
||||
config.name = directory_name;
|
||||
instances.push(config);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to parse {}: {}", config_path.display(), e);
|
||||
}
|
||||
@@ -578,7 +654,10 @@ impl InstanceManager {
|
||||
}
|
||||
};
|
||||
match serde_json::from_str::<InstanceConfig>(&contents) {
|
||||
Ok(config) => Ok(config),
|
||||
Ok(mut config) => {
|
||||
config.name = name.to_owned();
|
||||
Ok(config)
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
"Failed to parse instance '{}' config {}: {}",
|
||||
@@ -592,6 +671,47 @@ impl InstanceManager {
|
||||
}
|
||||
|
||||
pub fn save(&self, instance: &InstanceConfig) -> Result<(), InstanceError> {
|
||||
let _lock = self.config_lock(&instance.name)?;
|
||||
let mut instance = instance.clone();
|
||||
match self.load_one(&instance.name) {
|
||||
Ok(current) => {
|
||||
instance.last_played = instance.last_played.max(current.last_played);
|
||||
// Selection changes must commit with their corresponding filesystem payload.
|
||||
instance.config_sync_profile = current.config_sync_profile;
|
||||
}
|
||||
Err(InstanceError::NotFound(_)) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
self.save_unlocked(&instance)
|
||||
}
|
||||
|
||||
pub(crate) fn save_config_sync_profile(
|
||||
&self,
|
||||
name: &str,
|
||||
profile: Option<String>,
|
||||
) -> Result<InstanceConfig, InstanceError> {
|
||||
let _lock = self.config_lock(name)?;
|
||||
let mut config = self.load_one(name)?;
|
||||
config.config_sync_profile = profile;
|
||||
self.save_unlocked(&config)?;
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
pub(crate) fn config_lock(&self, name: &str) -> Result<std::fs::File, InstanceError> {
|
||||
validate_name(name)?;
|
||||
// the lock must survive replacing or renaming the instance directory.
|
||||
std::fs::create_dir_all(&self.instances_dir)?;
|
||||
let path = self.instances_dir.join(format!(".rmcl-config-{name}.lock"));
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.write(true)
|
||||
.open(path)?;
|
||||
file.lock()?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
fn save_unlocked(&self, instance: &InstanceConfig) -> Result<(), InstanceError> {
|
||||
validate_name(&instance.name)?;
|
||||
let instance_dir = self.instances_dir.join(&instance.name);
|
||||
if !instance_dir.is_dir() {
|
||||
@@ -609,34 +729,130 @@ impl InstanceManager {
|
||||
}
|
||||
|
||||
pub fn touch_last_played(&self, name: &str) -> Result<(), InstanceError> {
|
||||
let _lock = self.config_lock(name)?;
|
||||
let mut config = self.load_one(name)?;
|
||||
config.last_played = Some(chrono::Utc::now());
|
||||
tracing::debug!("Updating last_played for '{}'", name);
|
||||
self.save(&config)
|
||||
self.save_unlocked(&config)
|
||||
}
|
||||
}
|
||||
|
||||
// guard against path traversal and other filesystem shenanigans
|
||||
fn validate_name(name: &str) -> Result<(), InstanceError> {
|
||||
pub(crate) fn validate_name(name: &str) -> Result<(), InstanceError> {
|
||||
if name.is_empty() || name.len() > 64 {
|
||||
return Err(InstanceError::InvalidName(format!(
|
||||
"Name must be 1-64 chars, got: {:?}",
|
||||
name
|
||||
)));
|
||||
}
|
||||
if name.contains('/')
|
||||
|| name.contains('\\')
|
||||
|| name.starts_with('.')
|
||||
|| name.chars().any(char::is_control)
|
||||
{
|
||||
if name.starts_with('.') || !portable_component(name) {
|
||||
return Err(InstanceError::InvalidName(format!(
|
||||
"Name contains invalid characters: {:?}",
|
||||
"Name contains invalid characters or is reserved: {:?}",
|
||||
name
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn portable_component(name: &str) -> bool {
|
||||
if name.is_empty()
|
||||
|| name.ends_with([' ', '.'])
|
||||
|| name.chars().any(|c| {
|
||||
c.is_control() || matches!(c, '/' | '\\' | ':' | '<' | '>' | '"' | '|' | '?' | '*')
|
||||
})
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let stem = name
|
||||
.split('.')
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.trim_end_matches(' ')
|
||||
.to_ascii_uppercase();
|
||||
!matches!(
|
||||
stem.as_str(),
|
||||
"CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$"
|
||||
) && !["COM", "LPT"].into_iter().any(|prefix| {
|
||||
stem.strip_prefix(prefix).is_some_and(|suffix| {
|
||||
matches!(
|
||||
suffix,
|
||||
"1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn paths_alias(left: &Path, right: &Path) -> std::io::Result<bool> {
|
||||
if left.parent() != right.parent() {
|
||||
return Ok(false);
|
||||
}
|
||||
let right_metadata = match std::fs::symlink_metadata(right) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let left_metadata = std::fs::symlink_metadata(left)?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
if left_metadata.dev() != right_metadata.dev()
|
||||
|| left_metadata.ino() != right_metadata.ino()
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
// Distinct hard links are not aliases of the same directory entry.
|
||||
if left.file_name() != right.file_name() {
|
||||
let mut left_entry = false;
|
||||
let mut right_entry = false;
|
||||
for entry in std::fs::read_dir(
|
||||
left.parent()
|
||||
.ok_or_else(|| std::io::Error::other("Path has no parent"))?,
|
||||
)? {
|
||||
let name = entry?.file_name();
|
||||
left_entry |= Some(name.as_os_str()) == left.file_name();
|
||||
right_entry |= Some(name.as_os_str()) == right.file_name();
|
||||
}
|
||||
if left_entry && right_entry {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
if left_metadata.file_type().is_symlink() || right_metadata.file_type().is_symlink() {
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(std::fs::canonicalize(left)? == std::fs::canonicalize(right)?)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn rename_path(from: &Path, to: &Path, aliases_source: bool) -> std::io::Result<()> {
|
||||
if !aliases_source {
|
||||
return std::fs::rename(from, to);
|
||||
}
|
||||
let temporary = tempfile::Builder::new()
|
||||
.prefix(".rmcl-rename-")
|
||||
.tempdir_in(
|
||||
from.parent()
|
||||
.ok_or_else(|| std::io::Error::other("Path has no parent"))?,
|
||||
)?;
|
||||
let staged = temporary.path().join("original");
|
||||
std::fs::rename(from, &staged)?;
|
||||
if let Err(error) = std::fs::rename(&staged, to) {
|
||||
if let Err(rollback) = std::fs::rename(&staged, from) {
|
||||
let retained = temporary.keep();
|
||||
return Err(std::io::Error::other(format!(
|
||||
"Could not rename '{}' to '{}': {error}; rollback failed: {rollback}; original retained at '{}'",
|
||||
from.display(),
|
||||
to.display(),
|
||||
retained.join("original").display(),
|
||||
)));
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests/manager.rs"]
|
||||
mod tests;
|
||||
+4
-3
@@ -1,12 +1,11 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// instance management: creation, launching, importing modpacks, and all the
|
||||
// bookkeeping that comes with pretending to be a real launcher
|
||||
|
||||
pub mod config_sync;
|
||||
pub mod content;
|
||||
pub mod desktop;
|
||||
pub mod export;
|
||||
pub(crate) mod glfw;
|
||||
pub mod import;
|
||||
pub mod java;
|
||||
pub mod launch;
|
||||
@@ -14,6 +13,8 @@ pub mod loader;
|
||||
pub mod logs;
|
||||
pub mod manager;
|
||||
pub mod models;
|
||||
pub mod pack;
|
||||
mod process;
|
||||
pub mod runtime;
|
||||
pub mod screenshots;
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// core data types for an instance: what loader it uses, what version, memory
|
||||
// settings, etc. this is what gets persisted to instance.json
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum PackFormat {
|
||||
CurseForge,
|
||||
Mrpack,
|
||||
Mmc,
|
||||
}
|
||||
|
||||
impl PackFormat {
|
||||
pub const ALL: [Self; 3] = [Self::CurseForge, Self::Mrpack, Self::Mmc];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::CurseForge => "CurseForge",
|
||||
Self::Mrpack => "Modrinth",
|
||||
Self::Mmc => "MultiMC/Prism",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn extension(self) -> &'static str {
|
||||
match self {
|
||||
Self::Mrpack => "mrpack",
|
||||
Self::CurseForge | Self::Mmc => "zip",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::io;
|
||||
use tokio::process::{Child, Command};
|
||||
|
||||
/// Own descendants until completion or cancellation.
|
||||
pub(super) fn spawn_owned(command: &mut Command) -> io::Result<(Child, ProcessTree)> {
|
||||
command.kill_on_drop(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
command.process_group(0);
|
||||
let child = command.spawn()?;
|
||||
let tree = ProcessTree(Some(
|
||||
child.id().expect("newly spawned child has an ID") as i32
|
||||
));
|
||||
Ok((child, tree))
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
windows::spawn(command)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn output(command: &mut Command) -> io::Result<std::process::Output> {
|
||||
command
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped());
|
||||
let (child, _tree) = spawn_owned(command)?;
|
||||
child.wait_with_output().await
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(super) struct ProcessTree(Option<i32>);
|
||||
|
||||
#[cfg(unix)]
|
||||
impl ProcessTree {
|
||||
pub(super) fn detach(mut self) -> io::Result<()> {
|
||||
self.0 = None;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl Drop for ProcessTree {
|
||||
fn drop(&mut self) {
|
||||
let Some(group) = self.0 else {
|
||||
return;
|
||||
};
|
||||
// SAFETY: a negative PID addresses only the group created for this command.
|
||||
if unsafe { libc::kill(-group, libc::SIGKILL) } == -1 {
|
||||
let error = io::Error::last_os_error();
|
||||
if error.raw_os_error() != Some(libc::ESRCH) {
|
||||
tracing::warn!("Failed to terminate process group {group}: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(super) struct ProcessTree {
|
||||
_job: std::os::windows::io::OwnedHandle,
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl ProcessTree {
|
||||
pub(super) fn detach(self) -> io::Result<()> {
|
||||
windows::set_kill_on_close(&self._job, false)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows {
|
||||
use super::*;
|
||||
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{HANDLE, INVALID_HANDLE_VALUE},
|
||||
System::{
|
||||
Diagnostics::ToolHelp::{
|
||||
CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First,
|
||||
Thread32Next,
|
||||
},
|
||||
JobObjects::{
|
||||
AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
|
||||
JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
|
||||
SetInformationJobObject,
|
||||
},
|
||||
Threading::{CREATE_SUSPENDED, OpenThread, ResumeThread, THREAD_SUSPEND_RESUME},
|
||||
},
|
||||
};
|
||||
|
||||
fn own_handle(handle: HANDLE) -> io::Result<OwnedHandle> {
|
||||
if handle.is_null() || handle == INVALID_HANDLE_VALUE {
|
||||
Err(io::Error::last_os_error())
|
||||
} else {
|
||||
// SAFETY: these APIs return a new handle owned by the caller.
|
||||
Ok(unsafe { OwnedHandle::from_raw_handle(handle) })
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn set_kill_on_close(job: &OwnedHandle, kill: bool) -> io::Result<()> {
|
||||
let limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
|
||||
BasicLimitInformation:
|
||||
windows_sys::Win32::System::JobObjects::JOBOBJECT_BASIC_LIMIT_INFORMATION {
|
||||
LimitFlags: if kill {
|
||||
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
} else {
|
||||
0
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: the buffer has the required size and lives through the call.
|
||||
if unsafe {
|
||||
SetInformationJobObject(
|
||||
job.as_raw_handle(),
|
||||
JobObjectExtendedLimitInformation,
|
||||
(&limits as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),
|
||||
std::mem::size_of_val(&limits) as u32,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn spawn(command: &mut Command) -> io::Result<(Child, ProcessTree)> {
|
||||
// SAFETY: null security/name pointers request a private, unnamed job.
|
||||
let job = own_handle(unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) })?;
|
||||
set_kill_on_close(&job, true)?;
|
||||
// Suspend before job assignment so the shell cannot spawn unowned children.
|
||||
command.creation_flags(CREATE_SUSPENDED);
|
||||
let child = command.spawn()?;
|
||||
let process = child
|
||||
.raw_handle()
|
||||
.ok_or_else(|| io::Error::other("Process handle is unavailable"))?;
|
||||
// SAFETY: both handles are live and the child has not started running.
|
||||
if unsafe { AssignProcessToJobObject(job.as_raw_handle(), process) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let tree = ProcessTree { _job: job };
|
||||
resume_main_thread(child.id().expect("newly spawned child has an ID"))?;
|
||||
Ok((child, tree))
|
||||
}
|
||||
|
||||
// Tokio retains the process handle but not the primary thread handle.
|
||||
fn resume_main_thread(pid: u32) -> io::Result<()> {
|
||||
// SAFETY: the snapshot and entry buffer are owned here.
|
||||
let snapshot = own_handle(unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) })?;
|
||||
let mut entry = THREADENTRY32 {
|
||||
dwSize: std::mem::size_of::<THREADENTRY32>() as u32,
|
||||
..Default::default()
|
||||
};
|
||||
let mut found = unsafe { Thread32First(snapshot.as_raw_handle(), &mut entry) };
|
||||
while found != 0 {
|
||||
if entry.th32OwnerProcessID == pid {
|
||||
// A suspended, newly-created process has only its primary thread.
|
||||
let thread = own_handle(unsafe {
|
||||
OpenThread(THREAD_SUSPEND_RESUME, 0, entry.th32ThreadID)
|
||||
})?;
|
||||
if unsafe { ResumeThread(thread.as_raw_handle()) } == u32::MAX {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
found = unsafe { Thread32Next(snapshot.as_raw_handle(), &mut entry) };
|
||||
}
|
||||
Err(io::Error::other(format!(
|
||||
"Cannot find the primary thread of process {pid}"
|
||||
)))
|
||||
}
|
||||
}
|
||||
Loaded 100 of 241 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user