Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ad7cfb757 | ||
|
|
6cd81962b3 | ||
|
|
eed614fd67 | ||
|
|
85227bd31f | ||
|
|
da4a66850d | ||
|
|
a839925041 | ||
|
|
16e2f3204d | ||
|
|
70286ed9b8 | ||
|
|
59707b77d2 | ||
|
|
63b4adaca8 | ||
|
|
ae7a2de19d | ||
|
|
2d0007de52 | ||
|
|
e9ad30dc29 | ||
|
|
bfd8be6abe | ||
|
|
ed7387beb3 | ||
|
|
7d382aade9 | ||
|
|
e09e5a0168 | ||
|
|
bbf0317775 | ||
|
|
aa03dac34d | ||
|
|
062a9234ee | ||
|
|
695ba5a758 | ||
|
|
f049904466 | ||
|
|
d001ab8d0a | ||
|
|
d488954548 | ||
|
|
bf2957e75b | ||
|
|
2f982435f9 | ||
|
|
95a25836a0 | ||
|
|
fb976f1cb9 | ||
|
|
30a9f60830 | ||
|
|
37cccc352b | ||
|
|
52f074ce46 | ||
|
|
94b71fdc4e | ||
|
|
7986bab3a7 | ||
|
|
a98426e22a | ||
|
|
3192851556 | ||
|
|
3bee6d8338 | ||
|
|
ea7478eb27 | ||
|
|
4eed312c3d | ||
|
|
aefc4535e1 | ||
|
|
8f920080d1 | ||
|
|
7d904ccdfa | ||
|
|
12074f63d5 | ||
|
|
3b26581af5 | ||
|
|
de6defa1ff | ||
|
|
cccf65981a | ||
|
|
315567a79c | ||
|
|
bd1a1f910d | ||
|
|
6527b24081 | ||
|
|
992f15b082 | ||
|
|
6e898b8c45 | ||
|
|
b3c17b58c9 | ||
|
|
9c9c6d9976 | ||
|
|
c1af0f1b51 | ||
|
|
5e3699b64d | ||
|
|
1fa9aee3f0 | ||
|
|
d79843c54b | ||
|
|
3077fb9b35 | ||
|
|
7839602bcc | ||
|
|
b10e88c304 | ||
|
|
2aa45fe15a | ||
|
|
257cec9f41 | ||
|
|
e14075ad8d | ||
|
|
1742f62cd0 | ||
|
|
22d5da9f0d | ||
|
|
07212aa130 | ||
|
|
e95f544948 | ||
|
|
feeb3e6d50 | ||
|
|
c6205a337c | ||
|
|
15d76c18a0 | ||
|
|
078afe4b9d | ||
|
|
dc13746841 | ||
|
|
45ce7ef84b | ||
|
|
64bb5e2d16 | ||
|
|
9b17ec96c5 | ||
|
|
e21f68fd7c | ||
|
|
9a390fd7a4 | ||
|
|
1de0c7e139 | ||
|
|
d123bb5c19 | ||
|
|
798c323a82 | ||
|
|
aac3f47f6c | ||
|
|
6f0825c321 | ||
|
|
6138e248cb | ||
|
|
868f3e5b9d | ||
|
|
0d7903fc06 | ||
|
|
72b8b19f52 | ||
|
|
23c138dc32 | ||
|
|
e0fb34e876 | ||
|
|
4f5141760a | ||
|
|
6a0f8978b7 | ||
|
|
a7e4f30a8a | ||
|
|
18581fea34 | ||
|
|
aaa9224c7c | ||
|
|
77980dbb4d | ||
|
|
130661f144 | ||
|
|
f26a3542b9 | ||
|
|
32a5868894 | ||
|
|
0a930a4f86 | ||
|
|
c59228e1fd | ||
|
|
8a2a562235 | ||
|
|
fbf8142ea0 | ||
|
|
a05b030862 | ||
|
|
725b52579b | ||
|
|
19c47cdf7b | ||
|
|
774a6c6723 | ||
|
|
ddfe0e26b2 | ||
|
|
5feb656e9a | ||
|
|
39400d3149 | ||
|
|
803ac58f4d | ||
|
|
c4dd8488fe | ||
|
|
6dda8dc410 | ||
|
|
b4d03e7212 | ||
|
|
c792e1cc11 | ||
|
|
d10be1676e | ||
|
|
b94957a952 | ||
|
|
6f5722aa02 | ||
|
|
4bf43a438b | ||
|
|
b372571648 | ||
|
|
b5d98e5e8a | ||
|
|
7e5ff7f75f | ||
|
|
099d96bcca | ||
|
|
4ba9c65f73 | ||
|
|
be01370ab2 | ||
|
|
4ddb8f49bb | ||
|
|
4576da4551 | ||
|
|
269814945d | ||
|
|
69549b7152 | ||
|
|
8f16931502 | ||
|
|
a95250cf9a | ||
|
|
2adfd0afbd | ||
|
|
3ab6adf700 | ||
|
|
7c59758f5f | ||
|
|
63d7ef0fa1 | ||
|
|
68d2f45236 | ||
|
|
3dd384c5c6 | ||
|
|
c5da2c7c99 | ||
|
|
1fd1b4e09d | ||
|
|
0d9cd9c6b8 | ||
|
|
09f403aa07 | ||
|
|
3d7f233e27 | ||
|
|
db23b86dca | ||
|
|
09bc8f26fb | ||
|
|
a58e6fb76d | ||
|
|
7723716e18 | ||
|
|
29280e9f8d | ||
|
|
e7e033715e | ||
|
|
4c22381675 | ||
|
|
e809fac364 | ||
|
|
bf95404920 | ||
|
|
4197beea3c | ||
|
|
10bfe8ad2f | ||
|
|
58cbeb3ba0 | ||
|
|
8b15dbcda5 | ||
|
|
595af32e54 | ||
|
|
c6c774b1e3 | ||
|
|
5f43128a80 | ||
|
|
0eb47fd7b4 | ||
|
|
0d1b7984fc | ||
|
|
d612f83446 | ||
|
|
8d7a0903fd | ||
|
|
41d6da8008 | ||
|
|
6ac9f4e239 | ||
|
|
1f1a0ebb3d | ||
|
|
623acd9e2c | ||
|
|
7a9dfa850d | ||
|
|
d2e08d818b | ||
|
|
cc0dde106a | ||
|
|
c6fce8592a | ||
|
|
2163fef175 | ||
|
|
05bea59ef1 | ||
|
|
63fb96a0d2 | ||
|
|
c15cb9a378 | ||
|
|
961983d1fe | ||
|
|
aeeef26614 | ||
|
|
efcef1cab4 | ||
|
|
f45351841c | ||
|
|
d88ab085b5 | ||
|
|
363ada8211 | ||
|
|
412e6ff91a | ||
|
|
19887643bc | ||
|
|
a7b378b17d | ||
|
|
8d2b5b9832 | ||
|
|
0d00678a7c | ||
|
|
63014726e9 | ||
|
|
2029005c78 | ||
|
|
22e4481a2b | ||
|
|
50e31f38bb | ||
|
|
2cc0173873 | ||
|
|
681f7974d6 | ||
|
|
a54e53038a | ||
|
|
17bb771020 | ||
|
|
c3ea0bc592 |
No files matched your search
@@ -0,0 +1,428 @@
|
|||||||
|
# cargo-dist artifact building and publishing, called by release.yml.
|
||||||
|
# Based on cargo-dist's generated GitHub workflow.
|
||||||
|
|
||||||
|
name: build release
|
||||||
|
permissions:
|
||||||
|
"contents": "write"
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
tag:
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
# Run 'dist plan' (or host) to determine what tasks we need to do
|
||||||
|
plan:
|
||||||
|
runs-on: "ubuntu-22.04"
|
||||||
|
outputs:
|
||||||
|
val: ${{ steps.plan.outputs.manifest }}
|
||||||
|
tag: ${{ inputs.tag }}
|
||||||
|
tag-flag: ${{ format('--tag={0}', inputs.tag) }}
|
||||||
|
publishing: true
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
ref: ${{ inputs.tag }}
|
||||||
|
persist-credentials: false
|
||||||
|
submodules: recursive
|
||||||
|
- name: Install dist
|
||||||
|
# we specify bash to get pipefail; it guards against the `curl` command
|
||||||
|
# failing. otherwise `sh` won't catch that `curl` returned non-0
|
||||||
|
shell: bash
|
||||||
|
run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.31.0/cargo-dist-installer.sh | sh"
|
||||||
|
- name: Cache dist
|
||||||
|
uses: actions/upload-artifact@v6
|
||||||
|
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
|
||||||
|
echo "dist ran successfully"
|
||||||
|
cat plan-dist-manifest.json
|
||||||
|
echo "manifest=$(jq -c "." plan-dist-manifest.json)" >> "$GITHUB_OUTPUT"
|
||||||
|
- name: "Upload dist-manifest.json"
|
||||||
|
uses: actions/upload-artifact@v6
|
||||||
|
with:
|
||||||
|
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 }}
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
CURSEFORGE_API_KEY: ${{ secrets.CURSEFORGE_API_KEY }}
|
||||||
|
BUILD_MANIFEST_NAME: target/distrib/${{ join(matrix.targets, '-') }}-dist-manifest.json
|
||||||
|
steps:
|
||||||
|
- name: enable windows longpaths
|
||||||
|
run: |
|
||||||
|
git config --global core.longpaths true
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
ref: ${{ inputs.tag }}
|
||||||
|
persist-credentials: false
|
||||||
|
submodules: recursive
|
||||||
|
- name: Install Rust non-interactively if not already installed
|
||||||
|
if: ${{ matrix.container }}
|
||||||
|
run: |
|
||||||
|
if ! command -v cargo > /dev/null 2>&1; then
|
||||||
|
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
|
||||||
|
echo "$HOME/.cargo/bin" >> $GITHUB_PATH
|
||||||
|
fi
|
||||||
|
- name: "install JDK"
|
||||||
|
uses: "actions/setup-java@v5"
|
||||||
|
with:
|
||||||
|
"distribution": "temurin"
|
||||||
|
"java-version": "21"
|
||||||
|
- name: Install dist
|
||||||
|
run: ${{ matrix.install_dist.run }}
|
||||||
|
# Get the dist-manifest
|
||||||
|
- name: Fetch local artifacts
|
||||||
|
uses: actions/download-artifact@v7
|
||||||
|
with:
|
||||||
|
pattern: artifacts-*
|
||||||
|
path: target/distrib/
|
||||||
|
merge-multiple: true
|
||||||
|
- name: Install dependencies
|
||||||
|
run: |
|
||||||
|
${{ 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
|
||||||
|
name: Post-build
|
||||||
|
# We force bash here just because github makes it really hard to get values up
|
||||||
|
# to "real" actions without writing to env-vars, and writing to env-vars has
|
||||||
|
# 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"
|
||||||
|
|
||||||
|
cp dist-manifest.json "$BUILD_MANIFEST_NAME"
|
||||||
|
- name: "Upload artifacts"
|
||||||
|
uses: actions/upload-artifact@v6
|
||||||
|
with:
|
||||||
|
name: artifacts-build-local-${{ join(matrix.targets, '_') }}
|
||||||
|
path: |
|
||||||
|
${{ steps.cargo-dist.outputs.paths }}
|
||||||
|
${{ env.BUILD_MANIFEST_NAME }}
|
||||||
|
|
||||||
|
# Build and package all the platform-agnostic(ish) things
|
||||||
|
build-global-artifacts:
|
||||||
|
needs:
|
||||||
|
- plan
|
||||||
|
- build-local-artifacts
|
||||||
|
runs-on: "ubuntu-22.04"
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
BUILD_MANIFEST_NAME: target/distrib/global-dist-manifest.json
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
ref: ${{ inputs.tag }}
|
||||||
|
persist-credentials: false
|
||||||
|
submodules: recursive
|
||||||
|
- name: Install cached dist
|
||||||
|
uses: actions/download-artifact@v7
|
||||||
|
with:
|
||||||
|
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:
|
||||||
|
pattern: artifacts-*
|
||||||
|
path: target/distrib/
|
||||||
|
merge-multiple: true
|
||||||
|
- id: cargo-dist
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
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"
|
||||||
|
|
||||||
|
cp dist-manifest.json "$BUILD_MANIFEST_NAME"
|
||||||
|
- name: "Upload artifacts"
|
||||||
|
uses: actions/upload-artifact@v6
|
||||||
|
with:
|
||||||
|
name: artifacts-build-global
|
||||||
|
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 }}
|
||||||
|
runs-on: "ubuntu-22.04"
|
||||||
|
outputs:
|
||||||
|
val: ${{ steps.host.outputs.manifest }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
ref: ${{ inputs.tag }}
|
||||||
|
persist-credentials: false
|
||||||
|
submodules: recursive
|
||||||
|
fetch-depth: 0
|
||||||
|
fetch-tags: true
|
||||||
|
- name: Install cached dist
|
||||||
|
uses: actions/download-artifact@v7
|
||||||
|
with:
|
||||||
|
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:
|
||||||
|
pattern: artifacts-*
|
||||||
|
path: target/distrib/
|
||||||
|
merge-multiple: true
|
||||||
|
- id: host
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
dist host ${{ needs.plan.outputs.tag-flag }} --steps=upload --steps=release --output-format=json > dist-manifest.json
|
||||||
|
echo "artifacts uploaded and released successfully"
|
||||||
|
cat dist-manifest.json
|
||||||
|
echo "manifest=$(jq -c "." dist-manifest.json)" >> "$GITHUB_OUTPUT"
|
||||||
|
- 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:
|
||||||
|
pattern: artifacts-*
|
||||||
|
path: artifacts
|
||||||
|
merge-multiple: true
|
||||||
|
- name: Cleanup
|
||||||
|
run: |
|
||||||
|
# Remove internal cargo-dist manifests from the public GitHub Release.
|
||||||
|
rm -f artifacts/*-dist-manifest.json artifacts/dist-manifest.json
|
||||||
|
- name: Generate changelog
|
||||||
|
id: changelog
|
||||||
|
uses: orhun/git-cliff-action@v4
|
||||||
|
with:
|
||||||
|
args: --latest --strip header
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
- name: Create GitHub Release
|
||||||
|
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 }}"
|
||||||
|
run: |
|
||||||
|
echo "$CHANGELOG" > $RUNNER_TEMP/notes.txt
|
||||||
|
cat >> $RUNNER_TEMP/notes.txt <<EOF
|
||||||
|
|
||||||
|
## downloads
|
||||||
|
|
||||||
|
| File | Platform | Checksum |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| [rmcl-aarch64-apple-darwin.tar.xz](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-aarch64-apple-darwin.tar.xz) | Apple Silicon macOS | [checksum](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-aarch64-apple-darwin.tar.xz.sha256) |
|
||||||
|
| [rmcl-x86_64-apple-darwin.tar.xz](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-apple-darwin.tar.xz) | Intel macOS | [checksum](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-apple-darwin.tar.xz.sha256) |
|
||||||
|
| [rmcl-x86_64-pc-windows-msvc.zip](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-pc-windows-msvc.zip) | x64 Windows | [checksum](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-pc-windows-msvc.zip.sha256) |
|
||||||
|
| [rmcl-x86_64-pc-windows-msvc.msi](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-pc-windows-msvc.msi) | x64 Windows | [checksum](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-pc-windows-msvc.msi.sha256) |
|
||||||
|
| [rmcl-aarch64-unknown-linux-gnu.tar.xz](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-aarch64-unknown-linux-gnu.tar.xz) | ARM64 Linux | [checksum](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-aarch64-unknown-linux-gnu.tar.xz.sha256) |
|
||||||
|
| [rmcl-x86_64-unknown-linux-gnu.tar.xz](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-unknown-linux-gnu.tar.xz) | x64 Linux | [checksum](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-unknown-linux-gnu.tar.xz.sha256) |
|
||||||
|
|
||||||
|
## installation
|
||||||
|
|
||||||
|
release archives and installers are attached above. package-manager releases can take a little longer to become available.
|
||||||
|
|
||||||
|
### Cargo
|
||||||
|
|
||||||
|
\`\`\`
|
||||||
|
cargo install rmcl
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### Homebrew
|
||||||
|
|
||||||
|
\`\`\`
|
||||||
|
brew install objz/tap/rmcl
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### WinGet
|
||||||
|
|
||||||
|
\`\`\`
|
||||||
|
winget install Objz.Rmcl
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
The generated WinGet manifest is attached as \`winget-manifest-${APP_VERSION}.zip\` for local validation.
|
||||||
|
|
||||||
|
### AUR
|
||||||
|
|
||||||
|
\`\`\`
|
||||||
|
paru -S rmcl-bin
|
||||||
|
\`\`\`
|
||||||
|
EOF
|
||||||
|
|
||||||
|
gh release create "${{ needs.plan.outputs.tag }}" --target "$RELEASE_COMMIT" $PRERELEASE_FLAG --title "$ANNOUNCEMENT_TITLE" --notes-file "$RUNNER_TEMP/notes.txt" artifacts/*
|
||||||
|
|
||||||
|
publish-homebrew-formula:
|
||||||
|
needs:
|
||||||
|
- plan
|
||||||
|
- host
|
||||||
|
runs-on: "ubuntu-22.04"
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
PLAN: ${{ needs.plan.outputs.val }}
|
||||||
|
HOMEBREW_TAP_REPOSITORY: "objz/homebrew-tap"
|
||||||
|
GITHUB_USER: "axo bot"
|
||||||
|
GITHUB_EMAIL: "admin+bot@axo.dev"
|
||||||
|
if: ${{ !fromJson(needs.plan.outputs.val).announcement_is_prerelease || fromJson(needs.plan.outputs.val).publish_prereleases }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
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:
|
||||||
|
pattern: artifacts-*
|
||||||
|
path: Formula/
|
||||||
|
merge-multiple: true
|
||||||
|
# This is extra complex because you can make your Formula name not match your app name
|
||||||
|
# so we need to find releases with a *.rb file, and publish with that filename.
|
||||||
|
- name: Commit formula files
|
||||||
|
run: |
|
||||||
|
git config --global user.name "${GITHUB_USER}"
|
||||||
|
git config --global user.email "${GITHUB_EMAIL}"
|
||||||
|
starting_commit="$(git rev-parse HEAD)"
|
||||||
|
|
||||||
|
for release in $(echo "$PLAN" | jq --compact-output '.releases[] | select([.artifacts[] | endswith(".rb")] | any)'); do
|
||||||
|
filename=$(echo "$release" | jq '.artifacts[] | select(endswith(".rb"))' --raw-output)
|
||||||
|
name=$(echo "$filename" | sed "s/\.rb$//")
|
||||||
|
version=$(echo "$release" | jq .app_version --raw-output)
|
||||||
|
|
||||||
|
export PATH="/home/linuxbrew/.linuxbrew/bin:$PATH"
|
||||||
|
brew update
|
||||||
|
# We avoid reformatting user-provided data such as the app description and homepage.
|
||||||
|
brew style --except-cops FormulaAudit/Homepage,FormulaAudit/Desc,FormulaAuditStrict --fix "Formula/${filename}" || true
|
||||||
|
|
||||||
|
git add "Formula/${filename}"
|
||||||
|
if git diff --cached --quiet; then
|
||||||
|
echo "Formula/${filename} is unchanged"
|
||||||
|
else
|
||||||
|
git commit -m "${name} ${version}"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ "$(git rev-parse HEAD)" = "$starting_commit" ]; then
|
||||||
|
echo "No Homebrew formula changes to push"
|
||||||
|
else
|
||||||
|
git push
|
||||||
|
fi
|
||||||
|
|
||||||
|
custom-publish-crates:
|
||||||
|
needs:
|
||||||
|
- plan
|
||||||
|
- host
|
||||||
|
if: ${{ !fromJson(needs.plan.outputs.val).announcement_is_prerelease || fromJson(needs.plan.outputs.val).publish_prereleases }}
|
||||||
|
uses: ./.github/workflows/publish-crates.yml
|
||||||
|
with:
|
||||||
|
plan: ${{ needs.plan.outputs.val }}
|
||||||
|
dry_run: false
|
||||||
|
secrets: inherit
|
||||||
|
# publish jobs get escalated permissions
|
||||||
|
permissions:
|
||||||
|
"contents": "read"
|
||||||
|
|
||||||
|
custom-publish-aur:
|
||||||
|
needs:
|
||||||
|
- plan
|
||||||
|
- host
|
||||||
|
if: ${{ !fromJson(needs.plan.outputs.val).announcement_is_prerelease || fromJson(needs.plan.outputs.val).publish_prereleases }}
|
||||||
|
uses: ./.github/workflows/publish-aur.yml
|
||||||
|
with:
|
||||||
|
plan: ${{ needs.plan.outputs.val }}
|
||||||
|
secrets: inherit
|
||||||
|
# publish jobs get escalated permissions
|
||||||
|
permissions:
|
||||||
|
"contents": "read"
|
||||||
|
|
||||||
|
custom-publish-winget:
|
||||||
|
needs:
|
||||||
|
- plan
|
||||||
|
- host
|
||||||
|
if: ${{ !fromJson(needs.plan.outputs.val).announcement_is_prerelease || fromJson(needs.plan.outputs.val).publish_prereleases }}
|
||||||
|
uses: ./.github/workflows/publish-winget.yml
|
||||||
|
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
|
||||||
@@ -1,36 +1,17 @@
|
|||||||
name: build
|
name: ci
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [master]
|
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [master]
|
branches: [master]
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ci-${{ github.ref }}
|
||||||
|
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
check:
|
checks:
|
||||||
runs-on: ubuntu-latest
|
uses: ./.github/workflows/checks.yml
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v6
|
|
||||||
|
|
||||||
- name: install Rust
|
|
||||||
uses: dtolnay/rust-toolchain@stable
|
|
||||||
with:
|
|
||||||
components: clippy
|
|
||||||
|
|
||||||
- name: install JDK
|
|
||||||
uses: actions/setup-java@v5
|
|
||||||
with:
|
|
||||||
distribution: temurin
|
|
||||||
java-version: "21"
|
|
||||||
|
|
||||||
- uses: Swatinem/rust-cache@v2
|
|
||||||
|
|
||||||
- name: check
|
|
||||||
run: cargo check --locked
|
|
||||||
|
|
||||||
- name: clippy
|
|
||||||
run: cargo clippy --all-targets --locked -- -D warnings
|
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
name: checks
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
network-tests:
|
||||||
|
type: boolean
|
||||||
|
default: false
|
||||||
|
ref:
|
||||||
|
type: string
|
||||||
|
default: ""
|
||||||
|
secrets:
|
||||||
|
curseforge-api-key:
|
||||||
|
required: false
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
env:
|
||||||
|
CARGO_TERM_COLOR: always
|
||||||
|
RUST_BACKTRACE: 1
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
format:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
ref: ${{ inputs.ref || github.sha }}
|
||||||
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
|
with:
|
||||||
|
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 }}
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
ref: ${{ inputs.ref || github.sha }}
|
||||||
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
|
- uses: actions/setup-java@v5
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: "21"
|
||||||
|
- uses: Swatinem/rust-cache@v2
|
||||||
|
with:
|
||||||
|
key: ${{ matrix.os }}
|
||||||
|
- run: cargo build --locked
|
||||||
|
- run: cargo test --locked --all-targets
|
||||||
|
|
||||||
|
network-tests:
|
||||||
|
if: inputs.network-tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
env:
|
||||||
|
CURSEFORGE_API_KEY: ${{ secrets.curseforge-api-key }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
ref: ${{ inputs.ref || github.sha }}
|
||||||
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
|
- uses: actions/setup-java@v5
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: "21"
|
||||||
|
- uses: Swatinem/rust-cache@v2
|
||||||
|
- run: cargo test --locked --all-targets -- --ignored
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
name: publish chocolatey
|
|
||||||
|
|
||||||
on:
|
|
||||||
workflow_call:
|
|
||||||
inputs:
|
|
||||||
plan:
|
|
||||||
required: true
|
|
||||||
type: string
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
publish:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
env:
|
|
||||||
PLAN: ${{ inputs.plan }}
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
CHOCOLATEY_API_KEY: ${{ secrets.CHOCOLATEY_API_KEY }}
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v6
|
|
||||||
with:
|
|
||||||
ref: ${{ fromJson(inputs.plan).announcement_tag }}
|
|
||||||
|
|
||||||
- name: verify Chocolatey publishing secret
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
if [ -z "${CHOCOLATEY_API_KEY}" ]; then
|
|
||||||
echo "::error::CHOCOLATEY_API_KEY is required to publish rmcl to Chocolatey."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: prepare Chocolatey package
|
|
||||||
id: package
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
tag="$(jq --raw-output '.announcement_tag' <<< "$PLAN")"
|
|
||||||
version="$(jq --raw-output '.releases[0].app_version' <<< "$PLAN")"
|
|
||||||
package_dir="target/chocolatey/rmcl"
|
|
||||||
checksum_file="rmcl-x86_64-pc-windows-msvc.msi.sha256"
|
|
||||||
|
|
||||||
mkdir -p "$package_dir"
|
|
||||||
cp -R pkg/chocolatey/* "$package_dir/"
|
|
||||||
gh release download "$tag" --pattern "$checksum_file" --dir "$package_dir"
|
|
||||||
|
|
||||||
checksum="$(awk '{print $1}' "$package_dir/$checksum_file")"
|
|
||||||
sed -i "s|__TAG__|$tag|g; s|__CHECKSUM64__|$checksum|g" "$package_dir/tools/chocolateyInstall.ps1"
|
|
||||||
sed -i "s|__TAG__|$tag|g; s|__CHECKSUM64__|$checksum|g" "$package_dir/tools/VERIFICATION.txt"
|
|
||||||
|
|
||||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "package_dir=$package_dir" >> "$GITHUB_OUTPUT"
|
|
||||||
|
|
||||||
- name: pack Chocolatey package
|
|
||||||
uses: crazy-max/ghaction-chocolatey@v4
|
|
||||||
with:
|
|
||||||
args: pack ${{ steps.package.outputs.package_dir }}/rmcl.nuspec --version ${{ steps.package.outputs.version }} --output-directory target/chocolatey/out
|
|
||||||
|
|
||||||
- name: push Chocolatey package
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
package="target/chocolatey/out/rmcl.${{ steps.package.outputs.version }}.nupkg"
|
|
||||||
version="${{ steps.package.outputs.version }}"
|
|
||||||
public_package_url="https://community.chocolatey.org/packages/rmcl/$version"
|
|
||||||
saw_server_error=false
|
|
||||||
|
|
||||||
for attempt in 1 2 3; do
|
|
||||||
log_file="$RUNNER_TEMP/chocolatey-push-${attempt}.log"
|
|
||||||
|
|
||||||
if docker run --rm --workdir /wksp --volume "$PWD:/wksp" ghcr.io/crazy-max/chocolatey push "$package" --source "https://push.chocolatey.org/" --api-key "$CHOCOLATEY_API_KEY" --timeout 2700 2>&1 | tee "$log_file"; then
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
if grep -q "409 (Conflict)" "$log_file"; then
|
|
||||||
echo "::warning::Chocolatey package version already exists; treating this publish as complete."
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
if grep -qE "50[0-9] \\(" "$log_file"; then
|
|
||||||
saw_server_error=true
|
|
||||||
fi
|
|
||||||
|
|
||||||
if grep -q "403 (Forbidden)" "$log_file"; then
|
|
||||||
if [ "$saw_server_error" = "true" ]; then
|
|
||||||
echo "::warning::Chocolatey returned 403 after an earlier server error. The previous push may have been accepted and put into moderation; treating this publish as complete."
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
page_file="$RUNNER_TEMP/chocolatey-package-$version.html"
|
|
||||||
page_status="$(curl --location --silent --show-error --output "$page_file" --write-out "%{http_code}" "$public_package_url")"
|
|
||||||
|
|
||||||
if [ "$page_status" = "200" ] && grep -qE "awaiting moderation|remain unlisted until it has been approved|Version History" "$page_file"; then
|
|
||||||
echo "::warning::Chocolatey returned 403, but the public package page for version $version exists and is awaiting moderation; treating this publish as complete."
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "::error::Chocolatey rejected the push with 403 before any server-side failure. Check CHOCOLATEY_API_KEY ownership/permissions for rmcl."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ "$attempt" -eq 3 ]; then
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
|
|
||||||
sleep $((attempt * 30))
|
|
||||||
done
|
|
||||||
|
|
||||||
exit 1
|
|
||||||
@@ -104,6 +104,7 @@ jobs:
|
|||||||
shell: pwsh
|
shell: pwsh
|
||||||
env:
|
env:
|
||||||
GH_TOKEN: ${{ github.token }}
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
GH_REPO: ${{ github.repository }}
|
||||||
PLAN: ${{ inputs.plan }}
|
PLAN: ${{ inputs.plan }}
|
||||||
run: |
|
run: |
|
||||||
$plan = $env:PLAN | ConvertFrom-Json
|
$plan = $env:PLAN | ConvertFrom-Json
|
||||||
|
|||||||
+56
-450
@@ -1,472 +1,78 @@
|
|||||||
# This file was autogenerated by dist: https://axodotdev.github.io/cargo-dist
|
|
||||||
#
|
|
||||||
# Copyright 2022-2024, axodotdev
|
|
||||||
# SPDX-License-Identifier: MIT or Apache-2.0
|
|
||||||
#
|
|
||||||
# CI that:
|
|
||||||
#
|
|
||||||
# * checks for a Git Tag that looks like a release
|
|
||||||
# * builds artifacts with dist (archives, installers, hashes)
|
|
||||||
# * uploads those artifacts to temporary workflow zip
|
|
||||||
# * on success, uploads the artifacts to a GitHub Release
|
|
||||||
#
|
|
||||||
# Note that the GitHub Release will be created with a generated
|
|
||||||
# title/body based on your changelogs.
|
|
||||||
|
|
||||||
name: release
|
name: release
|
||||||
permissions:
|
|
||||||
"contents": "write"
|
|
||||||
|
|
||||||
# This task will run whenever you push a git tag that looks like a version
|
|
||||||
# like "1.0.0", "v0.1.0-prerelease.1", "my-app/0.1.0", "releases/v1.0.0", etc.
|
|
||||||
# Various formats will be parsed into a VERSION and an optional PACKAGE_NAME, where
|
|
||||||
# PACKAGE_NAME must be the name of a Cargo package in your workspace, and VERSION
|
|
||||||
# must be a Cargo-style SemVer Version (must have at least major.minor.patch).
|
|
||||||
#
|
|
||||||
# If PACKAGE_NAME is specified, then the announcement will be for that
|
|
||||||
# package (erroring out if it doesn't have the given version or isn't dist-able).
|
|
||||||
#
|
|
||||||
# If PACKAGE_NAME isn't specified, then the announcement will be for all
|
|
||||||
# (dist-able) packages in the workspace with that version (this mode is
|
|
||||||
# intended for workspaces with only one dist-able package, or with all dist-able
|
|
||||||
# packages versioned/released in lockstep).
|
|
||||||
#
|
|
||||||
# If you push multiple tags at once, separate instances of this workflow will
|
|
||||||
# spin up, creating an independent announcement for each one. However, GitHub
|
|
||||||
# will hard limit this to 3 tags per commit, as it will assume more tags is a
|
|
||||||
# mistake.
|
|
||||||
#
|
|
||||||
# If there's a prerelease-style suffix to the version, then the release(s)
|
|
||||||
# will be marked as a prerelease.
|
|
||||||
on:
|
on:
|
||||||
pull_request:
|
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
push:
|
|
||||||
tags:
|
permissions:
|
||||||
- '**[0-9]+.[0-9]+.[0-9]+*'
|
contents: write
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: release
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
# Run 'dist plan' (or host) to determine what tasks we need to do
|
checks:
|
||||||
plan:
|
uses: ./.github/workflows/checks.yml
|
||||||
runs-on: "ubuntu-22.04"
|
with:
|
||||||
|
network-tests: true
|
||||||
|
ref: master
|
||||||
|
secrets:
|
||||||
|
curseforge-api-key: ${{ secrets.CURSEFORGE_API_KEY }}
|
||||||
|
|
||||||
|
prepare:
|
||||||
|
needs: checks
|
||||||
|
runs-on: ubuntu-latest
|
||||||
outputs:
|
outputs:
|
||||||
val: ${{ steps.plan.outputs.manifest }}
|
release: ${{ steps.version.outputs.release }}
|
||||||
tag: ${{ !github.event.pull_request && github.ref_name || '' }}
|
tag: ${{ steps.version.outputs.tag }}
|
||||||
tag-flag: ${{ !github.event.pull_request && format('--tag={0}', github.ref_name) || '' }}
|
|
||||||
publishing: ${{ !github.event.pull_request }}
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v6
|
- uses: actions/checkout@v6
|
||||||
with:
|
with:
|
||||||
persist-credentials: false
|
ref: master
|
||||||
submodules: recursive
|
|
||||||
- name: Install dist
|
|
||||||
# we specify bash to get pipefail; it guards against the `curl` command
|
|
||||||
# failing. otherwise `sh` won't catch that `curl` returned non-0
|
|
||||||
shell: bash
|
|
||||||
run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.31.0/cargo-dist-installer.sh | sh"
|
|
||||||
- name: Cache dist
|
|
||||||
uses: actions/upload-artifact@v6
|
|
||||||
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 ${{ (!github.event.pull_request && format('host --steps=create --tag={0}', github.ref_name)) || 'plan' }} --output-format=json > plan-dist-manifest.json
|
|
||||||
echo "dist ran successfully"
|
|
||||||
cat plan-dist-manifest.json
|
|
||||||
echo "manifest=$(jq -c "." plan-dist-manifest.json)" >> "$GITHUB_OUTPUT"
|
|
||||||
- name: "Upload dist-manifest.json"
|
|
||||||
uses: actions/upload-artifact@v6
|
|
||||||
with:
|
|
||||||
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 }}
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
BUILD_MANIFEST_NAME: target/distrib/${{ join(matrix.targets, '-') }}-dist-manifest.json
|
|
||||||
steps:
|
|
||||||
- name: enable windows longpaths
|
|
||||||
run: |
|
|
||||||
git config --global core.longpaths true
|
|
||||||
- uses: actions/checkout@v6
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
submodules: recursive
|
|
||||||
- name: Install Rust non-interactively if not already installed
|
|
||||||
if: ${{ matrix.container }}
|
|
||||||
run: |
|
|
||||||
if ! command -v cargo > /dev/null 2>&1; then
|
|
||||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
|
|
||||||
echo "$HOME/.cargo/bin" >> $GITHUB_PATH
|
|
||||||
fi
|
|
||||||
- name: "install JDK"
|
|
||||||
uses: "actions/setup-java@v5"
|
|
||||||
with:
|
|
||||||
"distribution": "temurin"
|
|
||||||
"java-version": "21"
|
|
||||||
- name: Install dist
|
|
||||||
run: ${{ matrix.install_dist.run }}
|
|
||||||
# Get the dist-manifest
|
|
||||||
- name: Fetch local artifacts
|
|
||||||
uses: actions/download-artifact@v7
|
|
||||||
with:
|
|
||||||
pattern: artifacts-*
|
|
||||||
path: target/distrib/
|
|
||||||
merge-multiple: true
|
|
||||||
- name: Install dependencies
|
|
||||||
run: |
|
|
||||||
${{ 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
|
|
||||||
name: Post-build
|
|
||||||
# We force bash here just because github makes it really hard to get values up
|
|
||||||
# to "real" actions without writing to env-vars, and writing to env-vars has
|
|
||||||
# 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"
|
|
||||||
|
|
||||||
cp dist-manifest.json "$BUILD_MANIFEST_NAME"
|
|
||||||
- name: "Upload artifacts"
|
|
||||||
uses: actions/upload-artifact@v6
|
|
||||||
with:
|
|
||||||
name: artifacts-build-local-${{ join(matrix.targets, '_') }}
|
|
||||||
path: |
|
|
||||||
${{ steps.cargo-dist.outputs.paths }}
|
|
||||||
${{ env.BUILD_MANIFEST_NAME }}
|
|
||||||
|
|
||||||
# Build and package all the platform-agnostic(ish) things
|
|
||||||
build-global-artifacts:
|
|
||||||
needs:
|
|
||||||
- plan
|
|
||||||
- build-local-artifacts
|
|
||||||
runs-on: "ubuntu-22.04"
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
BUILD_MANIFEST_NAME: target/distrib/global-dist-manifest.json
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v6
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
submodules: recursive
|
|
||||||
- name: Install cached dist
|
|
||||||
uses: actions/download-artifact@v7
|
|
||||||
with:
|
|
||||||
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:
|
|
||||||
pattern: artifacts-*
|
|
||||||
path: target/distrib/
|
|
||||||
merge-multiple: true
|
|
||||||
- id: cargo-dist
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
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"
|
|
||||||
|
|
||||||
cp dist-manifest.json "$BUILD_MANIFEST_NAME"
|
|
||||||
- name: "Upload artifacts"
|
|
||||||
uses: actions/upload-artifact@v6
|
|
||||||
with:
|
|
||||||
name: artifacts-build-global
|
|
||||||
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 }}
|
|
||||||
runs-on: "ubuntu-22.04"
|
|
||||||
outputs:
|
|
||||||
val: ${{ steps.host.outputs.manifest }}
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v6
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
submodules: recursive
|
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
fetch-tags: true
|
fetch-tags: true
|
||||||
- name: Install cached dist
|
|
||||||
uses: actions/download-artifact@v7
|
- name: check version
|
||||||
with:
|
id: version
|
||||||
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:
|
|
||||||
pattern: artifacts-*
|
|
||||||
path: target/distrib/
|
|
||||||
merge-multiple: true
|
|
||||||
- id: host
|
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
dist host ${{ needs.plan.outputs.tag-flag }} --steps=upload --steps=release --output-format=json > dist-manifest.json
|
set -euo pipefail
|
||||||
echo "artifacts uploaded and released successfully"
|
|
||||||
cat dist-manifest.json
|
|
||||||
echo "manifest=$(jq -c "." dist-manifest.json)" >> "$GITHUB_OUTPUT"
|
|
||||||
- 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:
|
|
||||||
pattern: artifacts-*
|
|
||||||
path: artifacts
|
|
||||||
merge-multiple: true
|
|
||||||
- name: Cleanup
|
|
||||||
run: |
|
|
||||||
# Remove internal cargo-dist manifests from the public GitHub Release.
|
|
||||||
rm -f artifacts/*-dist-manifest.json artifacts/dist-manifest.json
|
|
||||||
- name: Generate changelog
|
|
||||||
id: changelog
|
|
||||||
uses: orhun/git-cliff-action@v4
|
|
||||||
with:
|
|
||||||
args: --latest --strip header
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
- name: Create GitHub Release
|
|
||||||
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 }}"
|
|
||||||
run: |
|
|
||||||
echo "$CHANGELOG" > $RUNNER_TEMP/notes.txt
|
|
||||||
cat >> $RUNNER_TEMP/notes.txt <<EOF
|
|
||||||
|
|
||||||
## Downloads
|
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
|
||||||
|
|
||||||
| File | Platform | Checksum |
|
if [[ -z "$latest" ]] || [[ "$version" != "$latest" && "$(printf '%s\n%s\n' "$latest" "$version" | sort -V | tail -n1)" == "$version" ]]; then
|
||||||
| --- | --- | --- |
|
release=true
|
||||||
| [rmcl-aarch64-apple-darwin.tar.xz](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-aarch64-apple-darwin.tar.xz) | Apple Silicon macOS | [checksum](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-aarch64-apple-darwin.tar.xz.sha256) |
|
|
||||||
| [rmcl-x86_64-apple-darwin.tar.xz](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-apple-darwin.tar.xz) | Intel macOS | [checksum](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-apple-darwin.tar.xz.sha256) |
|
|
||||||
| [rmcl-x86_64-pc-windows-msvc.zip](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-pc-windows-msvc.zip) | x64 Windows | [checksum](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-pc-windows-msvc.zip.sha256) |
|
|
||||||
| [rmcl-x86_64-pc-windows-msvc.msi](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-pc-windows-msvc.msi) | x64 Windows | [checksum](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-pc-windows-msvc.msi.sha256) |
|
|
||||||
| [rmcl-aarch64-unknown-linux-gnu.tar.xz](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-aarch64-unknown-linux-gnu.tar.xz) | ARM64 Linux | [checksum](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-aarch64-unknown-linux-gnu.tar.xz.sha256) |
|
|
||||||
| [rmcl-x86_64-unknown-linux-gnu.tar.xz](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-unknown-linux-gnu.tar.xz) | x64 Linux | [checksum](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-unknown-linux-gnu.tar.xz.sha256) |
|
|
||||||
|
|
||||||
## Cargo
|
|
||||||
|
|
||||||
\`\`\`
|
|
||||||
cargo install rmcl
|
|
||||||
\`\`\`
|
|
||||||
|
|
||||||
## Homebrew
|
|
||||||
|
|
||||||
\`\`\`
|
|
||||||
brew install objz/tap/rmcl
|
|
||||||
\`\`\`
|
|
||||||
|
|
||||||
## WinGet
|
|
||||||
|
|
||||||
\`\`\`
|
|
||||||
winget install Objz.Rmcl
|
|
||||||
\`\`\`
|
|
||||||
|
|
||||||
The generated WinGet manifest is attached as \`winget-manifest-${APP_VERSION}.zip\` for local validation.
|
|
||||||
|
|
||||||
## Chocolatey
|
|
||||||
|
|
||||||
\`\`\`
|
|
||||||
choco install rmcl
|
|
||||||
\`\`\`
|
|
||||||
|
|
||||||
## AUR
|
|
||||||
|
|
||||||
\`\`\`
|
|
||||||
paru -S rmcl-bin
|
|
||||||
\`\`\`
|
|
||||||
EOF
|
|
||||||
|
|
||||||
gh release create "${{ needs.plan.outputs.tag }}" --target "$RELEASE_COMMIT" $PRERELEASE_FLAG --title "$ANNOUNCEMENT_TITLE" --notes-file "$RUNNER_TEMP/notes.txt" artifacts/*
|
|
||||||
|
|
||||||
publish-homebrew-formula:
|
|
||||||
needs:
|
|
||||||
- plan
|
|
||||||
- host
|
|
||||||
runs-on: "ubuntu-22.04"
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
PLAN: ${{ needs.plan.outputs.val }}
|
|
||||||
HOMEBREW_TAP_REPOSITORY: "objz/homebrew-tap"
|
|
||||||
GITHUB_USER: "axo bot"
|
|
||||||
GITHUB_EMAIL: "admin+bot@axo.dev"
|
|
||||||
if: ${{ !fromJson(needs.plan.outputs.val).announcement_is_prerelease || fromJson(needs.plan.outputs.val).publish_prereleases }}
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v6
|
|
||||||
with:
|
|
||||||
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:
|
|
||||||
pattern: artifacts-*
|
|
||||||
path: Formula/
|
|
||||||
merge-multiple: true
|
|
||||||
# This is extra complex because you can make your Formula name not match your app name
|
|
||||||
# so we need to find releases with a *.rb file, and publish with that filename.
|
|
||||||
- name: Commit formula files
|
|
||||||
run: |
|
|
||||||
git config --global user.name "${GITHUB_USER}"
|
|
||||||
git config --global user.email "${GITHUB_EMAIL}"
|
|
||||||
starting_commit="$(git rev-parse HEAD)"
|
|
||||||
|
|
||||||
for release in $(echo "$PLAN" | jq --compact-output '.releases[] | select([.artifacts[] | endswith(".rb")] | any)'); do
|
|
||||||
filename=$(echo "$release" | jq '.artifacts[] | select(endswith(".rb"))' --raw-output)
|
|
||||||
name=$(echo "$filename" | sed "s/\.rb$//")
|
|
||||||
version=$(echo "$release" | jq .app_version --raw-output)
|
|
||||||
|
|
||||||
export PATH="/home/linuxbrew/.linuxbrew/bin:$PATH"
|
|
||||||
brew update
|
|
||||||
# We avoid reformatting user-provided data such as the app description and homepage.
|
|
||||||
brew style --except-cops FormulaAudit/Homepage,FormulaAudit/Desc,FormulaAuditStrict --fix "Formula/${filename}" || true
|
|
||||||
|
|
||||||
git add "Formula/${filename}"
|
|
||||||
if git diff --cached --quiet; then
|
|
||||||
echo "Formula/${filename} is unchanged"
|
|
||||||
else
|
|
||||||
git commit -m "${name} ${version}"
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
if [ "$(git rev-parse HEAD)" = "$starting_commit" ]; then
|
|
||||||
echo "No Homebrew formula changes to push"
|
|
||||||
else
|
|
||||||
git push
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
custom-publish-crates:
|
echo "release=$release" >> "$GITHUB_OUTPUT"
|
||||||
needs:
|
echo "tag=$tag" >> "$GITHUB_OUTPUT"
|
||||||
- plan
|
|
||||||
- host
|
|
||||||
if: ${{ !fromJson(needs.plan.outputs.val).announcement_is_prerelease || fromJson(needs.plan.outputs.val).publish_prereleases }}
|
|
||||||
uses: ./.github/workflows/publish-crates.yml
|
|
||||||
with:
|
|
||||||
plan: ${{ needs.plan.outputs.val }}
|
|
||||||
dry_run: false
|
|
||||||
secrets: inherit
|
|
||||||
# publish jobs get escalated permissions
|
|
||||||
permissions:
|
|
||||||
"contents": "read"
|
|
||||||
|
|
||||||
custom-publish-aur:
|
if [[ "$release" == true ]]; then
|
||||||
needs:
|
echo "releasing $tag (latest release: ${latest:-none})"
|
||||||
- plan
|
else
|
||||||
- host
|
echo "Cargo.toml version $version is not newer than latest release v$latest; nothing to release"
|
||||||
if: ${{ !fromJson(needs.plan.outputs.val).announcement_is_prerelease || fromJson(needs.plan.outputs.val).publish_prereleases }}
|
fi
|
||||||
uses: ./.github/workflows/publish-aur.yml
|
|
||||||
with:
|
|
||||||
plan: ${{ needs.plan.outputs.val }}
|
|
||||||
secrets: inherit
|
|
||||||
# publish jobs get escalated permissions
|
|
||||||
permissions:
|
|
||||||
"contents": "read"
|
|
||||||
|
|
||||||
custom-publish-winget:
|
- name: create tag
|
||||||
needs:
|
if: steps.version.outputs.release == 'true'
|
||||||
- plan
|
|
||||||
- host
|
|
||||||
if: ${{ !fromJson(needs.plan.outputs.val).announcement_is_prerelease || fromJson(needs.plan.outputs.val).publish_prereleases }}
|
|
||||||
uses: ./.github/workflows/publish-winget.yml
|
|
||||||
with:
|
|
||||||
plan: ${{ needs.plan.outputs.val }}
|
|
||||||
secrets: inherit
|
|
||||||
# publish jobs get escalated permissions
|
|
||||||
permissions:
|
|
||||||
"contents": "write"
|
|
||||||
|
|
||||||
custom-publish-chocolatey:
|
|
||||||
needs:
|
|
||||||
- plan
|
|
||||||
- host
|
|
||||||
if: ${{ !fromJson(needs.plan.outputs.val).announcement_is_prerelease || fromJson(needs.plan.outputs.val).publish_prereleases }}
|
|
||||||
uses: ./.github/workflows/publish-chocolatey.yml
|
|
||||||
with:
|
|
||||||
plan: ${{ needs.plan.outputs.val }}
|
|
||||||
secrets: inherit
|
|
||||||
# publish jobs get escalated permissions
|
|
||||||
permissions:
|
|
||||||
"contents": "read"
|
|
||||||
|
|
||||||
announce:
|
|
||||||
needs:
|
|
||||||
- plan
|
|
||||||
- host
|
|
||||||
- publish-homebrew-formula
|
|
||||||
- custom-publish-crates
|
|
||||||
- custom-publish-aur
|
|
||||||
- custom-publish-winget
|
|
||||||
- custom-publish-chocolatey
|
|
||||||
# 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') && (needs.custom-publish-chocolatey.result == 'skipped' || needs.custom-publish-chocolatey.result == 'success') }}
|
|
||||||
runs-on: "ubuntu-22.04"
|
|
||||||
env:
|
env:
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
TAG: ${{ steps.version.outputs.tag }}
|
||||||
steps:
|
run: |
|
||||||
- uses: actions/checkout@v6
|
git config user.name github-actions[bot]
|
||||||
|
git config user.email 41898282+github-actions[bot]@users.noreply.github.com
|
||||||
|
git tag --annotate "$TAG" --message "Release $TAG"
|
||||||
|
git push origin "$TAG"
|
||||||
|
|
||||||
|
publish:
|
||||||
|
needs: prepare
|
||||||
|
if: needs.prepare.outputs.release == 'true'
|
||||||
|
uses: ./.github/workflows/build-release.yml
|
||||||
with:
|
with:
|
||||||
persist-credentials: false
|
tag: ${{ needs.prepare.outputs.tag }}
|
||||||
submodules: recursive
|
secrets: inherit
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
name: tag release
|
|
||||||
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
workflow_run:
|
|
||||||
workflows: ["build"]
|
|
||||||
branches: [master]
|
|
||||||
types: [completed]
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
concurrency:
|
|
||||||
group: tag-release
|
|
||||||
cancel-in-progress: false
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
tag-release:
|
|
||||||
if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' }}
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v6
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
fetch-tags: true
|
|
||||||
ref: ${{ github.event.workflow_run.head_sha || 'master' }}
|
|
||||||
|
|
||||||
- name: decide release tag
|
|
||||||
id: release
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
version=$(awk '
|
|
||||||
$0 == "[package]" { in_package = 1; next }
|
|
||||||
/^\[/ && in_package { exit }
|
|
||||||
in_package && $1 == "version" {
|
|
||||||
gsub(/"/, "", $3)
|
|
||||||
print $3
|
|
||||||
exit
|
|
||||||
}
|
|
||||||
' Cargo.toml)
|
|
||||||
|
|
||||||
if [[ -z "$version" ]]; then
|
|
||||||
echo "failed to read package version from Cargo.toml" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
latest=$(
|
|
||||||
git tag --list \
|
|
||||||
| sed -nE 's/^v?([0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?)$/\1/p' \
|
|
||||||
| sort -V \
|
|
||||||
| tail -n1
|
|
||||||
)
|
|
||||||
|
|
||||||
should_release=false
|
|
||||||
if [[ -z "$latest" ]]; then
|
|
||||||
should_release=true
|
|
||||||
elif [[ "$version" != "$latest" && "$(printf '%s\n%s\n' "$latest" "$version" | sort -V | tail -n1)" == "$version" ]]; then
|
|
||||||
should_release=true
|
|
||||||
fi
|
|
||||||
|
|
||||||
tag="v${version}"
|
|
||||||
echo "version=${version}" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "latest=${latest}" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "tag=${tag}" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "should-release=${should_release}" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
|
|
||||||
|
|
||||||
if [[ "$should_release" == "true" ]]; then
|
|
||||||
echo "Cargo.toml version ${version} is newer than latest tag ${latest:-<none>}; creating ${tag}."
|
|
||||||
else
|
|
||||||
echo "Cargo.toml version ${version} is not newer than latest tag ${latest}; skipping release."
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: create release tag
|
|
||||||
if: ${{ steps.release.outputs.should-release == 'true' }}
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
|
||||||
TAG_NAME: ${{ steps.release.outputs.tag }}
|
|
||||||
TAG_SHA: ${{ steps.release.outputs.sha }}
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
if [[ -z "${GH_TOKEN}" ]]; then
|
|
||||||
echo "RELEASE_TOKEN is required so the created tag can trigger the generated release workflow." >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
gh api "repos/${{ github.repository }}/git/refs" \
|
|
||||||
-f "ref=refs/tags/${TAG_NAME}" \
|
|
||||||
-f "sha=${TAG_SHA}"
|
|
||||||
@@ -1,2 +1,3 @@
|
|||||||
/target
|
/target
|
||||||
|
/scripts
|
||||||
*.log
|
*.log
|
||||||
Generated
+1152
-69
File diff suppressed because it is too large.
Load diff
+24
-7
@@ -1,9 +1,9 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "rmcl"
|
name = "rmcl"
|
||||||
version = "0.3.0"
|
version = "0.4.0"
|
||||||
authors = ["objz"]
|
authors = ["objz"]
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
description = "A fully featured Minecraft launcher TUI"
|
description = "A fully featured Minecraft TUI launcher"
|
||||||
repository = "https://github.com/objz/rmcl"
|
repository = "https://github.com/objz/rmcl"
|
||||||
homepage = "https://github.com/objz/rmcl"
|
homepage = "https://github.com/objz/rmcl"
|
||||||
license = "GPL-3.0-only"
|
license = "GPL-3.0-only"
|
||||||
@@ -14,6 +14,7 @@ categories = ["command-line-utilities", "games"]
|
|||||||
[package.metadata.wix]
|
[package.metadata.wix]
|
||||||
upgrade-guid = "BEC08BE4-6A8F-4C1D-A1B4-B1AC963000AE"
|
upgrade-guid = "BEC08BE4-6A8F-4C1D-A1B4-B1AC963000AE"
|
||||||
path-guid = "E5863AC2-13FC-45C8-B79D-55338F371A8A"
|
path-guid = "E5863AC2-13FC-45C8-B79D-55338F371A8A"
|
||||||
|
include = ["pkg/wix/main.wxs"]
|
||||||
license = false
|
license = false
|
||||||
eula = false
|
eula = false
|
||||||
|
|
||||||
@@ -30,27 +31,34 @@ config = "0.15.6"
|
|||||||
crossterm = "0.29.0"
|
crossterm = "0.29.0"
|
||||||
dirs-next = "2.0.0"
|
dirs-next = "2.0.0"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
ratatui = { version = "0.30.0", features = ["serde"] }
|
ratatui = { version = "0.30.0", features = ["serde", "unstable-rendered-line-info"] }
|
||||||
ratatui-themekit = { version = "0.6", features = ["serde"] }
|
ratatui-themekit = { version = "0.6", features = ["serde"] }
|
||||||
ratatui-textarea = { version = "0.9.1", features = ["crossterm"] }
|
ratatui-textarea = { version = "0.9.1", features = ["crossterm"] }
|
||||||
|
tui-markdown = { version = "0.3.7", default-features = false }
|
||||||
|
pulldown-cmark = { version = "0.13.4", default-features = false }
|
||||||
|
html-to-markdown-rs = { version = "3.9.0", features = ["visitor"] }
|
||||||
|
resvg = "0.47"
|
||||||
reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls"] }
|
reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls"] }
|
||||||
serde = { version = "1.0.217", features = ["derive"] }
|
serde = { version = "1.0.217", features = ["derive"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
|
sha1 = "0.10"
|
||||||
|
sha2 = "0.10"
|
||||||
toml = "1.1.2"
|
toml = "1.1.2"
|
||||||
tachyonfx = "0.25"
|
tachyonfx = "0.25"
|
||||||
throbber-widgets-tui = "0.11"
|
throbber-widgets-tui = "0.11"
|
||||||
thiserror = "2"
|
thiserror = "2"
|
||||||
tokio = { version = "1", features = ["full"] }
|
tokio = { version = "1", features = ["full", "test-util"] }
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
tracing-appender = "0.2"
|
tracing-appender = "0.2"
|
||||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
|
unicode-segmentation = "1"
|
||||||
tui-popup = "0.7"
|
tui-popup = "0.7"
|
||||||
tui-prompts = "0.6"
|
tui-prompts = "0.6"
|
||||||
tui-logger = { version = "0.18", features = ["tracing-support"] }
|
tui-logger = { version = "0.18", features = ["tracing-support"] }
|
||||||
tui-scrollview = "0.6"
|
tui-scrollview = "0.6"
|
||||||
tui-widget-list = "0.15"
|
tui-widget-list = "0.15"
|
||||||
ratatui-image = { version = "10.0.6", default-features = false, features = ["crossterm"] }
|
ratatui-image = { version = "11.0.6", default-features = false, features = ["crossterm"] }
|
||||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
image = { version = "0.25", default-features = false, features = ["gif", "jpeg", "png", "webp"] }
|
||||||
zip = "8.5.1"
|
zip = "8.5.1"
|
||||||
minecraft-msa-auth = "0.4.0"
|
minecraft-msa-auth = "0.4.0"
|
||||||
oauth2 = "5.0.0"
|
oauth2 = "5.0.0"
|
||||||
@@ -58,6 +66,12 @@ open = "5"
|
|||||||
which = "8.0.2"
|
which = "8.0.2"
|
||||||
dirs = "6.0.0"
|
dirs = "6.0.0"
|
||||||
notify = "8"
|
notify = "8"
|
||||||
|
regex = "1"
|
||||||
|
fast-strip-ansi = "0.13"
|
||||||
|
libcasr = "2.13"
|
||||||
|
fs2 = "0.4"
|
||||||
|
fastnbt = "2.6.2"
|
||||||
|
flate2 = "1.1.9"
|
||||||
|
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
@@ -66,10 +80,13 @@ lto = true
|
|||||||
opt-level = "s"
|
opt-level = "s"
|
||||||
strip = true
|
strip = true
|
||||||
|
|
||||||
# The profile that 'dist' will build with
|
|
||||||
[profile.dist]
|
[profile.dist]
|
||||||
inherits = "release"
|
inherits = "release"
|
||||||
lto = "thin"
|
lto = "thin"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
|
insta = "1"
|
||||||
|
wiremock = "0.6"
|
||||||
|
rstest = "0.23"
|
||||||
|
image = { version = "0.25", default-features = false, features = ["png", "webp"] }
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
[![Issues][issues-shield]][issues-url]
|
[![Issues][issues-shield]][issues-url]
|
||||||
[![GPL-3.0 License][license-shield]][license-url]
|
[![GPL-3.0 License][license-shield]][license-url]
|
||||||
|
|
||||||
**R**ust **M**ine**C**raft **L**auncher. or **R**ust **M**ine**C**raft c**L**i. pick whichever sounds better to you.
|
**R**usty **M**ine**C**raft **L**auncher. or **R**ust **M**ine**C**raft c**L**i. pick whichever sounds better to you.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
@@ -20,23 +20,27 @@
|
|||||||
|
|
||||||
## about
|
## about
|
||||||
|
|
||||||
we all love TUIs. and we all know the official Minecraft launcher is not exactly a joy to use (performance wise; no hatespeech here). so here's rmcl, a fully featured Minecraft launcher that lives in your terminal. written in Rust because if you're replacing something bloated you might as well go all the way.
|
we all love TUIs. and we all know the official Minecraft launcher is not exactly a joy to use (performance wise; no hatespeech here). so here's rmcl, a fully featured Minecraft launcher that lives in your terminal. written in Rust.
|
||||||
|
|
||||||
it does everything you'd expect from a launcher. multiple instances, mod loaders, modpack imports, Microsoft auth, content management, launching. all from a TUI or from the command line. the TUI is the main thing though, the CLI is there for scripting and automation.
|
it does everything you'd expect from a launcher.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
## features
|
## features
|
||||||
|
| Mod Loader | Supported |
|
||||||
|
|------------|-----------|
|
||||||
|
| Vanilla | ✅ |
|
||||||
|
| Fabric | ✅ |
|
||||||
|
| Forge | ✅ |
|
||||||
|
| NeoForge | ✅ |
|
||||||
|
| Quilt | ✅ |
|
||||||
|
| LiteLoader | ❌ |
|
||||||
|
| Rift | ❌ |
|
||||||
|
|
||||||
| | |
|
|
||||||
|---|---|
|
### modpacks and accounts
|
||||||
| **instances** | create and manage multiple instances, each with their own version, loader, mods, and settings |
|
|
||||||
| **mod loaders** | vanilla, Fabric, Quilt, Forge, NeoForge. more might show up later |
|
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.
|
||||||
| **content** | browse and toggle mods, shaders, resource packs. view worlds, screenshots, and logs |
|
|
||||||
| **modpack import** | import from Modrinth via `.mrpack` file, URL, or slug |
|
|
||||||
| **accounts** | multiple Microsoft accounts and offline players, switch between them |
|
|
||||||
| **launching** | launch directly from the TUI or generate a desktop shortcut for any instance |
|
|
||||||
| **desktop shortcuts** | click it and Minecraft starts, no need to open rmcl or type anything |
|
|
||||||
| **CLI** | every feature the TUI has is also available as a subcommand |
|
|
||||||
| **theming** | 10 built-in themes, custom themes, color overrides |
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -48,10 +52,14 @@ Authentication is performed through Microsoft’s official services.
|
|||||||
|
|
||||||
## installation
|
## installation
|
||||||
|
|
||||||
|
[](https://github.com/objz/rmcl/releases)
|
||||||
|
|
||||||
### macOS / Linux
|
### macOS / Linux
|
||||||
|
|
||||||
prebuilt archives are attached to each GitHub release.
|
prebuilt archives are attached to each GitHub release.
|
||||||
|
|
||||||
|
[](https://github.com/objz/homebrew-tap)
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
# Homebrew
|
# Homebrew
|
||||||
brew install objz/tap/rmcl
|
brew install objz/tap/rmcl
|
||||||
@@ -59,19 +67,21 @@ brew install objz/tap/rmcl
|
|||||||
|
|
||||||
### Windows
|
### Windows
|
||||||
|
|
||||||
release builds include a `.zip` archive and an `.msi`. WinGet and Chocolatey
|
release builds include a `.zip` archive and an `.msi`. WinGet packages are
|
||||||
packages are submitted from release CI and become available after review.
|
submitted from release CI and become available after review.
|
||||||
|
|
||||||
|
[](https://winstall.app/apps/Objz.Rmcl)
|
||||||
```powershell
|
```powershell
|
||||||
# WinGet
|
# WinGet
|
||||||
winget install Objz.Rmcl
|
winget install Objz.Rmcl
|
||||||
|
|
||||||
# Chocolatey
|
|
||||||
choco install rmcl
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Arch Linux
|
### Arch Linux
|
||||||
|
|
||||||
|
[](https://aur.archlinux.org/packages/rmcl)
|
||||||
|
[](https://aur.archlinux.org/packages/rmcl-bin)
|
||||||
|
[](https://aur.archlinux.org/packages/rmcl-git)
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
# from source (release tarball)
|
# from source (release tarball)
|
||||||
paru -S rmcl
|
paru -S rmcl
|
||||||
@@ -85,29 +95,11 @@ paru -S rmcl-git
|
|||||||
|
|
||||||
### Cargo
|
### Cargo
|
||||||
|
|
||||||
|
[](https://crates.io/crates/rmcl)
|
||||||
```sh
|
```sh
|
||||||
cargo install rmcl
|
cargo install rmcl
|
||||||
```
|
```
|
||||||
|
|
||||||
### package status
|
|
||||||
|
|
||||||
release:
|
|
||||||
|
|
||||||
[](https://github.com/objz/rmcl/releases)
|
|
||||||
[](https://crates.io/crates/rmcl)
|
|
||||||
|
|
||||||
package managers:
|
|
||||||
|
|
||||||
[](https://github.com/objz/homebrew-tap)
|
|
||||||
[](https://winstall.app/apps/Objz.Rmcl)
|
|
||||||
[](https://community.chocolatey.org/packages/rmcl)
|
|
||||||
|
|
||||||
aur:
|
|
||||||
|
|
||||||
[](https://aur.archlinux.org/packages/rmcl)
|
|
||||||
[](https://aur.archlinux.org/packages/rmcl-bin)
|
|
||||||
[](https://aur.archlinux.org/packages/rmcl-git)
|
|
||||||
|
|
||||||
### from source
|
### from source
|
||||||
|
|
||||||
requires a Rust toolchain and a JDK (`javac` and `jar` on `PATH`).
|
requires a Rust toolchain and a JDK (`javac` and `jar` on `PATH`).
|
||||||
@@ -132,7 +124,7 @@ settings, accounts, instances, and cached game metadata.
|
|||||||
| instances | `~/.local/share/rmcl/instances/` | `~/Library/Application Support/rmcl/instances/` | `%LOCALAPPDATA%\rmcl\instances\` |
|
| 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\` |
|
| metadata (versions, libraries, assets, loader profiles) | `~/.local/share/rmcl/meta/` | `~/Library/Application Support/rmcl/meta/` | `%LOCALAPPDATA%\rmcl\meta\` |
|
||||||
|
|
||||||
each instance has an `instance.json` for its config and a `.minecraft/` directory with the actual game files. standard layout, nothing weird.
|
each instance has an `instance.json` for its config and a `.minecraft/` directory with the actual game files.
|
||||||
|
|
||||||
### logs
|
### logs
|
||||||
|
|
||||||
@@ -145,9 +137,23 @@ launcher logs are per-session and contain rmcl's own output. instance launch log
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## configuration
|
## performance
|
||||||
|
|
||||||
everything is configured through TOML files. `config.toml` for paths, default memory allocation, and UI behavior. `theme.toml` for theme selection and border style. you can also override individual colors without making a full custom theme.
|
the following measurements were taken from a release build on a Linux development system. they are intended as a practical reference, since terminal, window size, content count, and hardware all affect the result.
|
||||||
|
|
||||||
|
### idle instance list
|
||||||
|
|
||||||
|
over a `60` second sample, the instance list used `497.81 ms` of CPU time. that is about `0.83%` of one CPU core. resident memory was `15.1 MiB`.
|
||||||
|
|
||||||
|
### idle mods list
|
||||||
|
|
||||||
|
with a populated mods list and its icons loaded, a `60` second sample used `664.77 ms` of CPU time. that is about `1.11%` of one CPU core. resident memory was `67.2 MiB`, with a peak of `69.9 MiB`.
|
||||||
|
|
||||||
|
### scrolling mods list
|
||||||
|
|
||||||
|
continuously scrolling through the populated mods list used `1000.02 ms` of CPU time over 30 seconds. that is about `3.33%` of one CPU core.
|
||||||
|
|
||||||
|
In comparison, the Modrinth AppImage used approximately `14-30%` of a CPU core and about `327 Mib` of memory while browsing the mod list.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -163,7 +169,7 @@ you can create your own by dropping a TOML file in `~/.config/rmcl/theme/` and r
|
|||||||
|
|
||||||
## contributing
|
## contributing
|
||||||
|
|
||||||
contributions are welcome. fork it, branch it, PR it. see [CONTRIBUTING.md](CONTRIBUTING.md) for code style and project structure.
|
contributions are welcome. fork it, branch it, PR it. see [CONTRIBUTING.md](CONTRIBUTING.md)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
+18
-2
@@ -1,9 +1,9 @@
|
|||||||
[paths]
|
[paths]
|
||||||
# where instances are stored
|
# where instances are stored
|
||||||
instances_dir = "~/.local/share/mcl/instances"
|
instances_dir = "~/.local/share/rmcl/instances"
|
||||||
|
|
||||||
# metadata, cache, whatever else ends up there
|
# metadata, cache, whatever else ends up there
|
||||||
meta_dir = "~/.local/share/mcl/meta"
|
meta_dir = "~/.local/share/rmcl/meta"
|
||||||
|
|
||||||
# optional java override (empty = uses JAVA_HOME)
|
# optional java override (empty = uses JAVA_HOME)
|
||||||
java_path = ""
|
java_path = ""
|
||||||
@@ -14,6 +14,8 @@ memory_min = "512M"
|
|||||||
memory_max = "2G"
|
memory_max = "2G"
|
||||||
|
|
||||||
[ui]
|
[ui]
|
||||||
|
# image protocol for content icons and screenshots: halfblocks, quadrants, kitty, or iterm2
|
||||||
|
image_protocol = "kitty"
|
||||||
# error popup timing (in ms)
|
# error popup timing (in ms)
|
||||||
error_auto_dismiss_ms = 5000
|
error_auto_dismiss_ms = 5000
|
||||||
error_slide_start_ms = 3500
|
error_slide_start_ms = 3500
|
||||||
@@ -21,3 +23,17 @@ error_fly_out_ms = 300
|
|||||||
|
|
||||||
# don’t let this blow up endlessly
|
# don’t let this blow up endlessly
|
||||||
max_error_events = 50
|
max_error_events = 50
|
||||||
|
|
||||||
|
[content]
|
||||||
|
# ask before choosing when the same file exists on multiple providers
|
||||||
|
ask_on_provider_conflict = true
|
||||||
|
# preferred for duplicate discovery results and automatic conflict resolution
|
||||||
|
# accepts "modrinth" or "curseforge"
|
||||||
|
preferred_provider = "modrinth"
|
||||||
|
# only show results from the preferred provider instead of filling from both
|
||||||
|
preferred_provider_only = false
|
||||||
|
# retry unchanged files that were not found after this many hours
|
||||||
|
unmatched_retry_hours = 24
|
||||||
|
# avoid hashing enormous external packs during automatic provider matching;
|
||||||
|
# set to 0 to remove the limit
|
||||||
|
max_fingerprint_size_mib = 512
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 3.7 MiB |
+16
-16
@@ -11,21 +11,21 @@ repo = "rmcl"
|
|||||||
# See https://keats.github.io/tera/docs/#introduction
|
# See https://keats.github.io/tera/docs/#introduction
|
||||||
body = """
|
body = """
|
||||||
{% if version %}\
|
{% if version %}\
|
||||||
## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }}
|
## {{ version | trim_start_matches(pat="v") }} - {{ timestamp | date(format="%Y-%m-%d") }}
|
||||||
{% else %}\
|
{% else %}\
|
||||||
## [unreleased]
|
## unreleased
|
||||||
{% endif %}\
|
{% endif %}\
|
||||||
{% for group, commits in commits | group_by(attribute="group") %}
|
{% for group, commits in commits | group_by(attribute="group") %}
|
||||||
### {{ group | striptags | trim | upper_first }}
|
### {{ group | striptags | trim }}
|
||||||
{% for commit in commits %}
|
{% for commit in commits %}
|
||||||
- {% if commit.scope %}*({{ commit.scope }})* {% endif %}\
|
- {% if commit.scope %}*({{ commit.scope }})* {% endif %}\
|
||||||
{% if commit.breaking %}[**breaking**] {% endif %}\
|
{% if commit.breaking %}[**breaking**] {% endif %}\
|
||||||
{{ commit.message | upper_first }}\
|
{{ commit.message }}\
|
||||||
{% if commit.github.pr_number %} ([#{{ commit.github.pr_number }}](https://github.com/objz/rmcl/pull/{{ commit.github.pr_number }})){% endif %}\
|
{% if commit.github.pr_number %} ([#{{ commit.github.pr_number }}](https://github.com/objz/rmcl/pull/{{ commit.github.pr_number }})){% endif %}\
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
{% if github.contributors | filter(attribute="is_first_time", value=true) | length != 0 %}
|
{% if github.contributors | filter(attribute="is_first_time", value=true) | length != 0 %}
|
||||||
### New Contributors
|
### new contributors
|
||||||
{% for contributor in github.contributors | filter(attribute="is_first_time", value=true) %}
|
{% for contributor in github.contributors | filter(attribute="is_first_time", value=true) %}
|
||||||
- @{{ contributor.username }} made their first contribution\
|
- @{{ contributor.username }} made their first contribution\
|
||||||
{% if contributor.pr_number %} in [#{{ contributor.pr_number }}](https://github.com/objz/rmcl/pull/{{ contributor.pr_number }}){% endif %}\
|
{% if contributor.pr_number %} in [#{{ contributor.pr_number }}](https://github.com/objz/rmcl/pull/{{ contributor.pr_number }}){% endif %}\
|
||||||
@@ -68,21 +68,21 @@ protect_breaking_commits = false
|
|||||||
# Assigns commits to groups.
|
# Assigns commits to groups.
|
||||||
# Optionally sets the commit's scope and can decide to exclude commits from further processing.
|
# Optionally sets the commit's scope and can decide to exclude commits from further processing.
|
||||||
commit_parsers = [
|
commit_parsers = [
|
||||||
{ message = "^feat", group = "<!-- 0 -->Features" },
|
{ message = "^feat", group = "<!-- 0 -->features" },
|
||||||
{ message = "^fix", group = "<!-- 1 -->Bug Fixes" },
|
{ message = "^fix", group = "<!-- 1 -->bug fixes" },
|
||||||
{ message = "^doc", group = "<!-- 3 -->Documentation" },
|
{ message = "^doc", group = "<!-- 3 -->documentation" },
|
||||||
{ message = "^perf", group = "<!-- 4 -->Performance" },
|
{ message = "^perf", group = "<!-- 4 -->performance" },
|
||||||
{ message = "^refactor", group = "<!-- 2 -->Refactor" },
|
{ message = "^refactor", group = "<!-- 2 -->refactoring" },
|
||||||
{ message = "^style", group = "<!-- 5 -->Styling" },
|
{ message = "^style", group = "<!-- 5 -->styling" },
|
||||||
{ message = "^test", group = "<!-- 6 -->Testing" },
|
{ message = "^test", group = "<!-- 6 -->testing" },
|
||||||
{ message = "^chore\\(release\\): prepare for", skip = true },
|
{ message = "^chore\\(release\\): prepare for", skip = true },
|
||||||
{ message = "^chore\\(deps.*\\)", skip = true },
|
{ message = "^chore\\(deps.*\\)", skip = true },
|
||||||
{ message = "^chore\\(pr\\)", skip = true },
|
{ message = "^chore\\(pr\\)", skip = true },
|
||||||
{ message = "^chore\\(pull\\)", skip = true },
|
{ message = "^chore\\(pull\\)", skip = true },
|
||||||
{ message = "^chore|^ci", group = "<!-- 7 -->Miscellaneous Tasks" },
|
{ message = "^chore|^ci", group = "<!-- 7 -->maintenance" },
|
||||||
{ body = ".*security", group = "<!-- 8 -->Security" },
|
{ body = ".*security", group = "<!-- 8 -->security" },
|
||||||
{ message = "^revert", group = "<!-- 9 -->Revert" },
|
{ message = "^revert", group = "<!-- 9 -->reverts" },
|
||||||
{ message = ".*", group = "<!-- 10 -->Other" },
|
{ message = ".*", group = "<!-- 10 -->other changes" },
|
||||||
]
|
]
|
||||||
# Exclude commits that are not matched by any commit parser.
|
# Exclude commits that are not matched by any commit parser.
|
||||||
filter_commits = false
|
filter_commits = false
|
||||||
|
|||||||
+3
-3
@@ -16,9 +16,9 @@ targets = ["aarch64-apple-darwin", "aarch64-unknown-linux-gnu", "x86_64-apple-da
|
|||||||
# Path that installers should place binaries in
|
# Path that installers should place binaries in
|
||||||
install-path = "CARGO_HOME"
|
install-path = "CARGO_HOME"
|
||||||
# Publish jobs to run in CI
|
# Publish jobs to run in CI
|
||||||
publish-jobs = ["homebrew", "./publish-crates", "./publish-aur", "./publish-winget", "./publish-chocolatey"]
|
publish-jobs = ["homebrew", "./publish-crates", "./publish-aur", "./publish-winget"]
|
||||||
# Custom permissions for publish jobs
|
# Custom permissions for publish jobs
|
||||||
github-custom-job-permissions = { publish-crates = { contents = "read" }, publish-aur = { contents = "read" }, publish-winget = { contents = "read" }, publish-chocolatey = { contents = "read" } }
|
github-custom-job-permissions = { publish-crates = { contents = "read" }, publish-aur = { contents = "read" }, publish-winget = { contents = "read" } }
|
||||||
# Extra setup steps for release artifact builders
|
# Extra setup steps for release artifact builders
|
||||||
github-build-setup = "../dist-build-setup.yml"
|
github-build-setup = "../dist-build-setup.yml"
|
||||||
# Where to host releases
|
# Where to host releases
|
||||||
@@ -26,4 +26,4 @@ hosting = "github"
|
|||||||
# Whether to install an updater program
|
# Whether to install an updater program
|
||||||
install-updater = false
|
install-updater = false
|
||||||
# Allow custom edits to the generated CI file
|
# Allow custom edits to the generated CI file
|
||||||
allow-dirty = ["ci"]
|
allow-dirty = ["ci", "msi"]
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<package xmlns="http://schemas.microsoft.com/packaging/2015/06/nuspec.xsd">
|
|
||||||
<metadata>
|
|
||||||
<id>rmcl</id>
|
|
||||||
<version>0.0.0</version>
|
|
||||||
<packageSourceUrl>https://github.com/objz/rmcl</packageSourceUrl>
|
|
||||||
<owners>objz</owners>
|
|
||||||
<title>rmcl</title>
|
|
||||||
<authors>objz</authors>
|
|
||||||
<projectUrl>https://github.com/objz/rmcl</projectUrl>
|
|
||||||
<licenseUrl>https://github.com/objz/rmcl/blob/master/LICENSE</licenseUrl>
|
|
||||||
<requireLicenseAcceptance>false</requireLicenseAcceptance>
|
|
||||||
<projectSourceUrl>https://github.com/objz/rmcl</projectSourceUrl>
|
|
||||||
<docsUrl>https://github.com/objz/rmcl#readme</docsUrl>
|
|
||||||
<bugTrackerUrl>https://github.com/objz/rmcl/issues</bugTrackerUrl>
|
|
||||||
<tags>minecraft launcher cli tui rust</tags>
|
|
||||||
<summary>Minecraft launcher TUI</summary>
|
|
||||||
<description>A fully featured Minecraft launcher TUI with Microsoft account authentication, instance management, mod loaders, imports, content management, and launch support.</description>
|
|
||||||
</metadata>
|
|
||||||
<files>
|
|
||||||
<file src="tools\**" target="tools" />
|
|
||||||
</files>
|
|
||||||
</package>
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
VERIFICATION
|
|
||||||
|
|
||||||
This package downloads the official MSI from the GitHub release:
|
|
||||||
|
|
||||||
https://github.com/objz/rmcl/releases/download/__TAG__/rmcl-x86_64-pc-windows-msvc.msi
|
|
||||||
|
|
||||||
The SHA256 checksum is generated by cargo-dist and published next to the release asset:
|
|
||||||
|
|
||||||
https://github.com/objz/rmcl/releases/download/__TAG__/rmcl-x86_64-pc-windows-msvc.msi.sha256
|
|
||||||
|
|
||||||
Expected SHA256:
|
|
||||||
__CHECKSUM64__
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
$ErrorActionPreference = 'Stop'
|
|
||||||
|
|
||||||
$packageArgs = @{
|
|
||||||
packageName = $env:ChocolateyPackageName
|
|
||||||
fileType = 'msi'
|
|
||||||
url64bit = 'https://github.com/objz/rmcl/releases/download/__TAG__/rmcl-x86_64-pc-windows-msvc.msi'
|
|
||||||
softwareName = 'rmcl*'
|
|
||||||
checksum64 = '__CHECKSUM64__'
|
|
||||||
checksumType64 = 'sha256'
|
|
||||||
silentArgs = '/quiet /norestart'
|
|
||||||
validExitCodes = @(0, 3010, 1641)
|
|
||||||
}
|
|
||||||
|
|
||||||
Install-ChocolateyPackage @packageArgs
|
|
||||||
@@ -20,11 +20,16 @@ pkgver() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
build() {
|
build() {
|
||||||
|
export CARGO_TARGET_DIR="$srcdir/target"
|
||||||
|
rm -rf "$CARGO_TARGET_DIR"
|
||||||
cd "$srcdir/rmcl"
|
cd "$srcdir/rmcl"
|
||||||
cargo build --release --locked
|
cargo build --release --locked
|
||||||
}
|
}
|
||||||
|
|
||||||
check() {
|
check() {
|
||||||
|
export CARGO_TARGET_DIR="$srcdir/target"
|
||||||
|
export XDG_CONFIG_HOME="$srcdir/xdg-config"
|
||||||
|
mkdir -p "$XDG_CONFIG_HOME"
|
||||||
cd "$srcdir/rmcl"
|
cd "$srcdir/rmcl"
|
||||||
cargo test --release --locked
|
cargo test --release --locked
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,11 +15,16 @@ source=("${url}/archive/v${pkgver}.tar.gz")
|
|||||||
sha256sums=('SKIP')
|
sha256sums=('SKIP')
|
||||||
|
|
||||||
build() {
|
build() {
|
||||||
|
export CARGO_TARGET_DIR="$srcdir/target"
|
||||||
|
rm -rf "$CARGO_TARGET_DIR"
|
||||||
cd "$srcdir/rmcl-${pkgver}"
|
cd "$srcdir/rmcl-${pkgver}"
|
||||||
cargo build --release --locked
|
cargo build --release --locked
|
||||||
}
|
}
|
||||||
|
|
||||||
check() {
|
check() {
|
||||||
|
export CARGO_TARGET_DIR="$srcdir/target"
|
||||||
|
export XDG_CONFIG_HOME="$srcdir/xdg-config"
|
||||||
|
mkdir -p "$XDG_CONFIG_HOME"
|
||||||
cd "$srcdir/rmcl-${pkgver}"
|
cd "$srcdir/rmcl-${pkgver}"
|
||||||
cargo test --release --locked
|
cargo test --release --locked
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -69,7 +69,7 @@
|
|||||||
|
|
||||||
<Package Id='*'
|
<Package Id='*'
|
||||||
Keywords='Installer'
|
Keywords='Installer'
|
||||||
Description='A fully featured Minecraft launcher TUI'
|
Description='A fully featured Minecraft TUI launcher'
|
||||||
Manufacturer='objz'
|
Manufacturer='objz'
|
||||||
InstallerVersion='450'
|
InstallerVersion='450'
|
||||||
Languages='1033'
|
Languages='1033'
|
||||||
@@ -170,7 +170,7 @@
|
|||||||
The product icon is the graphic that appears in the Add/Remove
|
The product icon is the graphic that appears in the Add/Remove
|
||||||
Programs control panel for the application.
|
Programs control panel for the application.
|
||||||
-->
|
-->
|
||||||
<!--<Icon Id='ProductICO' SourceFile='wix\Product.ico'/>-->
|
<!--<Icon Id='ProductICO' SourceFile='pkg\wix\Product.ico'/>-->
|
||||||
<!--<Property Id='ARPPRODUCTICON' Value='ProductICO' />-->
|
<!--<Property Id='ARPPRODUCTICON' Value='ProductICO' />-->
|
||||||
|
|
||||||
<Property Id='ARPHELPLINK' Value='https://github.com/objz/rmcl'/>
|
<Property Id='ARPHELPLINK' Value='https://github.com/objz/rmcl'/>
|
||||||
@@ -210,7 +210,7 @@
|
|||||||
|
|
||||||
The banner BMP dimensions are 493 x 58 pixels.
|
The banner BMP dimensions are 493 x 58 pixels.
|
||||||
-->
|
-->
|
||||||
<!--<WixVariable Id='WixUIBannerBmp' Value='wix\Banner.bmp'/>-->
|
<!--<WixVariable Id='WixUIBannerBmp' Value='pkg\wix\Banner.bmp'/>-->
|
||||||
|
|
||||||
|
|
||||||
<!--
|
<!--
|
||||||
@@ -221,7 +221,7 @@
|
|||||||
|
|
||||||
The dialog BMP dimensions are 493 x 312 pixels.
|
The dialog BMP dimensions are 493 x 312 pixels.
|
||||||
-->
|
-->
|
||||||
<!--<WixVariable Id='WixUIDialogBmp' Value='wix\Dialog.bmp'/>-->
|
<!--<WixVariable Id='WixUIDialogBmp' Value='pkg\wix\Dialog.bmp'/>-->
|
||||||
|
|
||||||
</Product>
|
</Product>
|
||||||
|
|
||||||
+58
-189
@@ -39,9 +39,27 @@ impl AccountStore {
|
|||||||
pub fn load() -> Self {
|
pub fn load() -> Self {
|
||||||
let path = account_store_path();
|
let path = account_store_path();
|
||||||
let accounts = match std::fs::read_to_string(&path) {
|
let accounts = match std::fs::read_to_string(&path) {
|
||||||
Ok(content) => serde_json::from_str(&content).unwrap_or_default(),
|
Ok(content) => match serde_json::from_str(&content) {
|
||||||
Err(_) => Vec::new(),
|
Ok(accounts) => accounts,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!("Failed to parse accounts file {}: {}", path.display(), e);
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||||
|
tracing::debug!("No accounts file at {}", path.display());
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!("Failed to read accounts file {}: {}", path.display(), e);
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
tracing::debug!(
|
||||||
|
"Loaded {} account(s) from {}",
|
||||||
|
accounts.len(),
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
Self { accounts, path }
|
Self { accounts, path }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,7 +73,17 @@ impl AccountStore {
|
|||||||
match serde_json::to_string_pretty(&self.accounts) {
|
match serde_json::to_string_pretty(&self.accounts) {
|
||||||
Ok(json) => {
|
Ok(json) => {
|
||||||
if let Err(e) = std::fs::write(&self.path, json) {
|
if let Err(e) = std::fs::write(&self.path, json) {
|
||||||
tracing::error!("Failed to write accounts file: {}", e);
|
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),
|
Err(e) => tracing::error!("Failed to serialize accounts: {}", e),
|
||||||
@@ -73,9 +101,18 @@ impl AccountStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_active(&mut self, index: usize) {
|
pub fn set_active(&mut self, index: usize) {
|
||||||
|
let username = self
|
||||||
|
.accounts
|
||||||
|
.get(index)
|
||||||
|
.map(|account| account.username.clone());
|
||||||
for (i, acc) in self.accounts.iter_mut().enumerate() {
|
for (i, acc) in self.accounts.iter_mut().enumerate() {
|
||||||
acc.active = i == index;
|
acc.active = i == index;
|
||||||
}
|
}
|
||||||
|
if let Some(username) = username {
|
||||||
|
tracing::info!("Selected account '{}'", username);
|
||||||
|
} else {
|
||||||
|
tracing::warn!("Tried to select missing account index {}", index);
|
||||||
|
}
|
||||||
self.save();
|
self.save();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,22 +120,38 @@ impl AccountStore {
|
|||||||
// first account added auto-becomes active so there's always a selection.
|
// first account added auto-becomes active so there's always a selection.
|
||||||
pub fn add(&mut self, account: Account) {
|
pub fn add(&mut self, account: Account) {
|
||||||
let uuid = &account.uuid;
|
let uuid = &account.uuid;
|
||||||
|
let replaced = self.accounts.iter().any(|a| a.uuid == *uuid);
|
||||||
|
let account_type = account.account_type.clone();
|
||||||
|
let username = account.username.clone();
|
||||||
self.accounts.retain(|a| a.uuid != *uuid);
|
self.accounts.retain(|a| a.uuid != *uuid);
|
||||||
let mut account = account;
|
let mut account = account;
|
||||||
if self.accounts.is_empty() {
|
if self.accounts.is_empty() {
|
||||||
account.active = true;
|
account.active = true;
|
||||||
}
|
}
|
||||||
self.accounts.push(account);
|
self.accounts.push(account);
|
||||||
|
tracing::info!(
|
||||||
|
"{} {:?} account '{}'",
|
||||||
|
if replaced { "Updated" } else { "Added" },
|
||||||
|
account_type,
|
||||||
|
username
|
||||||
|
);
|
||||||
self.save();
|
self.save();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn remove(&mut self, index: usize) {
|
pub fn remove(&mut self, index: usize) {
|
||||||
if index >= self.accounts.len() {
|
if index >= self.accounts.len() {
|
||||||
|
tracing::warn!("Tried to remove missing account index {}", index);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let account = self.accounts.remove(index);
|
let account = self.accounts.remove(index);
|
||||||
|
tracing::info!(
|
||||||
|
"Removed {:?} account '{}'",
|
||||||
|
account.account_type,
|
||||||
|
account.username
|
||||||
|
);
|
||||||
if account.active && !self.accounts.is_empty() {
|
if account.active && !self.accounts.is_empty() {
|
||||||
self.accounts[0].active = true;
|
self.accounts[0].active = true;
|
||||||
|
tracing::debug!("Activated fallback account '{}'", self.accounts[0].username);
|
||||||
}
|
}
|
||||||
self.save();
|
self.save();
|
||||||
}
|
}
|
||||||
@@ -139,189 +192,5 @@ pub fn create_offline_account(username: &str) -> Account {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/accounts.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn offline_uuid_is_valid_format() {
|
|
||||||
let uuid = offline_uuid("Steve");
|
|
||||||
let parts: Vec<&str> = uuid.split('-').collect();
|
|
||||||
assert_eq!(parts.len(), 5, "UUID must have 5 dash-separated parts");
|
|
||||||
assert_eq!(parts[0].len(), 8);
|
|
||||||
assert_eq!(parts[1].len(), 4);
|
|
||||||
assert_eq!(parts[2].len(), 4);
|
|
||||||
assert_eq!(parts[3].len(), 4);
|
|
||||||
assert_eq!(parts[4].len(), 12);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn offline_uuid_version_3_marker() {
|
|
||||||
let uuid = offline_uuid("Steve");
|
|
||||||
assert!(uuid.split('-').nth(2).unwrap().starts_with('3'));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn offline_uuid_variant_bit_set() {
|
|
||||||
let uuid = offline_uuid("Steve");
|
|
||||||
let part3 = uuid.split('-').nth(3).unwrap();
|
|
||||||
let first_nibble = u8::from_str_radix(&part3[..1], 16).unwrap();
|
|
||||||
assert!((0x8..=0xb).contains(&first_nibble));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn offline_uuid_deterministic() {
|
|
||||||
assert_eq!(offline_uuid("Steve"), offline_uuid("Steve"));
|
|
||||||
assert_eq!(offline_uuid("Alex"), offline_uuid("Alex"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn offline_uuid_different_for_different_names() {
|
|
||||||
assert_ne!(offline_uuid("Steve"), offline_uuid("Alex"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn create_offline_account_fields() {
|
|
||||||
let acc = create_offline_account("TestPlayer");
|
|
||||||
assert_eq!(acc.username, "TestPlayer");
|
|
||||||
assert_eq!(acc.account_type, AccountType::Offline);
|
|
||||||
assert!(!acc.active);
|
|
||||||
assert!(acc.refresh_token.is_none());
|
|
||||||
assert!(!acc.uuid.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
fn make_store(dir: &std::path::Path) -> AccountStore {
|
|
||||||
AccountStore {
|
|
||||||
accounts: Vec::new(),
|
|
||||||
path: dir.join("accounts.json"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn dummy_account(name: &str) -> Account {
|
|
||||||
create_offline_account(name)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn microsoft_account(name: &str) -> Account {
|
|
||||||
Account {
|
|
||||||
uuid: format!("00000000-0000-0000-0000-{:012}", name.len()),
|
|
||||||
username: name.to_owned(),
|
|
||||||
account_type: AccountType::Microsoft,
|
|
||||||
active: false,
|
|
||||||
refresh_token: Some("refresh".to_owned()),
|
|
||||||
cached_mc_token: None,
|
|
||||||
cached_mc_token_expires_at: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_add_first_becomes_active() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = make_store(tmp.path());
|
|
||||||
store.add(dummy_account("Alice"));
|
|
||||||
assert_eq!(store.accounts.len(), 1);
|
|
||||||
assert!(store.accounts[0].active);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_add_second_stays_inactive() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = make_store(tmp.path());
|
|
||||||
store.add(dummy_account("Alice"));
|
|
||||||
store.add(dummy_account("Bob"));
|
|
||||||
assert_eq!(store.accounts.len(), 2);
|
|
||||||
assert!(store.accounts[0].active);
|
|
||||||
assert!(!store.accounts[1].active);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_add_duplicate_uuid_replaces() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = make_store(tmp.path());
|
|
||||||
store.add(dummy_account("Alice"));
|
|
||||||
let mut dup = dummy_account("Alice");
|
|
||||||
dup.username = "AliceRenamed".to_owned();
|
|
||||||
dup.uuid = store.accounts[0].uuid.clone();
|
|
||||||
store.add(dup);
|
|
||||||
assert_eq!(store.accounts.len(), 1);
|
|
||||||
assert_eq!(store.accounts[0].username, "AliceRenamed");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_active_account_none_when_empty() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let store = make_store(tmp.path());
|
|
||||||
assert!(store.active_account().is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_has_microsoft_account_when_one_exists() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = make_store(tmp.path());
|
|
||||||
store.add(dummy_account("Offline"));
|
|
||||||
assert!(!store.has_microsoft_account());
|
|
||||||
|
|
||||||
store.add(microsoft_account("Owner"));
|
|
||||||
assert!(store.has_microsoft_account());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_active_account_returns_active() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = make_store(tmp.path());
|
|
||||||
store.add(dummy_account("Alice"));
|
|
||||||
store.add(dummy_account("Bob"));
|
|
||||||
let active = store.active_account().unwrap();
|
|
||||||
assert_eq!(active.username, "Alice");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_set_active_changes_active() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = make_store(tmp.path());
|
|
||||||
store.add(dummy_account("Alice"));
|
|
||||||
store.add(dummy_account("Bob"));
|
|
||||||
store.set_active(1);
|
|
||||||
assert!(!store.accounts[0].active);
|
|
||||||
assert!(store.accounts[1].active);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_remove_activates_first_remaining() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = make_store(tmp.path());
|
|
||||||
store.add(dummy_account("Alice"));
|
|
||||||
store.add(dummy_account("Bob"));
|
|
||||||
store.remove(0);
|
|
||||||
assert_eq!(store.accounts.len(), 1);
|
|
||||||
assert_eq!(store.accounts[0].username, "Bob");
|
|
||||||
assert!(store.accounts[0].active);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_remove_out_of_bounds_noop() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = make_store(tmp.path());
|
|
||||||
store.add(dummy_account("Alice"));
|
|
||||||
store.remove(5);
|
|
||||||
assert_eq!(store.accounts.len(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_save_and_reload() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = make_store(tmp.path());
|
|
||||||
store.add(dummy_account("Alice"));
|
|
||||||
store.add(dummy_account("Bob"));
|
|
||||||
store.save();
|
|
||||||
|
|
||||||
let reloaded = AccountStore {
|
|
||||||
accounts: serde_json::from_str(
|
|
||||||
&std::fs::read_to_string(tmp.path().join("accounts.json")).unwrap(),
|
|
||||||
)
|
|
||||||
.unwrap(),
|
|
||||||
path: tmp.path().join("accounts.json"),
|
|
||||||
};
|
|
||||||
assert_eq!(reloaded.accounts.len(), 2);
|
|
||||||
assert_eq!(reloaded.accounts[0].username, "Alice");
|
|
||||||
assert!(reloaded.accounts[0].active);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+20
-49
@@ -34,6 +34,19 @@ struct McProfile {
|
|||||||
name: String,
|
name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn normalize_profile_uuid(id: &str) -> Option<String> {
|
||||||
|
(id.len() == 32 && id.bytes().all(|byte| byte.is_ascii_hexdigit())).then(|| {
|
||||||
|
format!(
|
||||||
|
"{}-{}-{}-{}-{}",
|
||||||
|
&id[..8],
|
||||||
|
&id[8..12],
|
||||||
|
&id[12..16],
|
||||||
|
&id[16..20],
|
||||||
|
&id[20..32],
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// shared slot so the TUI can poll for the device code to show the user
|
// 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>>>> =
|
pub static DEVICE_CODE_DISPLAY: LazyLock<Arc<Mutex<Option<DeviceCodeInfo>>>> =
|
||||||
LazyLock::new(|| Arc::new(Mutex::new(None)));
|
LazyLock::new(|| Arc::new(Mutex::new(None)));
|
||||||
@@ -61,6 +74,7 @@ async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
|
|||||||
user_code: details.user_code().secret().to_owned(),
|
user_code: details.user_code().secret().to_owned(),
|
||||||
verification_uri: details.verification_uri().to_string(),
|
verification_uri: details.verification_uri().to_string(),
|
||||||
});
|
});
|
||||||
|
crate::feedback::request_redraw();
|
||||||
}
|
}
|
||||||
|
|
||||||
let token = oauth_client
|
let token = oauth_client
|
||||||
@@ -85,6 +99,7 @@ pub fn start_microsoft_auth() -> Arc<Mutex<Option<AuthResult>>> {
|
|||||||
let outcome = run_full_auth_flow().await;
|
let outcome = run_full_auth_flow().await;
|
||||||
if let Ok(mut slot) = result_clone.lock() {
|
if let Ok(mut slot) = result_clone.lock() {
|
||||||
*slot = Some(outcome);
|
*slot = Some(outcome);
|
||||||
|
crate::feedback::request_redraw();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -134,17 +149,9 @@ async fn exchange_and_build_account(
|
|||||||
};
|
};
|
||||||
|
|
||||||
// mojang returns uuids without dashes
|
// mojang returns uuids without dashes
|
||||||
let uuid = if profile.id.len() == 32 {
|
let uuid = match normalize_profile_uuid(&profile.id) {
|
||||||
format!(
|
Some(uuid) => uuid,
|
||||||
"{}-{}-{}-{}-{}",
|
None => return AuthResult::Error("Profile returned an invalid UUID".to_owned()),
|
||||||
&profile.id[..8],
|
|
||||||
&profile.id[8..12],
|
|
||||||
&profile.id[12..16],
|
|
||||||
&profile.id[16..20],
|
|
||||||
&profile.id[20..32],
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
profile.id.clone()
|
|
||||||
};
|
};
|
||||||
|
|
||||||
AuthResult::Success(Account {
|
AuthResult::Success(Account {
|
||||||
@@ -235,41 +242,5 @@ pub async fn refresh_and_get_token(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/oauth.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
fn microsoft_account(cached_mc_token_expires_at: Option<i64>) -> Account {
|
|
||||||
Account {
|
|
||||||
uuid: "00000000-0000-0000-0000-000000000000".to_owned(),
|
|
||||||
username: "TestPlayer".to_owned(),
|
|
||||||
account_type: AccountType::Microsoft,
|
|
||||||
active: true,
|
|
||||||
refresh_token: Some("refresh".to_owned()),
|
|
||||||
cached_mc_token: Some("cached".to_owned()),
|
|
||||||
cached_mc_token_expires_at,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn cached_mc_token_is_valid_before_refresh_margin() {
|
|
||||||
let now = 1_000;
|
|
||||||
let account = microsoft_account(Some(now + MC_TOKEN_CACHE_REFRESH_MARGIN_SECS + 1));
|
|
||||||
|
|
||||||
assert_eq!(valid_cached_mc_token(&account, now), Some("cached"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn cached_mc_token_expires_inside_refresh_margin() {
|
|
||||||
let now = 1_000;
|
|
||||||
let account = microsoft_account(Some(now + MC_TOKEN_CACHE_REFRESH_MARGIN_SECS));
|
|
||||||
|
|
||||||
assert!(valid_cached_mc_token(&account, now).is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn cached_mc_token_requires_expiry() {
|
|
||||||
let account = microsoft_account(None);
|
|
||||||
|
|
||||||
assert!(valid_cached_mc_token(&account, 1_000).is_none());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
use super::*;
|
||||||
|
|
||||||
|
impl AccountStore {
|
||||||
|
pub(crate) fn empty_for_test(path: PathBuf) -> Self {
|
||||||
|
Self {
|
||||||
|
accounts: Vec::new(),
|
||||||
|
path,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn offline_uuid_has_valid_v3_shape() {
|
||||||
|
let uuid = offline_uuid("Steve");
|
||||||
|
let parts: Vec<&str> = uuid.split('-').collect();
|
||||||
|
assert_eq!(parts.len(), 5, "UUID must have 5 dash-separated parts");
|
||||||
|
assert_eq!(parts[0].len(), 8);
|
||||||
|
assert_eq!(parts[1].len(), 4);
|
||||||
|
assert_eq!(parts[2].len(), 4);
|
||||||
|
assert_eq!(parts[3].len(), 4);
|
||||||
|
assert_eq!(parts[4].len(), 12);
|
||||||
|
assert!(parts[2].starts_with('3'));
|
||||||
|
let first_nibble = u8::from_str_radix(&parts[3][..1], 16).unwrap();
|
||||||
|
assert!((0x8..=0xb).contains(&first_nibble));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn offline_uuid_is_pinned_for_known_names() {
|
||||||
|
assert_eq!(
|
||||||
|
offline_uuid("Steve"),
|
||||||
|
"7e0a3689-ed7c-347c-87cc-3689ed7c47cc"
|
||||||
|
);
|
||||||
|
assert_eq!(offline_uuid("Alex"), "a13d42a3-454f-3e39-a392-42a3454fe392");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn offline_uuid_different_for_different_names() {
|
||||||
|
assert_ne!(offline_uuid("Steve"), offline_uuid("Alex"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn create_offline_account_fields() {
|
||||||
|
let acc = create_offline_account("TestPlayer");
|
||||||
|
assert_eq!(acc.username, "TestPlayer");
|
||||||
|
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"));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn make_store(dir: &std::path::Path) -> AccountStore {
|
||||||
|
AccountStore {
|
||||||
|
accounts: Vec::new(),
|
||||||
|
path: dir.join("accounts.json"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn microsoft_account(name: &str) -> Account {
|
||||||
|
Account {
|
||||||
|
uuid: format!("00000000-0000-0000-0000-{:012}", name.len()),
|
||||||
|
username: name.to_owned(),
|
||||||
|
account_type: AccountType::Microsoft,
|
||||||
|
active: false,
|
||||||
|
refresh_token: Some("refresh".to_owned()),
|
||||||
|
cached_mc_token: None,
|
||||||
|
cached_mc_token_expires_at: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_add_first_becomes_active() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = make_store(tmp.path());
|
||||||
|
store.add(create_offline_account("Alice"));
|
||||||
|
assert_eq!(store.accounts.len(), 1);
|
||||||
|
assert!(store.accounts[0].active);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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"));
|
||||||
|
assert_eq!(store.accounts.len(), 2);
|
||||||
|
assert!(store.accounts[0].active);
|
||||||
|
assert!(!store.accounts[1].active);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_add_duplicate_uuid_replaces() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = make_store(tmp.path());
|
||||||
|
store.add(create_offline_account("Alice"));
|
||||||
|
let mut dup = create_offline_account("Alice");
|
||||||
|
dup.username = "AliceRenamed".to_owned();
|
||||||
|
dup.uuid = store.accounts[0].uuid.clone();
|
||||||
|
store.add(dup);
|
||||||
|
assert_eq!(store.accounts.len(), 1);
|
||||||
|
assert_eq!(store.accounts[0].username, "AliceRenamed");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_active_account_none_when_empty() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let store = make_store(tmp.path());
|
||||||
|
assert!(store.active_account().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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"));
|
||||||
|
assert!(!store.has_microsoft_account());
|
||||||
|
|
||||||
|
store.add(microsoft_account("Owner"));
|
||||||
|
assert!(store.has_microsoft_account());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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"));
|
||||||
|
let active = store.active_account().unwrap();
|
||||||
|
assert_eq!(active.username, "Alice");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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);
|
||||||
|
assert!(!store.accounts[0].active);
|
||||||
|
assert!(store.accounts[1].active);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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);
|
||||||
|
assert_eq!(store.accounts.len(), 1);
|
||||||
|
assert_eq!(store.accounts[0].username, "Bob");
|
||||||
|
assert!(store.accounts[0].active);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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);
|
||||||
|
assert_eq!(store.accounts.len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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();
|
||||||
|
|
||||||
|
let reloaded = AccountStore {
|
||||||
|
accounts: serde_json::from_str(
|
||||||
|
&std::fs::read_to_string(tmp.path().join("accounts.json")).unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
path: tmp.path().join("accounts.json"),
|
||||||
|
};
|
||||||
|
assert_eq!(reloaded.accounts.len(), 2);
|
||||||
|
assert_eq!(reloaded.accounts[0].username, "Alice");
|
||||||
|
assert!(reloaded.accounts[0].active);
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn microsoft_account(cached_mc_token_expires_at: Option<i64>) -> Account {
|
||||||
|
Account {
|
||||||
|
uuid: "00000000-0000-0000-0000-000000000000".to_owned(),
|
||||||
|
username: "TestPlayer".to_owned(),
|
||||||
|
account_type: AccountType::Microsoft,
|
||||||
|
active: true,
|
||||||
|
refresh_token: Some("refresh".to_owned()),
|
||||||
|
cached_mc_token: Some("cached".to_owned()),
|
||||||
|
cached_mc_token_expires_at,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cached_mc_token_is_valid_before_refresh_margin() {
|
||||||
|
let now = 1_000;
|
||||||
|
let account = microsoft_account(Some(now + MC_TOKEN_CACHE_REFRESH_MARGIN_SECS + 1));
|
||||||
|
|
||||||
|
assert_eq!(valid_cached_mc_token(&account, now), Some("cached"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cached_mc_token_expires_inside_refresh_margin() {
|
||||||
|
let now = 1_000;
|
||||||
|
let account = microsoft_account(Some(now + MC_TOKEN_CACHE_REFRESH_MARGIN_SECS));
|
||||||
|
|
||||||
|
assert!(valid_cached_mc_token(&account, now).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cached_mc_token_requires_expiry() {
|
||||||
|
let account = microsoft_account(None);
|
||||||
|
|
||||||
|
assert!(valid_cached_mc_token(&account, 1_000).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn profile_uuid_is_normalized_without_slicing_unicode() {
|
||||||
|
assert_eq!(
|
||||||
|
normalize_profile_uuid("0123456789abcdef0123456789abcdef"),
|
||||||
|
Some("01234567-89ab-cdef-0123-456789abcdef".to_owned())
|
||||||
|
);
|
||||||
|
|
||||||
|
let unicode_id = format!("{}é{}", "a".repeat(7), "b".repeat(23));
|
||||||
|
assert_eq!(unicode_id.len(), 32);
|
||||||
|
assert_eq!(normalize_profile_uuid(&unicode_id), None);
|
||||||
|
assert_eq!(
|
||||||
|
normalize_profile_uuid("not-a-valid-minecraft-profile-id"),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
}
|
||||||
+4
-78
@@ -19,22 +19,6 @@ pub async fn handle_account(matches: &ArgMatches) -> CliResult {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// trait indirection so a mock store can be swapped in for tests
|
|
||||||
trait AccountStoreLike {
|
|
||||||
fn has_microsoft_account(&self) -> bool;
|
|
||||||
fn add_account(&mut self, account: Account);
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AccountStoreLike for AccountStore {
|
|
||||||
fn has_microsoft_account(&self) -> bool {
|
|
||||||
AccountStore::has_microsoft_account(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn add_account(&mut self, account: Account) {
|
|
||||||
self.add(account);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn list_accounts() -> CliResult {
|
fn list_accounts() -> CliResult {
|
||||||
let store = AccountStore::load();
|
let store = AccountStore::load();
|
||||||
let rows = store
|
let rows = store
|
||||||
@@ -109,7 +93,7 @@ async fn add_microsoft_account() -> CliResult {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_offline_account<T: AccountStoreLike>(store: &mut T, username: &str) -> CliResult {
|
fn add_offline_account(store: &mut AccountStore, username: &str) -> CliResult {
|
||||||
let username = username.trim();
|
let username = username.trim();
|
||||||
if username.is_empty() {
|
if username.is_empty() {
|
||||||
return Err(io::Error::other("offline username cannot be empty").into());
|
return Err(io::Error::other("offline username cannot be empty").into());
|
||||||
@@ -121,7 +105,7 @@ fn add_offline_account<T: AccountStoreLike>(store: &mut T, username: &str) -> Cl
|
|||||||
.into());
|
.into());
|
||||||
}
|
}
|
||||||
|
|
||||||
store.add_account(crate::auth::create_offline_account(username));
|
store.add(crate::auth::create_offline_account(username));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -160,63 +144,5 @@ fn find_account_index(accounts: &[Account], username: &str) -> Option<usize> {
|
|||||||
use super::utils::{confirm, required_arg};
|
use super::utils::{confirm, required_arg};
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/account.rs"]
|
||||||
use super::{AccountStoreLike, add_offline_account};
|
mod tests;
|
||||||
use crate::auth::{Account, AccountType};
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
struct MockStore {
|
|
||||||
accounts: Vec<Account>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AccountStoreLike for MockStore {
|
|
||||||
fn has_microsoft_account(&self) -> bool {
|
|
||||||
self.accounts
|
|
||||||
.iter()
|
|
||||||
.any(|account| account.account_type == AccountType::Microsoft)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn add_account(&mut self, account: Account) {
|
|
||||||
self.accounts.push(account);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn microsoft_account() -> Account {
|
|
||||||
Account {
|
|
||||||
uuid: "00000000-0000-0000-0000-000000000001".to_owned(),
|
|
||||||
username: "Owner".to_owned(),
|
|
||||||
account_type: AccountType::Microsoft,
|
|
||||||
active: false,
|
|
||||||
refresh_token: Some("refresh".to_owned()),
|
|
||||||
cached_mc_token: None,
|
|
||||||
cached_mc_token_expires_at: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn creates_offline_account_after_microsoft_account_exists() {
|
|
||||||
let mut store = MockStore::default();
|
|
||||||
store.add_account(microsoft_account());
|
|
||||||
add_offline_account(&mut store, "Steve").expect("offline account should be added");
|
|
||||||
|
|
||||||
assert_eq!(store.accounts.len(), 2);
|
|
||||||
assert_eq!(store.accounts[1].username, "Steve");
|
|
||||||
assert_eq!(store.accounts[1].account_type, AccountType::Offline);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_offline_account_before_microsoft_account_exists() {
|
|
||||||
let mut store = MockStore::default();
|
|
||||||
let err = add_offline_account(&mut store, "Steve")
|
|
||||||
.expect_err("offline account should require a microsoft account");
|
|
||||||
|
|
||||||
assert!(err.to_string().contains("Microsoft account"));
|
|
||||||
assert!(store.accounts.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_empty_offline_username() {
|
|
||||||
let mut store = MockStore::default();
|
|
||||||
assert!(add_offline_account(&mut store, " ").is_err());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+4
-32
@@ -8,7 +8,7 @@ use clap::ArgMatches;
|
|||||||
|
|
||||||
use super::utils::{require_instance, required_arg};
|
use super::utils::{require_instance, required_arg};
|
||||||
use crate::cli::output::print_table;
|
use crate::cli::output::print_table;
|
||||||
use crate::instance::ContentEntry;
|
use crate::instance::content::entry::ContentEntry;
|
||||||
|
|
||||||
type CliResult = Result<(), Box<dyn std::error::Error>>;
|
type CliResult = Result<(), Box<dyn std::error::Error>>;
|
||||||
type Scanner = fn(&Path, &str) -> Vec<ContentEntry>;
|
type Scanner = fn(&Path, &str) -> Vec<ContentEntry>;
|
||||||
@@ -106,7 +106,7 @@ fn toggle_entry(
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
crate::instance::content::mods::toggle_entry(entry)?;
|
crate::instance::content::entry::toggle_entry(entry)?;
|
||||||
println!(
|
println!(
|
||||||
"{}d '{}'.",
|
"{}d '{}'.",
|
||||||
if should_enable { "Enable" } else { "Disable" },
|
if should_enable { "Enable" } else { "Disable" },
|
||||||
@@ -116,33 +116,5 @@ fn toggle_entry(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/content.rs"]
|
||||||
use super::find_entry_by_stem;
|
mod tests;
|
||||||
use crate::instance::ContentEntry;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
fn entry(file_stem: &str) -> ContentEntry {
|
|
||||||
ContentEntry {
|
|
||||||
file_stem: file_stem.to_string(),
|
|
||||||
name: file_stem.to_string(),
|
|
||||||
description: String::new(),
|
|
||||||
enabled: true,
|
|
||||||
icon_bytes: None,
|
|
||||||
path: PathBuf::from(file_stem),
|
|
||||||
icon_lines: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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");
|
|
||||||
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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+27
-15
@@ -39,18 +39,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
|||||||
.await
|
.await
|
||||||
.map_err(|e| format!("Failed to fetch versions: {e}"))?;
|
.map_err(|e| format!("Failed to fetch versions: {e}"))?;
|
||||||
|
|
||||||
if versions.is_empty() {
|
let version = select_version(&versions, override_version.map(String::as_str))?;
|
||||||
return Err("No versions found for this modpack".into());
|
|
||||||
}
|
|
||||||
|
|
||||||
let version = if let Some(version_name) = override_version {
|
|
||||||
versions
|
|
||||||
.iter()
|
|
||||||
.find(|v| v.version_number == *version_name || v.name == *version_name)
|
|
||||||
.ok_or_else(|| format!("Version '{version_name}' not found"))?
|
|
||||||
} else {
|
|
||||||
&versions[0]
|
|
||||||
};
|
|
||||||
|
|
||||||
println!(
|
println!(
|
||||||
"Using version {} ({})",
|
"Using version {} ({})",
|
||||||
@@ -58,7 +47,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
|||||||
version.game_versions.first().unwrap_or(&"?".to_string())
|
version.game_versions.first().unwrap_or(&"?".to_string())
|
||||||
);
|
);
|
||||||
|
|
||||||
let tmp_dir = manager.meta_dir.join("tmp");
|
let tmp_dir = crate::storage::MetadataPaths::new(&manager.meta_dir).temporary();
|
||||||
std::fs::create_dir_all(&tmp_dir)?;
|
std::fs::create_dir_all(&tmp_dir)?;
|
||||||
modrinth::download_mrpack(&client, version, &tmp_dir)
|
modrinth::download_mrpack(&client, version, &tmp_dir)
|
||||||
.await
|
.await
|
||||||
@@ -79,7 +68,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
|||||||
version.game_versions.first().unwrap_or(&"?".to_string())
|
version.game_versions.first().unwrap_or(&"?".to_string())
|
||||||
);
|
);
|
||||||
|
|
||||||
let tmp_dir = manager.meta_dir.join("tmp");
|
let tmp_dir = crate::storage::MetadataPaths::new(&manager.meta_dir).temporary();
|
||||||
std::fs::create_dir_all(&tmp_dir)?;
|
std::fs::create_dir_all(&tmp_dir)?;
|
||||||
modrinth::download_mrpack(&client, &version, &tmp_dir)
|
modrinth::download_mrpack(&client, &version, &tmp_dir)
|
||||||
.await
|
.await
|
||||||
@@ -95,7 +84,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
println!(
|
println!(
|
||||||
"Importing '{}' — {} {} ({} mods, {} overrides)",
|
"Importing '{}' - {} {} ({} mods, {} overrides)",
|
||||||
summary.name,
|
summary.name,
|
||||||
summary.game_version,
|
summary.game_version,
|
||||||
summary.loader,
|
summary.loader,
|
||||||
@@ -110,3 +99,26 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
|||||||
println!("Instance '{}' created successfully.", config.name);
|
println!("Instance '{}' created successfully.", config.name);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn select_version<'a>(
|
||||||
|
versions: &'a [modrinth::VersionInfo],
|
||||||
|
requested: Option<&str>,
|
||||||
|
) -> Result<&'a modrinth::VersionInfo, String> {
|
||||||
|
requested.map_or_else(
|
||||||
|
|| {
|
||||||
|
versions
|
||||||
|
.first()
|
||||||
|
.ok_or_else(|| "No versions found for this modpack".to_owned())
|
||||||
|
},
|
||||||
|
|name| {
|
||||||
|
versions
|
||||||
|
.iter()
|
||||||
|
.find(|version| version.version_number == name || version.name == name)
|
||||||
|
.ok_or_else(|| format!("Version '{name}' not found"))
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "tests/import.rs"]
|
||||||
|
mod tests;
|
||||||
+83
-25
@@ -7,10 +7,11 @@ use clap::ArgMatches;
|
|||||||
|
|
||||||
use super::utils::{confirm, required_arg};
|
use super::utils::{confirm, required_arg};
|
||||||
use crate::cli::output::{format_datetime, print_table};
|
use crate::cli::output::{format_datetime, print_table};
|
||||||
|
use crate::instance::runtime::RunState;
|
||||||
use crate::instance::{InstanceManager, ModLoader};
|
use crate::instance::{InstanceManager, ModLoader};
|
||||||
use crate::running::RunState;
|
|
||||||
|
|
||||||
type CliResult = Result<(), Box<dyn std::error::Error>>;
|
type CliResult = Result<(), Box<dyn std::error::Error>>;
|
||||||
|
const LOCAL_CONFIG_PROFILE: &str = "instance default";
|
||||||
|
|
||||||
pub async fn handle_instance(matches: &ArgMatches) -> CliResult {
|
pub async fn handle_instance(matches: &ArgMatches) -> CliResult {
|
||||||
match matches.subcommand() {
|
match matches.subcommand() {
|
||||||
@@ -20,6 +21,7 @@ pub async fn handle_instance(matches: &ArgMatches) -> CliResult {
|
|||||||
Some(("rename", sub_matches)) => rename_instance(sub_matches),
|
Some(("rename", sub_matches)) => rename_instance(sub_matches),
|
||||||
Some(("launch", sub_matches)) => launch_instance(sub_matches).await,
|
Some(("launch", sub_matches)) => launch_instance(sub_matches).await,
|
||||||
Some(("config", sub_matches)) => config_instance(sub_matches),
|
Some(("config", sub_matches)) => config_instance(sub_matches),
|
||||||
|
Some(("profile", sub_matches)) => profile_instance(sub_matches),
|
||||||
Some(("desktop", sub_matches)) => desktop_instance(sub_matches),
|
Some(("desktop", sub_matches)) => desktop_instance(sub_matches),
|
||||||
_ => Ok(()),
|
_ => Ok(()),
|
||||||
}
|
}
|
||||||
@@ -134,26 +136,24 @@ async fn launch_instance(matches: &ArgMatches) -> CliResult {
|
|||||||
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
|
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
|
||||||
let config = manager.load_one(name)?;
|
let config = manager.load_one(name)?;
|
||||||
|
|
||||||
println!("Launching '{}'...", name);
|
crate::instance::launch::launch(&config, &instances_dir, &meta_dir, None)
|
||||||
crate::instance::launch::launch(&config, &instances_dir, &meta_dir)
|
|
||||||
.await
|
.await
|
||||||
.map_err(|error| io::Error::other(format!("Launch failed: {}", error)))?;
|
.map_err(|error| io::Error::other(format!("Launch failed: {}", error)))?;
|
||||||
|
|
||||||
// poll until the game process exits. in CLI mode this blocks here
|
// poll until the game process exits. in CLI mode this blocks here
|
||||||
// so the user gets a proper exit code at the end.
|
// so the user gets a proper exit code at the end.
|
||||||
loop {
|
loop {
|
||||||
match crate::running::get(name) {
|
match crate::instance::runtime::get(name) {
|
||||||
Some(RunState::Crashed(Some(code))) => {
|
Some(RunState::Crashed(Some(code))) => {
|
||||||
println!("Game exited with status {}.", code);
|
println!("Game exited with status {}", code);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
Some(RunState::Crashed(None)) => {
|
Some(RunState::Crashed(None)) => {
|
||||||
println!("Game was terminated.");
|
println!("Game was terminated");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
Some(_) => tokio::time::sleep(Duration::from_millis(500)).await,
|
Some(_) => tokio::time::sleep(Duration::from_millis(500)).await,
|
||||||
None => {
|
None => {
|
||||||
println!("Game exited with status 0.");
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -235,12 +235,86 @@ fn config_instance(matches: &ArgMatches) -> CliResult {
|
|||||||
.map(|(width, height)| format!("{}x{}", width, height))
|
.map(|(width, height)| format!("{}x{}", width, height))
|
||||||
.unwrap_or_else(|| "-".to_string()),
|
.unwrap_or_else(|| "-".to_string()),
|
||||||
],
|
],
|
||||||
|
vec![
|
||||||
|
"config-sync-profile".to_string(),
|
||||||
|
display_config_profile(config.config_sync_profile.as_deref()).to_string(),
|
||||||
|
],
|
||||||
];
|
];
|
||||||
|
|
||||||
print_table(&["Field", "Value"], &rows);
|
print_table(&["Field", "Value"], &rows);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn profile_instance(matches: &ArgMatches) -> 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![
|
||||||
|
vec![
|
||||||
|
"current".to_string(),
|
||||||
|
display_config_profile(config.config_sync_profile.as_deref()).to_string(),
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
"available".to_string(),
|
||||||
|
if profiles.is_empty() {
|
||||||
|
LOCAL_CONFIG_PROFILE.to_string()
|
||||||
|
} else {
|
||||||
|
format!("{}, {}", LOCAL_CONFIG_PROFILE, profiles.join(", "))
|
||||||
|
},
|
||||||
|
],
|
||||||
|
];
|
||||||
|
print_table(&["Field", "Value"], &rows);
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
|
||||||
|
let target = if is_local_profile_alias(profile) {
|
||||||
|
None
|
||||||
|
} 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)?;
|
||||||
|
|
||||||
|
println!(
|
||||||
|
"Updated '{}' config profile to {}.",
|
||||||
|
name,
|
||||||
|
display_config_profile(config.config_sync_profile.as_deref())
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn display_config_profile(profile: Option<&str>) -> &str {
|
||||||
|
profile.unwrap_or(LOCAL_CONFIG_PROFILE)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_local_profile_alias(profile: &str) -> bool {
|
||||||
|
let profile = profile.trim();
|
||||||
|
profile.eq_ignore_ascii_case("none")
|
||||||
|
|| profile.eq_ignore_ascii_case("default")
|
||||||
|
|| profile.eq_ignore_ascii_case("local")
|
||||||
|
|| profile.eq_ignore_ascii_case("instance-default")
|
||||||
|
|| profile.eq_ignore_ascii_case("instance default")
|
||||||
|
}
|
||||||
|
|
||||||
// maps --set key=value pairs to config fields. empty value = clear the field.
|
// maps --set key=value pairs to config fields. empty value = clear the field.
|
||||||
fn apply_config_update(
|
fn apply_config_update(
|
||||||
config: &mut crate::instance::InstanceConfig,
|
config: &mut crate::instance::InstanceConfig,
|
||||||
@@ -280,21 +354,5 @@ fn apply_config_update(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/instance.rs"]
|
||||||
use super::parse_resolution;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parses_valid_resolution() {
|
|
||||||
assert_eq!(
|
|
||||||
parse_resolution("1920x1080").expect("should parse"),
|
|
||||||
(1920, 1080)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_invalid_resolution_format() {
|
|
||||||
assert!(parse_resolution("1920").is_err());
|
|
||||||
assert!(parse_resolution("1920xa").is_err());
|
|
||||||
assert!(parse_resolution("0x1080").is_err());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+7
-52
@@ -20,7 +20,7 @@ pub async fn handle_log(matches: &ArgMatches) -> CliResult {
|
|||||||
fn list_logs(instance: &str) -> CliResult {
|
fn list_logs(instance: &str) -> CliResult {
|
||||||
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
|
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
|
||||||
require_instance(&instances_dir, instance)?;
|
require_instance(&instances_dir, instance)?;
|
||||||
let rows = crate::instance::log_files::scan_log_files(&instances_dir, instance)
|
let rows = crate::instance::logs::files::scan_log_files(&instances_dir, instance)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|entry| {
|
.map(|entry| {
|
||||||
let size = std::fs::metadata(&entry.path)
|
let size = std::fs::metadata(&entry.path)
|
||||||
@@ -42,7 +42,7 @@ async fn show_log(matches: &ArgMatches) -> CliResult {
|
|||||||
require_instance(&instances_dir, instance)?;
|
require_instance(&instances_dir, instance)?;
|
||||||
let path = resolve_log_path(&instances_dir, instance, file)?;
|
let path = resolve_log_path(&instances_dir, instance, file)?;
|
||||||
|
|
||||||
let lines = crate::instance::log_files::read_log_file(&path);
|
let lines = crate::instance::logs::files::read_log_file(&path);
|
||||||
for line in &lines {
|
for line in &lines {
|
||||||
println!("{}", line);
|
println!("{}", line);
|
||||||
}
|
}
|
||||||
@@ -53,7 +53,7 @@ async fn show_log(matches: &ArgMatches) -> CliResult {
|
|||||||
let mut last_len = lines.len();
|
let mut last_len = lines.len();
|
||||||
loop {
|
loop {
|
||||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||||
let new_lines = crate::instance::log_files::read_log_file(&path);
|
let new_lines = crate::instance::logs::files::read_log_file(&path);
|
||||||
for line in new_lines.iter().skip(last_len) {
|
for line in new_lines.iter().skip(last_len) {
|
||||||
println!("{}", line);
|
println!("{}", line);
|
||||||
}
|
}
|
||||||
@@ -71,14 +71,14 @@ pub(crate) fn resolve_log_path(
|
|||||||
file: Option<&str>,
|
file: Option<&str>,
|
||||||
) -> Result<PathBuf, io::Error> {
|
) -> Result<PathBuf, io::Error> {
|
||||||
if let Some(name) = file {
|
if let Some(name) = file {
|
||||||
let path = crate::instance::log_files::log_dir(instances_dir, instance).join(name);
|
let path = crate::instance::logs::files::log_dir(instances_dir, instance).join(name);
|
||||||
if !path.exists() {
|
if !path.exists() {
|
||||||
return Err(io::Error::other(format!("log '{}' not found", name)));
|
return Err(io::Error::other(format!("log '{}' not found", name)));
|
||||||
}
|
}
|
||||||
return Ok(path);
|
return Ok(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
crate::instance::log_files::scan_log_files(instances_dir, instance)
|
crate::instance::logs::files::scan_log_files(instances_dir, instance)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.next()
|
.next()
|
||||||
.map(|entry| entry.path)
|
.map(|entry| entry.path)
|
||||||
@@ -88,50 +88,5 @@ pub(crate) fn resolve_log_path(
|
|||||||
use super::utils::{require_instance, required_arg};
|
use super::utils::{require_instance, required_arg};
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/log.rs"]
|
||||||
use super::resolve_log_path;
|
mod tests;
|
||||||
|
|
||||||
fn unique_temp_dir() -> std::path::PathBuf {
|
|
||||||
std::env::temp_dir().join(format!(
|
|
||||||
"rmcl_cli_log_test_{}",
|
|
||||||
std::time::SystemTime::now()
|
|
||||||
.duration_since(std::time::UNIX_EPOCH)
|
|
||||||
.expect("time should work")
|
|
||||||
.as_nanos()
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolves_latest_log_when_no_file_is_given() {
|
|
||||||
let root = unique_temp_dir();
|
|
||||||
let dir = root.join("demo/.minecraft/logs/launches");
|
|
||||||
std::fs::create_dir_all(&dir).expect("log directory should exist");
|
|
||||||
std::fs::write(dir.join("2024-01-02_03-04-05.log"), "newer").expect("write newer log");
|
|
||||||
std::fs::write(dir.join("2024-01-01_03-04-05.log"), "older").expect("write older log");
|
|
||||||
|
|
||||||
let path = resolve_log_path(&root, "demo", None).expect("latest log should resolve");
|
|
||||||
assert_eq!(
|
|
||||||
path.file_name().and_then(|name| name.to_str()),
|
|
||||||
Some("2024-01-02_03-04-05.log")
|
|
||||||
);
|
|
||||||
|
|
||||||
let _ = std::fs::remove_dir_all(&root);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolves_named_log_file() {
|
|
||||||
let root = unique_temp_dir();
|
|
||||||
let dir = root.join("demo/.minecraft/logs/launches");
|
|
||||||
std::fs::create_dir_all(&dir).expect("log directory should exist");
|
|
||||||
std::fs::write(dir.join("latest.log"), "hello").expect("write named log");
|
|
||||||
|
|
||||||
let path =
|
|
||||||
resolve_log_path(&root, "demo", Some("latest.log")).expect("named log should resolve");
|
|
||||||
assert_eq!(
|
|
||||||
path.file_name().and_then(|name| name.to_str()),
|
|
||||||
Some("latest.log")
|
|
||||||
);
|
|
||||||
|
|
||||||
let _ = std::fs::remove_dir_all(&root);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+52
-11
@@ -24,6 +24,49 @@ pub async fn init() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
|
||||||
|
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
|
||||||
|
if crate::layout_migration::is_needed(&instances_dir, &meta_dir) {
|
||||||
|
let config = crate::config::get_config_path().join("config.toml");
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
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 {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let result = match matches.subcommand() {
|
let result = match matches.subcommand() {
|
||||||
Some(("instance", sub_matches)) => instance::handle_instance(sub_matches).await,
|
Some(("instance", sub_matches)) => instance::handle_instance(sub_matches).await,
|
||||||
Some(("mod", sub_matches)) => content::handle_mod(sub_matches),
|
Some(("mod", sub_matches)) => content::handle_mod(sub_matches),
|
||||||
@@ -104,6 +147,13 @@ fn build_command() -> Command {
|
|||||||
.arg(Arg::new("name").required(true).action(ArgAction::Set))
|
.arg(Arg::new("name").required(true).action(ArgAction::Set))
|
||||||
.arg(Arg::new("set").long("set").action(ArgAction::Set)),
|
.arg(Arg::new("set").long("set").action(ArgAction::Set)),
|
||||||
)
|
)
|
||||||
|
.subcommand(
|
||||||
|
Command::new("profile")
|
||||||
|
.about("Show or set an instance config-sync profile")
|
||||||
|
.arg_required_else_help(true)
|
||||||
|
.arg(Arg::new("name").required(true).action(ArgAction::Set))
|
||||||
|
.arg(Arg::new("profile").action(ArgAction::Set)),
|
||||||
|
)
|
||||||
.subcommand(
|
.subcommand(
|
||||||
Command::new("desktop")
|
Command::new("desktop")
|
||||||
.about("Toggle desktop shortcut for an instance")
|
.about("Toggle desktop shortcut for an instance")
|
||||||
@@ -239,14 +289,5 @@ fn build_content_command(name: &'static str, about: &'static str) -> Command {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/arguments.rs"]
|
||||||
use super::build_command;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parses_instance_list_subcommand() {
|
|
||||||
let matches = build_command()
|
|
||||||
.try_get_matches_from(["rmcl", "instance", "list"])
|
|
||||||
.expect("command should parse");
|
|
||||||
assert!(matches.subcommand_matches("instance").is_some());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+2
-27
@@ -78,30 +78,5 @@ fn render_separator(widths: &[usize]) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/output.rs"]
|
||||||
use super::{format_datetime, render_table};
|
mod tests;
|
||||||
use chrono::{TimeZone, Utc};
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn render_table_aligns_columns() {
|
|
||||||
let rendered = render_table(
|
|
||||||
&["Name", "State"],
|
|
||||||
&[
|
|
||||||
vec!["Alpha".to_string(), "enabled".to_string()],
|
|
||||||
vec!["Longer Name".to_string(), "off".to_string()],
|
|
||||||
],
|
|
||||||
);
|
|
||||||
|
|
||||||
let lines: Vec<&str> = rendered.lines().collect();
|
|
||||||
assert_eq!(lines[0], "Name State ");
|
|
||||||
assert_eq!(lines[1], "----------- -------");
|
|
||||||
assert_eq!(lines[2], "Alpha enabled");
|
|
||||||
assert_eq!(lines[3], "Longer Name off ");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
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");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
use super::add_offline_account;
|
||||||
|
use crate::auth::{Account, AccountStore, AccountType};
|
||||||
|
|
||||||
|
fn microsoft_account() -> Account {
|
||||||
|
Account {
|
||||||
|
uuid: "00000000-0000-0000-0000-000000000001".to_owned(),
|
||||||
|
username: "Owner".to_owned(),
|
||||||
|
account_type: AccountType::Microsoft,
|
||||||
|
active: false,
|
||||||
|
refresh_token: Some("refresh".to_owned()),
|
||||||
|
cached_mc_token: None,
|
||||||
|
cached_mc_token_expires_at: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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());
|
||||||
|
add_offline_account(&mut store, "Steve").expect("offline account should be added");
|
||||||
|
|
||||||
|
assert_eq!(store.accounts.len(), 2);
|
||||||
|
assert_eq!(store.accounts[1].username, "Steve");
|
||||||
|
assert_eq!(store.accounts[1].account_type, AccountType::Offline);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_offline_account_before_microsoft_account_exists() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json"));
|
||||||
|
let err = add_offline_account(&mut store, "Steve")
|
||||||
|
.expect_err("offline account should require a microsoft account");
|
||||||
|
|
||||||
|
assert!(err.to_string().contains("Microsoft account"));
|
||||||
|
assert!(store.accounts.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_empty_offline_username() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json"));
|
||||||
|
assert!(add_offline_account(&mut store, " ").is_err());
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
use super::build_command;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_instance_list_subcommand() {
|
||||||
|
let matches = build_command()
|
||||||
|
.try_get_matches_from(["rmcl", "instance", "list"])
|
||||||
|
.expect("command should parse");
|
||||||
|
let instance = matches
|
||||||
|
.subcommand_matches("instance")
|
||||||
|
.expect("instance subcommand should be present");
|
||||||
|
assert_eq!(
|
||||||
|
instance.subcommand_name(),
|
||||||
|
Some("list"),
|
||||||
|
"instance list should resolve to the list subcommand"
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
use super::find_entry_by_stem;
|
||||||
|
use crate::instance::content::entry::ContentEntry;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
fn entry(file_stem: &str) -> ContentEntry {
|
||||||
|
ContentEntry {
|
||||||
|
file_stem: file_stem.to_string(),
|
||||||
|
name: file_stem.to_string(),
|
||||||
|
source_slug: None,
|
||||||
|
installed_path: None,
|
||||||
|
provider_project: None,
|
||||||
|
world_details: None,
|
||||||
|
title_suffix: None,
|
||||||
|
footer_label: None,
|
||||||
|
footer_change: None,
|
||||||
|
description: String::new(),
|
||||||
|
enabled: true,
|
||||||
|
icon_bytes: None,
|
||||||
|
provider_icon: false,
|
||||||
|
provider_description: false,
|
||||||
|
path: PathBuf::from(file_stem),
|
||||||
|
icon_lines: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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");
|
||||||
|
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());
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn version(name: &str, number: &str) -> modrinth::VersionInfo {
|
||||||
|
modrinth::VersionInfo {
|
||||||
|
id: number.to_owned(),
|
||||||
|
project_id: "project".to_owned(),
|
||||||
|
name: name.to_owned(),
|
||||||
|
version_number: number.to_owned(),
|
||||||
|
game_versions: vec!["1.21.1".to_owned()],
|
||||||
|
loaders: vec!["fabric".to_owned()],
|
||||||
|
version_type: modrinth::VersionType::Release,
|
||||||
|
dependencies: Vec::new(),
|
||||||
|
date_published: String::new(),
|
||||||
|
files: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn version_override_matches_name_or_number_and_rejects_unknown_values() {
|
||||||
|
let versions = vec![version("Stable", "1.0.0"), version("Beta", "2.0.0-beta")];
|
||||||
|
|
||||||
|
assert_eq!(select_version(&versions, None).unwrap().name, "Stable");
|
||||||
|
assert_eq!(
|
||||||
|
select_version(&versions, Some("Beta"))
|
||||||
|
.unwrap()
|
||||||
|
.version_number,
|
||||||
|
"2.0.0-beta"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
select_version(&versions, Some("1.0.0")).unwrap().name,
|
||||||
|
"Stable"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
select_version(&versions, Some("missing")).unwrap_err(),
|
||||||
|
"Version 'missing' not found"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn import_command_parses_name_and_version_overrides() {
|
||||||
|
let matches = crate::cli::build_command()
|
||||||
|
.try_get_matches_from([
|
||||||
|
"rmcl",
|
||||||
|
"import",
|
||||||
|
"example-pack",
|
||||||
|
"--name",
|
||||||
|
"Example",
|
||||||
|
"--version",
|
||||||
|
"1.2.3",
|
||||||
|
])
|
||||||
|
.unwrap();
|
||||||
|
let import = matches.subcommand_matches("import").unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
import.get_one::<String>("source").map(String::as_str),
|
||||||
|
Some("example-pack")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
import.get_one::<String>("name").map(String::as_str),
|
||||||
|
Some("Example")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
import.get_one::<String>("version").map(String::as_str),
|
||||||
|
Some("1.2.3")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn missing_local_pack_returns_a_file_not_found_error() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let missing = temp.path().join("missing.mrpack");
|
||||||
|
let source = missing.to_string_lossy().into_owned();
|
||||||
|
let matches = crate::cli::build_command()
|
||||||
|
.try_get_matches_from(["rmcl", "import", &source])
|
||||||
|
.unwrap();
|
||||||
|
let import = matches.subcommand_matches("import").unwrap();
|
||||||
|
|
||||||
|
let error = handle_import(import).await.unwrap_err().to_string();
|
||||||
|
|
||||||
|
assert_eq!(error, format!("File not found: {}", missing.display()));
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
use super::parse_resolution;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_valid_resolution() {
|
||||||
|
assert_eq!(
|
||||||
|
parse_resolution("1920x1080").expect("should parse"),
|
||||||
|
(1920, 1080)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_invalid_resolution_format() {
|
||||||
|
assert!(parse_resolution("1920").is_err());
|
||||||
|
assert!(parse_resolution("1920xa").is_err());
|
||||||
|
assert!(parse_resolution("0x1080").is_err());
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
use super::resolve_log_path;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolves_latest_log_when_no_file_is_given() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = tmp.path().join("demo/minecraft/logs/launches");
|
||||||
|
std::fs::create_dir_all(&dir).expect("log directory should exist");
|
||||||
|
std::fs::write(dir.join("2024-01-02_03-04-05.log"), "newer").expect("write newer log");
|
||||||
|
std::fs::write(dir.join("2024-01-01_03-04-05.log"), "older").expect("write older log");
|
||||||
|
|
||||||
|
let path = resolve_log_path(tmp.path(), "demo", None).expect("latest log should resolve");
|
||||||
|
assert_eq!(
|
||||||
|
path.file_name().and_then(|name| name.to_str()),
|
||||||
|
Some("2024-01-02_03-04-05.log")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolves_named_log_file() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = tmp.path().join("demo/minecraft/logs/launches");
|
||||||
|
std::fs::create_dir_all(&dir).expect("log directory should exist");
|
||||||
|
std::fs::write(dir.join("latest.log"), "hello").expect("write named log");
|
||||||
|
|
||||||
|
let path =
|
||||||
|
resolve_log_path(tmp.path(), "demo", Some("latest.log")).expect("named log should resolve");
|
||||||
|
assert_eq!(
|
||||||
|
path.file_name().and_then(|name| name.to_str()),
|
||||||
|
Some("latest.log")
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
use super::{format_datetime, render_table};
|
||||||
|
use chrono::{TimeZone, Utc};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_table_aligns_columns() {
|
||||||
|
let rendered = render_table(
|
||||||
|
&["Name", "State"],
|
||||||
|
&[
|
||||||
|
vec!["Alpha".to_string(), "enabled".to_string()],
|
||||||
|
vec!["Longer Name".to_string(), "off".to_string()],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
let lines: Vec<&str> = rendered.lines().collect();
|
||||||
|
assert_eq!(lines[0], "Name State ");
|
||||||
|
assert_eq!(lines[1], "----------- -------");
|
||||||
|
assert_eq!(lines[2], "Alpha enabled");
|
||||||
|
assert_eq!(lines[3], "Longer Name off ");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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");
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
use super::filter_manifest_versions;
|
||||||
|
use crate::net::mojang::{LatestVersions, VersionEntry, VersionManifest};
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
fn manifest() -> VersionManifest {
|
||||||
|
VersionManifest {
|
||||||
|
latest: LatestVersions {
|
||||||
|
release: "1.20.1".to_string(),
|
||||||
|
snapshot: "24w01a".to_string(),
|
||||||
|
},
|
||||||
|
versions: vec![
|
||||||
|
VersionEntry {
|
||||||
|
id: "1.20.1".to_string(),
|
||||||
|
version_type: "release".to_string(),
|
||||||
|
url: "https://example.com/release".to_string(),
|
||||||
|
sha1: "a".to_string(),
|
||||||
|
},
|
||||||
|
VersionEntry {
|
||||||
|
id: "24w01a".to_string(),
|
||||||
|
version_type: "snapshot".to_string(),
|
||||||
|
url: "https://example.com/snapshot".to_string(),
|
||||||
|
sha1: "b".to_string(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn filters_out_snapshots_by_default() {
|
||||||
|
let rows = filter_manifest_versions(&manifest(), None, false);
|
||||||
|
assert_eq!(rows.len(), 1);
|
||||||
|
assert_eq!(rows[0].id, "1.20.1");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn intersects_supported_versions() {
|
||||||
|
let supported = HashSet::from(["24w01a".to_string()]);
|
||||||
|
let rows = filter_manifest_versions(&manifest(), Some(&supported), true);
|
||||||
|
assert_eq!(rows.len(), 1);
|
||||||
|
assert_eq!(rows[0].id, "24w01a");
|
||||||
|
}
|
||||||
+2
-43
@@ -96,46 +96,5 @@ fn filter_manifest_versions(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/version.rs"]
|
||||||
use super::filter_manifest_versions;
|
mod tests;
|
||||||
use crate::net::mojang::{LatestVersions, VersionEntry, VersionManifest};
|
|
||||||
use std::collections::HashSet;
|
|
||||||
|
|
||||||
fn manifest() -> VersionManifest {
|
|
||||||
VersionManifest {
|
|
||||||
latest: LatestVersions {
|
|
||||||
release: "1.20.1".to_string(),
|
|
||||||
snapshot: "24w01a".to_string(),
|
|
||||||
},
|
|
||||||
versions: vec![
|
|
||||||
VersionEntry {
|
|
||||||
id: "1.20.1".to_string(),
|
|
||||||
version_type: "release".to_string(),
|
|
||||||
url: "https://example.com/release".to_string(),
|
|
||||||
sha1: "a".to_string(),
|
|
||||||
},
|
|
||||||
VersionEntry {
|
|
||||||
id: "24w01a".to_string(),
|
|
||||||
version_type: "snapshot".to_string(),
|
|
||||||
url: "https://example.com/snapshot".to_string(),
|
|
||||||
sha1: "b".to_string(),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn filters_out_snapshots_by_default() {
|
|
||||||
let rows = filter_manifest_versions(&manifest(), None, false);
|
|
||||||
assert_eq!(rows.len(), 1);
|
|
||||||
assert_eq!(rows[0].id, "1.20.1");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn intersects_supported_versions() {
|
|
||||||
let supported = HashSet::from(["24w01a".to_string()]);
|
|
||||||
let rows = filter_manifest_versions(&manifest(), Some(&supported), true);
|
|
||||||
assert_eq!(rows.len(), 1);
|
|
||||||
assert_eq!(rows[0].id, "24w01a");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+22
-56
@@ -22,15 +22,31 @@ pub fn get_config_path() -> PathBuf {
|
|||||||
fn ensure_config_exists() -> PathBuf {
|
fn ensure_config_exists() -> PathBuf {
|
||||||
let config_path = get_config_path().join("config.toml");
|
let config_path = get_config_path().join("config.toml");
|
||||||
if !config_path.exists() {
|
if !config_path.exists() {
|
||||||
if let Some(parent) = config_path.parent() {
|
if let Some(parent) = config_path.parent()
|
||||||
let _ = fs::create_dir_all(parent);
|
&& let Err(e) = fs::create_dir_all(parent)
|
||||||
|
{
|
||||||
|
tracing::warn!(
|
||||||
|
"Failed to create config directory {}: {}",
|
||||||
|
parent.display(),
|
||||||
|
e
|
||||||
|
);
|
||||||
}
|
}
|
||||||
let _ = fs::write(&config_path, include_str!("../../assets/config.toml"));
|
match fs::write(&config_path, include_str!("../../assets/config.toml")) {
|
||||||
|
Ok(()) => tracing::debug!("Wrote default config to {}", config_path.display()),
|
||||||
|
Err(e) => tracing::warn!(
|
||||||
|
"Failed to write default config to {}: {}",
|
||||||
|
config_path.display(),
|
||||||
|
e
|
||||||
|
),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
tracing::trace!("Using existing config at {}", config_path.display());
|
||||||
}
|
}
|
||||||
config_path
|
config_path
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn load_config(config_path: &std::path::Path) -> Result<Config, ConfigError> {
|
pub fn load_config(config_path: &std::path::Path) -> Result<Config, ConfigError> {
|
||||||
|
tracing::debug!("Loading config from {}", config_path.display());
|
||||||
ConfigLoader::builder()
|
ConfigLoader::builder()
|
||||||
.add_source(File::from(config_path).required(false))
|
.add_source(File::from(config_path).required(false))
|
||||||
.build()?
|
.build()?
|
||||||
@@ -46,61 +62,11 @@ pub static SETTINGS: LazyLock<Config> = LazyLock::new(|| {
|
|||||||
paths: settings::Paths::default(),
|
paths: settings::Paths::default(),
|
||||||
defaults: settings::Defaults::default(),
|
defaults: settings::Defaults::default(),
|
||||||
ui: settings::Ui::default(),
|
ui: settings::Ui::default(),
|
||||||
|
content: settings::Content::default(),
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/loading.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn load_config_from_valid_toml() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let path = tmp.path().join("config.toml");
|
|
||||||
std::fs::write(
|
|
||||||
&path,
|
|
||||||
r#"
|
|
||||||
[defaults]
|
|
||||||
memory_max = "4G"
|
|
||||||
"#,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let config = load_config(&path).unwrap();
|
|
||||||
assert_eq!(config.defaults.memory_max, "4G");
|
|
||||||
assert_eq!(config.defaults.memory_min, "512M");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn load_config_from_empty_file() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let path = tmp.path().join("config.toml");
|
|
||||||
std::fs::write(&path, "").unwrap();
|
|
||||||
let config = load_config(&path).unwrap();
|
|
||||||
assert_eq!(config.defaults.memory_max, "2G");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn load_config_missing_file_uses_defaults() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let path = tmp.path().join("nonexistent.toml");
|
|
||||||
load_config(&path).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn load_config_partial_sections() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let path = tmp.path().join("config.toml");
|
|
||||||
std::fs::write(
|
|
||||||
&path,
|
|
||||||
r#"
|
|
||||||
[paths]
|
|
||||||
instances_dir = "/custom/path"
|
|
||||||
"#,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let config = load_config(&path).unwrap();
|
|
||||||
assert_eq!(config.paths.instances_dir, "/custom/path");
|
|
||||||
assert!(config.paths.java_path.is_none());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+115
-105
@@ -5,9 +5,117 @@ use std::path::PathBuf;
|
|||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Default, Clone, Copy, PartialEq, Eq)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum ImageProtocol {
|
||||||
|
Halfblocks,
|
||||||
|
Quadrants,
|
||||||
|
#[default]
|
||||||
|
Kitty,
|
||||||
|
Iterm2,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Default)]
|
#[derive(Debug, Deserialize, Default)]
|
||||||
pub struct General {}
|
pub struct General {}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct Content {
|
||||||
|
#[serde(default = "default_true")]
|
||||||
|
pub ask_on_provider_conflict: bool,
|
||||||
|
#[serde(default = "default_provider")]
|
||||||
|
pub preferred_provider: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub preferred_provider_only: bool,
|
||||||
|
#[serde(default = "default_unmatched_retry_hours")]
|
||||||
|
pub unmatched_retry_hours: u64,
|
||||||
|
#[serde(default = "default_max_fingerprint_size_mib")]
|
||||||
|
pub max_fingerprint_size_mib: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_true() -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_provider() -> String {
|
||||||
|
"modrinth".to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_unmatched_retry_hours() -> u64 {
|
||||||
|
24
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_max_fingerprint_size_mib() -> u64 {
|
||||||
|
512
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Content {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
ask_on_provider_conflict: true,
|
||||||
|
preferred_provider: default_provider(),
|
||||||
|
preferred_provider_only: false,
|
||||||
|
unmatched_retry_hours: default_unmatched_retry_hours(),
|
||||||
|
max_fingerprint_size_mib: default_max_fingerprint_size_mib(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Content {
|
||||||
|
pub fn preferred_provider(&self) -> &str {
|
||||||
|
self.preferred_provider_with_curseforge(crate::net::curseforge::api_key().is_some())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn discovery_provider_enabled(&self, provider: &str) -> bool {
|
||||||
|
self.discovery_provider_enabled_with_curseforge(
|
||||||
|
provider,
|
||||||
|
crate::net::curseforge::api_key().is_some(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn discovery_provider_label(&self) -> &'static str {
|
||||||
|
self.discovery_provider_label_with_curseforge(crate::net::curseforge::api_key().is_some())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn preferred_provider_with_curseforge(&self, curseforge_available: bool) -> &'static str {
|
||||||
|
if self.preferred_provider.eq_ignore_ascii_case("curseforge") && curseforge_available {
|
||||||
|
"curseforge"
|
||||||
|
} else {
|
||||||
|
"modrinth"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn discovery_provider_enabled_with_curseforge(
|
||||||
|
&self,
|
||||||
|
provider: &str,
|
||||||
|
curseforge_available: bool,
|
||||||
|
) -> bool {
|
||||||
|
match provider {
|
||||||
|
"modrinth" => {
|
||||||
|
!self.preferred_provider_only
|
||||||
|
|| self.preferred_provider_with_curseforge(curseforge_available) == "modrinth"
|
||||||
|
}
|
||||||
|
"curseforge" => {
|
||||||
|
curseforge_available
|
||||||
|
&& (!self.preferred_provider_only
|
||||||
|
|| self.preferred_provider_with_curseforge(curseforge_available)
|
||||||
|
== "curseforge")
|
||||||
|
}
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn discovery_provider_label_with_curseforge(&self, curseforge_available: bool) -> &'static str {
|
||||||
|
match (
|
||||||
|
self.discovery_provider_enabled_with_curseforge("modrinth", curseforge_available),
|
||||||
|
self.discovery_provider_enabled_with_curseforge("curseforge", curseforge_available),
|
||||||
|
) {
|
||||||
|
(true, true) => "providers",
|
||||||
|
(false, true) => "CurseForge",
|
||||||
|
_ => "Modrinth",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
pub struct Paths {
|
pub struct Paths {
|
||||||
#[serde(default = "default_instances_dir")]
|
#[serde(default = "default_instances_dir")]
|
||||||
@@ -102,6 +210,8 @@ impl Default for Defaults {
|
|||||||
// timing knobs for the error toast animation: show for 5s, start sliding at 3.5s,
|
// 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.
|
// fly off screen over 300ms. tweak these if the toasts feel too fast or slow.
|
||||||
pub struct Ui {
|
pub struct Ui {
|
||||||
|
#[serde(default)]
|
||||||
|
pub image_protocol: ImageProtocol,
|
||||||
#[serde(default = "default_error_auto_dismiss_ms")]
|
#[serde(default = "default_error_auto_dismiss_ms")]
|
||||||
pub error_auto_dismiss_ms: u64,
|
pub error_auto_dismiss_ms: u64,
|
||||||
#[serde(default = "default_error_slide_start_ms")]
|
#[serde(default = "default_error_slide_start_ms")]
|
||||||
@@ -128,6 +238,7 @@ fn default_max_error_events() -> usize {
|
|||||||
impl Default for Ui {
|
impl Default for Ui {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
image_protocol: ImageProtocol::default(),
|
||||||
error_auto_dismiss_ms: default_error_auto_dismiss_ms(),
|
error_auto_dismiss_ms: default_error_auto_dismiss_ms(),
|
||||||
error_slide_start_ms: default_error_slide_start_ms(),
|
error_slide_start_ms: default_error_slide_start_ms(),
|
||||||
error_fly_out_ms: default_error_fly_out_ms(),
|
error_fly_out_ms: default_error_fly_out_ms(),
|
||||||
@@ -146,111 +257,10 @@ pub struct Config {
|
|||||||
pub defaults: Defaults,
|
pub defaults: Defaults,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub ui: Ui,
|
pub ui: Ui,
|
||||||
|
#[serde(default)]
|
||||||
|
pub content: Content,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/settings.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn effective_java_path_none_when_absent() {
|
|
||||||
let paths = Paths {
|
|
||||||
java_path: None,
|
|
||||||
..Paths::default()
|
|
||||||
};
|
|
||||||
assert!(paths.effective_java_path().is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn effective_java_path_none_when_empty() {
|
|
||||||
let paths = Paths {
|
|
||||||
java_path: Some(String::new()),
|
|
||||||
..Paths::default()
|
|
||||||
};
|
|
||||||
assert!(paths.effective_java_path().is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn effective_java_path_some_when_set() {
|
|
||||||
let paths = Paths {
|
|
||||||
java_path: Some("/usr/bin/java".to_owned()),
|
|
||||||
..Paths::default()
|
|
||||||
};
|
|
||||||
assert_eq!(paths.effective_java_path(), Some("/usr/bin/java"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolve_path_absolute() {
|
|
||||||
assert_eq!(resolve_path("/opt/rmcl"), PathBuf::from("/opt/rmcl"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolve_path_bare_tilde() {
|
|
||||||
let resolved = resolve_path("~");
|
|
||||||
assert!(!resolved.to_string_lossy().starts_with('~'));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolve_instances_dir_absolute() {
|
|
||||||
let paths = Paths {
|
|
||||||
instances_dir: "/opt/rmcl/instances".to_owned(),
|
|
||||||
..Paths::default()
|
|
||||||
};
|
|
||||||
assert_eq!(
|
|
||||||
paths.resolve_instances_dir(),
|
|
||||||
PathBuf::from("/opt/rmcl/instances")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolve_meta_dir_absolute() {
|
|
||||||
let paths = Paths {
|
|
||||||
meta_dir: "/opt/rmcl/meta".to_owned(),
|
|
||||||
..Paths::default()
|
|
||||||
};
|
|
||||||
assert_eq!(paths.resolve_meta_dir(), PathBuf::from("/opt/rmcl/meta"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn defaults_have_expected_values() {
|
|
||||||
let d = Defaults::default();
|
|
||||||
assert_eq!(d.memory_min, "512M");
|
|
||||||
assert_eq!(d.memory_max, "2G");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn ui_defaults_have_expected_values() {
|
|
||||||
let ui = Ui::default();
|
|
||||||
assert_eq!(ui.error_auto_dismiss_ms, 5000);
|
|
||||||
assert_eq!(ui.error_slide_start_ms, 3500);
|
|
||||||
assert_eq!(ui.error_fly_out_ms, 300);
|
|
||||||
assert_eq!(ui.max_error_events, 50);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn config_deserializes_from_empty_toml() {
|
|
||||||
let config: Config = toml::from_str("").unwrap();
|
|
||||||
assert_eq!(config.defaults.memory_max, "2G");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn config_deserializes_partial_toml() {
|
|
||||||
let toml_str = r#"
|
|
||||||
[general]
|
|
||||||
debug = true
|
|
||||||
|
|
||||||
[defaults]
|
|
||||||
memory_max = "8G"
|
|
||||||
"#;
|
|
||||||
let config: Config = toml::from_str(toml_str).unwrap();
|
|
||||||
assert_eq!(config.defaults.memory_max, "8G");
|
|
||||||
assert_eq!(config.defaults.memory_min, "512M");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_config_from_valid_toml() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let path = tmp.path().join("config.toml");
|
||||||
|
std::fs::write(
|
||||||
|
&path,
|
||||||
|
r#"
|
||||||
|
[defaults]
|
||||||
|
memory_max = "4G"
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let config = load_config(&path).unwrap();
|
||||||
|
assert_eq!(config.defaults.memory_max, "4G");
|
||||||
|
assert_eq!(config.defaults.memory_min, "512M");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_config_from_empty_file() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let path = tmp.path().join("config.toml");
|
||||||
|
std::fs::write(&path, "").unwrap();
|
||||||
|
let config = load_config(&path).unwrap();
|
||||||
|
assert_eq!(config.defaults.memory_max, "2G");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_config_missing_file_uses_defaults() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let path = tmp.path().join("nonexistent.toml");
|
||||||
|
load_config(&path).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_config_partial_sections() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let path = tmp.path().join("config.toml");
|
||||||
|
std::fs::write(
|
||||||
|
&path,
|
||||||
|
r#"
|
||||||
|
[paths]
|
||||||
|
instances_dir = "/custom/path"
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let config = load_config(&path).unwrap();
|
||||||
|
assert_eq!(config.paths.instances_dir, "/custom/path");
|
||||||
|
assert!(config.paths.java_path.is_none());
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn effective_java_path_none_when_absent() {
|
||||||
|
let paths = Paths {
|
||||||
|
java_path: None,
|
||||||
|
..Paths::default()
|
||||||
|
};
|
||||||
|
assert!(paths.effective_java_path().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn effective_java_path_none_when_empty() {
|
||||||
|
let paths = Paths {
|
||||||
|
java_path: Some(String::new()),
|
||||||
|
..Paths::default()
|
||||||
|
};
|
||||||
|
assert!(paths.effective_java_path().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn effective_java_path_some_when_set() {
|
||||||
|
let paths = Paths {
|
||||||
|
java_path: Some("/usr/bin/java".to_owned()),
|
||||||
|
..Paths::default()
|
||||||
|
};
|
||||||
|
assert_eq!(paths.effective_java_path(), Some("/usr/bin/java"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn content_provider_settings_are_normalized() {
|
||||||
|
let content: Content =
|
||||||
|
toml::from_str("preferred_provider = \"curseforge\"\npreferred_provider_only = true")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
content.preferred_provider_with_curseforge(false),
|
||||||
|
"modrinth"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
content.preferred_provider_with_curseforge(true),
|
||||||
|
"curseforge"
|
||||||
|
);
|
||||||
|
assert!(content.preferred_provider_only);
|
||||||
|
assert!(content.discovery_provider_enabled_with_curseforge("modrinth", false));
|
||||||
|
assert!(!content.discovery_provider_enabled_with_curseforge("curseforge", false));
|
||||||
|
assert!(!content.discovery_provider_enabled_with_curseforge("modrinth", true));
|
||||||
|
assert!(content.discovery_provider_enabled_with_curseforge("curseforge", true));
|
||||||
|
assert_eq!(
|
||||||
|
content.discovery_provider_label_with_curseforge(false),
|
||||||
|
"Modrinth"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
content.discovery_provider_label_with_curseforge(true),
|
||||||
|
"CurseForge"
|
||||||
|
);
|
||||||
|
|
||||||
|
let merged = Content::default();
|
||||||
|
assert_eq!(
|
||||||
|
merged.discovery_provider_label_with_curseforge(false),
|
||||||
|
"Modrinth"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
merged.discovery_provider_label_with_curseforge(true),
|
||||||
|
"providers"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolve_path_absolute() {
|
||||||
|
assert_eq!(resolve_path("/opt/rmcl"), PathBuf::from("/opt/rmcl"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolve_path_bare_tilde() {
|
||||||
|
let resolved = resolve_path("~");
|
||||||
|
assert!(!resolved.to_string_lossy().starts_with('~'));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_deserializes_from_empty_toml() {
|
||||||
|
let config: Config = toml::from_str("").unwrap();
|
||||||
|
assert_eq!(config.defaults.memory_max, "2G");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_deserializes_partial_toml() {
|
||||||
|
let toml_str = r#"
|
||||||
|
[general]
|
||||||
|
debug = true
|
||||||
|
|
||||||
|
[defaults]
|
||||||
|
memory_max = "8G"
|
||||||
|
"#;
|
||||||
|
let config: Config = toml::from_str(toml_str).unwrap();
|
||||||
|
assert_eq!(config.defaults.memory_max, "8G");
|
||||||
|
assert_eq!(config.defaults.memory_min, "512M");
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
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)]
|
||||||
|
#[case::double(BorderStyle::Double, BorderType::Double)]
|
||||||
|
#[case::thick(BorderStyle::Thick, BorderType::Thick)]
|
||||||
|
fn border_style_roundtrip(#[case] style: BorderStyle, #[case] expected: BorderType) {
|
||||||
|
assert_eq!(style.to_border_type(), expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn theme_config_deserialize_builtin() {
|
||||||
|
let toml_str = r#"
|
||||||
|
theme = "dracula"
|
||||||
|
border_style = "plain"
|
||||||
|
"#;
|
||||||
|
let config: ThemeConfig = toml::from_str(toml_str).unwrap();
|
||||||
|
assert_eq!(config.theme, "dracula");
|
||||||
|
assert_eq!(config.border_style, BorderStyle::Plain);
|
||||||
|
assert!(config.custom.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn theme_config_with_partial_overrides() {
|
||||||
|
let toml_str = r#"
|
||||||
|
theme = "dracula"
|
||||||
|
|
||||||
|
[custom]
|
||||||
|
accent = "Red"
|
||||||
|
"#;
|
||||||
|
let config: ThemeConfig = toml::from_str(toml_str).unwrap();
|
||||||
|
assert_eq!(config.theme, "dracula");
|
||||||
|
let overrides = config.custom.unwrap();
|
||||||
|
assert_eq!(overrides.accent, Some(Color::Red));
|
||||||
|
assert!(overrides.text.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolve_with_overrides_keeps_base() {
|
||||||
|
let config = ThemeConfig {
|
||||||
|
theme: "dracula".to_owned(),
|
||||||
|
custom: Some(ThemeOverrides {
|
||||||
|
accent: Some(Color::Red),
|
||||||
|
..ThemeOverrides::default()
|
||||||
|
}),
|
||||||
|
..ThemeConfig::default()
|
||||||
|
};
|
||||||
|
let theme = resolve_app_theme(&config);
|
||||||
|
assert_eq!(theme.accent(), Color::Red);
|
||||||
|
let base = resolve_theme("dracula");
|
||||||
|
assert_eq!(theme.text(), base.text());
|
||||||
|
assert_eq!(theme.error(), base.error());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolve_builtin_theme() {
|
||||||
|
let theme = resolve_theme("dracula");
|
||||||
|
let expected = if std::env::var_os("NO_COLOR").is_some() {
|
||||||
|
"no-color"
|
||||||
|
} else {
|
||||||
|
"dracula"
|
||||||
|
};
|
||||||
|
assert_eq!(theme.id(), expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn theme_config_empty_toml_uses_defaults() {
|
||||||
|
let config: ThemeConfig = toml::from_str("").unwrap();
|
||||||
|
assert_eq!(config.theme, "catppuccin");
|
||||||
|
assert_eq!(config.border_style, BorderStyle::Rounded);
|
||||||
|
}
|
||||||
+2
-78
@@ -169,81 +169,5 @@ pub static BORDER_STYLE: LazyLock<BorderStyle> =
|
|||||||
LazyLock::new(|| THEME_CONFIG.border_style.clone());
|
LazyLock::new(|| THEME_CONFIG.border_style.clone());
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/theme.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn default_theme_config() {
|
|
||||||
let config = ThemeConfig::default();
|
|
||||||
assert_eq!(config.theme, "catppuccin");
|
|
||||||
assert_eq!(config.border_style, BorderStyle::Rounded);
|
|
||||||
assert!(config.custom.is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn border_style_roundtrip() {
|
|
||||||
let style = BorderStyle::Double;
|
|
||||||
assert_eq!(style.to_border_type(), BorderType::Double);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn theme_config_deserialize_builtin() {
|
|
||||||
let toml_str = r#"
|
|
||||||
theme = "dracula"
|
|
||||||
border_style = "plain"
|
|
||||||
"#;
|
|
||||||
let config: ThemeConfig = toml::from_str(toml_str).unwrap();
|
|
||||||
assert_eq!(config.theme, "dracula");
|
|
||||||
assert_eq!(config.border_style, BorderStyle::Plain);
|
|
||||||
assert!(config.custom.is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn theme_config_with_partial_overrides() {
|
|
||||||
let toml_str = r#"
|
|
||||||
theme = "dracula"
|
|
||||||
|
|
||||||
[custom]
|
|
||||||
accent = "Red"
|
|
||||||
"#;
|
|
||||||
let config: ThemeConfig = toml::from_str(toml_str).unwrap();
|
|
||||||
assert_eq!(config.theme, "dracula");
|
|
||||||
let overrides = config.custom.unwrap();
|
|
||||||
assert_eq!(overrides.accent, Some(Color::Red));
|
|
||||||
assert!(overrides.text.is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolve_with_overrides_keeps_base() {
|
|
||||||
let config = ThemeConfig {
|
|
||||||
theme: "dracula".to_owned(),
|
|
||||||
custom: Some(ThemeOverrides {
|
|
||||||
accent: Some(Color::Red),
|
|
||||||
..ThemeOverrides::default()
|
|
||||||
}),
|
|
||||||
..ThemeConfig::default()
|
|
||||||
};
|
|
||||||
let theme = resolve_app_theme(&config);
|
|
||||||
assert_eq!(theme.accent(), Color::Red);
|
|
||||||
let base = resolve_theme("dracula");
|
|
||||||
assert_eq!(theme.text(), base.text());
|
|
||||||
assert_eq!(theme.error(), base.error());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolve_builtin_theme() {
|
|
||||||
let config = ThemeConfig {
|
|
||||||
theme: "dracula".to_owned(),
|
|
||||||
..ThemeConfig::default()
|
|
||||||
};
|
|
||||||
let theme = resolve_app_theme(&config);
|
|
||||||
assert_eq!(theme.id(), "dracula");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn theme_config_empty_toml_uses_defaults() {
|
|
||||||
let config: ThemeConfig = toml::from_str("").unwrap();
|
|
||||||
assert_eq!(config.theme, "catppuccin");
|
|
||||||
assert_eq!(config.border_style, BorderStyle::Rounded);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -32,10 +32,13 @@ pub fn push_error(event: ErrorEvent) {
|
|||||||
Ok(mut events) => {
|
Ok(mut events) => {
|
||||||
let mut event = event;
|
let mut event = event;
|
||||||
event.id = NEXT_ERROR_ID.fetch_add(1, Ordering::Relaxed);
|
event.id = NEXT_ERROR_ID.fetch_add(1, Ordering::Relaxed);
|
||||||
|
|
||||||
events.push_back(event);
|
events.push_back(event);
|
||||||
|
|
||||||
while events.len() > MAX_ERROR_EVENTS {
|
while events.len() > MAX_ERROR_EVENTS {
|
||||||
events.pop_front();
|
events.pop_front();
|
||||||
}
|
}
|
||||||
|
super::request_redraw();
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::error!("Error buffer lock poisoned: {}", e);
|
tracing::error!("Error buffer lock poisoned: {}", e);
|
||||||
@@ -54,7 +57,13 @@ pub fn has_errors() -> bool {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn pop_error() -> Option<ErrorEvent> {
|
pub fn pop_error() -> Option<ErrorEvent> {
|
||||||
match ERROR_EVENTS.lock() {
|
match ERROR_EVENTS.lock() {
|
||||||
Ok(mut events) => events.pop_front(),
|
Ok(mut events) => {
|
||||||
|
let event = events.pop_front();
|
||||||
|
if event.is_some() {
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
event
|
||||||
|
}
|
||||||
Err(_) => None,
|
Err(_) => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -77,69 +86,5 @@ pub fn peek_all_errors() -> Vec<ErrorEvent> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/errors.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
fn make_event(msg: &str) -> ErrorEvent {
|
|
||||||
ErrorEvent {
|
|
||||||
id: 0,
|
|
||||||
level: Level::ERROR,
|
|
||||||
message: msg.to_string(),
|
|
||||||
pushed_at: Instant::now(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn push_and_pop_fifo() {
|
|
||||||
push_error(make_event("err_fifo_1"));
|
|
||||||
push_error(make_event("err_fifo_2"));
|
|
||||||
let first = pop_error();
|
|
||||||
assert!(first.is_some() || has_errors());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn has_errors_after_push() {
|
|
||||||
push_error(make_event("err_has"));
|
|
||||||
assert!(has_errors());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn peek_does_not_remove() {
|
|
||||||
push_error(make_event("err_peek"));
|
|
||||||
let before = peek_error();
|
|
||||||
assert!(before.is_some());
|
|
||||||
assert!(has_errors());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn peek_all_returns_newest_first() {
|
|
||||||
push_error(make_event("err_all_a"));
|
|
||||||
push_error(make_event("err_all_b"));
|
|
||||||
let all = peek_all_errors();
|
|
||||||
assert!(all.len() >= 2);
|
|
||||||
if all.len() >= 2 {
|
|
||||||
assert!(all[0].id >= all[1].id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn auto_assigned_ids_are_unique() {
|
|
||||||
push_error(make_event("err_id_1"));
|
|
||||||
push_error(make_event("err_id_2"));
|
|
||||||
let all = peek_all_errors();
|
|
||||||
if all.len() >= 2 {
|
|
||||||
let ids: Vec<u64> = all.iter().map(|e| e.id).collect();
|
|
||||||
let unique: std::collections::HashSet<u64> = ids.iter().copied().collect();
|
|
||||||
assert_eq!(ids.len(), unique.len());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn overflow_drops_oldest() {
|
|
||||||
for i in 0..(MAX_ERROR_EVENTS + 10) {
|
|
||||||
push_error(make_event(&format!("overflow_{i}")));
|
|
||||||
}
|
|
||||||
let all = peek_all_errors();
|
|
||||||
assert!(all.len() <= MAX_ERROR_EVENTS);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
// application feedback shared by background work and every frontend.
|
||||||
|
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
|
||||||
|
pub mod errors;
|
||||||
|
pub mod progress;
|
||||||
|
|
||||||
|
static REDRAW_REQUESTED: AtomicBool = AtomicBool::new(true);
|
||||||
|
|
||||||
|
pub fn request_redraw() {
|
||||||
|
REDRAW_REQUESTED.store(true, Ordering::Release);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn take_redraw_request() -> bool {
|
||||||
|
REDRAW_REQUESTED.swap(false, Ordering::AcqRel)
|
||||||
|
}
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
// 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};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Clone)]
|
||||||
|
pub struct ProgressState {
|
||||||
|
pub current_action: Option<String>,
|
||||||
|
pub progress: Option<(u64, u64)>,
|
||||||
|
pub sub_action: Option<String>,
|
||||||
|
tasks: BTreeMap<u64, TaskState>,
|
||||||
|
legacy_active: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
struct TaskState {
|
||||||
|
action: String,
|
||||||
|
sub_action: Option<String>,
|
||||||
|
progress: Option<(u64, u64)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub static PROGRESS: LazyLock<Arc<Mutex<ProgressState>>> =
|
||||||
|
LazyLock::new(|| Arc::new(Mutex::new(ProgressState::default())));
|
||||||
|
static NEXT_TASK_ID: AtomicU64 = AtomicU64::new(1);
|
||||||
|
|
||||||
|
pub struct ProgressTask {
|
||||||
|
id: u64,
|
||||||
|
finished: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ProgressTaskHandle {
|
||||||
|
id: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProgressTask {
|
||||||
|
pub fn start(action: impl Into<String>) -> Self {
|
||||||
|
let id = NEXT_TASK_ID.fetch_add(1, Ordering::Relaxed);
|
||||||
|
let action = action.into();
|
||||||
|
if let Ok(mut state) = PROGRESS.lock() {
|
||||||
|
state.tasks.insert(
|
||||||
|
id,
|
||||||
|
TaskState {
|
||||||
|
action: action.clone(),
|
||||||
|
sub_action: None,
|
||||||
|
progress: None,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
refresh_visible(&mut state);
|
||||||
|
}
|
||||||
|
tracing::info!("{}", action);
|
||||||
|
super::request_redraw();
|
||||||
|
Self {
|
||||||
|
id,
|
||||||
|
finished: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn handle(&self) -> ProgressTaskHandle {
|
||||||
|
ProgressTaskHandle { id: self.id }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_action(&self, text: impl Into<String>) {
|
||||||
|
update_task_action(self.id, text.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_sub_action(&self, text: impl Into<String>) {
|
||||||
|
update_task_sub_action(self.id, text.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_progress(&self, current: u64, total: u64) {
|
||||||
|
update_task_progress(self.id, current, total);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn finish(mut self) {
|
||||||
|
self.remove();
|
||||||
|
self.finished = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fail(mut self, error: impl std::fmt::Display) {
|
||||||
|
tracing::warn!("Progress task failed: {error}");
|
||||||
|
self.remove();
|
||||||
|
self.finished = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove(&self) {
|
||||||
|
if let Ok(mut state) = PROGRESS.lock() {
|
||||||
|
state.tasks.remove(&self.id);
|
||||||
|
refresh_visible(&mut state);
|
||||||
|
}
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProgressTaskHandle {
|
||||||
|
pub fn set_sub_action(&self, text: impl Into<String>) {
|
||||||
|
update_task_sub_action(self.id, text.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_progress(&self, current: u64, total: u64) {
|
||||||
|
update_task_progress(self.id, current, total);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_task_action(id: u64, text: String) {
|
||||||
|
if let Ok(mut state) = PROGRESS.lock() {
|
||||||
|
if let Some(task) = state.tasks.get_mut(&id) {
|
||||||
|
task.action = text;
|
||||||
|
task.progress = None;
|
||||||
|
}
|
||||||
|
refresh_visible(&mut state);
|
||||||
|
}
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_task_sub_action(id: u64, text: String) {
|
||||||
|
if let Ok(mut state) = PROGRESS.lock() {
|
||||||
|
if let Some(task) = state.tasks.get_mut(&id) {
|
||||||
|
task.sub_action = Some(text);
|
||||||
|
}
|
||||||
|
refresh_visible(&mut state);
|
||||||
|
}
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_task_progress(id: u64, current: u64, total: u64) {
|
||||||
|
if let Ok(mut state) = PROGRESS.lock() {
|
||||||
|
if let Some(task) = state.tasks.get_mut(&id) {
|
||||||
|
task.progress = Some((current, total));
|
||||||
|
}
|
||||||
|
refresh_visible(&mut state);
|
||||||
|
}
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for ProgressTask {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if !self.finished {
|
||||||
|
self.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refresh_visible(state: &mut ProgressState) {
|
||||||
|
if let Some((_, task)) = state.tasks.last_key_value() {
|
||||||
|
state.current_action = Some(task.action.clone());
|
||||||
|
state.sub_action.clone_from(&task.sub_action);
|
||||||
|
state.progress = task.progress;
|
||||||
|
} else if !state.legacy_active {
|
||||||
|
state.current_action = None;
|
||||||
|
state.sub_action = None;
|
||||||
|
state.progress = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Progress lock poisoned: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tracing::info!("{}", text);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_progress(current: u64, total: u64) {
|
||||||
|
match PROGRESS.lock() {
|
||||||
|
Ok(mut state) => {
|
||||||
|
state.progress = Some((current, total));
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Progress lock poisoned: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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());
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Progress lock poisoned: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tracing::debug!(" {}", text);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear() {
|
||||||
|
match PROGRESS.lock() {
|
||||||
|
Ok(mut state) => {
|
||||||
|
state.legacy_active = false;
|
||||||
|
refresh_visible(&mut state);
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Progress lock poisoned: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_active() -> bool {
|
||||||
|
PROGRESS
|
||||||
|
.lock()
|
||||||
|
.is_ok_and(|state| state.current_action.is_some())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "tests/progress.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
use super::*;
|
||||||
|
use crate::tests::TEST_LOCK;
|
||||||
|
|
||||||
|
fn clear_errors_for_test() {
|
||||||
|
ERROR_EVENTS.lock().unwrap().clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn make_event(msg: &str) -> ErrorEvent {
|
||||||
|
ErrorEvent {
|
||||||
|
id: 0,
|
||||||
|
level: Level::ERROR,
|
||||||
|
message: msg.to_string(),
|
||||||
|
pushed_at: Instant::now(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn peek_does_not_remove() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear_errors_for_test();
|
||||||
|
|
||||||
|
push_error(make_event("peek-test"));
|
||||||
|
|
||||||
|
let count_before = peek_all_errors().len();
|
||||||
|
let peeked = peek_error();
|
||||||
|
let count_after = peek_all_errors().len();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
count_before, count_after,
|
||||||
|
"peek should not change queue length"
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(peeked.is_some());
|
||||||
|
assert_eq!(peeked.unwrap().message, "peek-test");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn peek_all_returns_newest_first() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear_errors_for_test();
|
||||||
|
|
||||||
|
push_error(make_event("newest_a"));
|
||||||
|
push_error(make_event("newest_b"));
|
||||||
|
|
||||||
|
let all = peek_all_errors();
|
||||||
|
|
||||||
|
assert_eq!(all.len(), 2);
|
||||||
|
assert!(all[0].message.ends_with("_b"));
|
||||||
|
assert!(all[1].message.ends_with("_a"));
|
||||||
|
assert!(all[0].id > all[1].id);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn auto_assigned_ids_are_unique() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear_errors_for_test();
|
||||||
|
|
||||||
|
push_error(make_event("unique_1"));
|
||||||
|
push_error(make_event("unique_2"));
|
||||||
|
|
||||||
|
let all = peek_all_errors();
|
||||||
|
|
||||||
|
assert_eq!(all.len(), 2);
|
||||||
|
assert_ne!(all[0].id, all[1].id);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn overflow_drops_oldest() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear_errors_for_test();
|
||||||
|
|
||||||
|
for i in 0..(MAX_ERROR_EVENTS + 10) {
|
||||||
|
push_error(make_event(&format!("overflow_{i}")));
|
||||||
|
}
|
||||||
|
|
||||||
|
let all = peek_all_errors();
|
||||||
|
|
||||||
|
assert_eq!(all.len(), MAX_ERROR_EVENTS);
|
||||||
|
|
||||||
|
assert!(!all.iter().any(|e| e.message == "overflow_0"));
|
||||||
|
assert!(!all.iter().any(|e| e.message == "overflow_9"));
|
||||||
|
|
||||||
|
assert!(all.iter().any(|e| e.message == "overflow_10"));
|
||||||
|
assert!(all.iter().any(|e| e.message == "overflow_59"));
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
use super::*;
|
||||||
|
use crate::tests::TEST_LOCK;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn newest_task_is_visible_and_drop_restores_previous_task() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear();
|
||||||
|
let first = ProgressTask::start("first");
|
||||||
|
first.set_progress(1, 2);
|
||||||
|
{
|
||||||
|
let second = ProgressTask::start("second");
|
||||||
|
second.set_sub_action("working");
|
||||||
|
let state = PROGRESS.lock().unwrap();
|
||||||
|
assert_eq!(state.current_action.as_deref(), Some("second"));
|
||||||
|
assert_eq!(state.sub_action.as_deref(), Some("working"));
|
||||||
|
}
|
||||||
|
let state = PROGRESS.lock().unwrap();
|
||||||
|
assert_eq!(state.current_action.as_deref(), Some("first"));
|
||||||
|
assert_eq!(state.progress, Some((1, 2)));
|
||||||
|
drop(state);
|
||||||
|
first.finish();
|
||||||
|
clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn changing_phase_resets_progress_to_indeterminate() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear();
|
||||||
|
let task = ProgressTask::start("inventory");
|
||||||
|
task.set_progress(4, 10);
|
||||||
|
task.set_action("provider matching");
|
||||||
|
|
||||||
|
let state = PROGRESS.lock().unwrap();
|
||||||
|
assert_eq!(state.current_action.as_deref(), Some("provider matching"));
|
||||||
|
assert_eq!(state.progress, None);
|
||||||
|
drop(state);
|
||||||
|
|
||||||
|
task.finish();
|
||||||
|
assert!(!is_active());
|
||||||
|
clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn clearing_legacy_progress_keeps_owned_tasks() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear();
|
||||||
|
let task = ProgressTask::start("indexing");
|
||||||
|
set_action("legacy download");
|
||||||
|
clear();
|
||||||
|
|
||||||
|
let state = PROGRESS.lock().unwrap();
|
||||||
|
assert_eq!(state.current_action.as_deref(), Some("indexing"));
|
||||||
|
drop(state);
|
||||||
|
|
||||||
|
task.finish();
|
||||||
|
clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_new_legacy_action_does_not_reuse_the_previous_phase_progress() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear();
|
||||||
|
set_action("Downloading installer");
|
||||||
|
set_progress(1, 1);
|
||||||
|
|
||||||
|
set_action("Running installer");
|
||||||
|
|
||||||
|
let state = PROGRESS.lock().unwrap();
|
||||||
|
assert_eq!(state.current_action.as_deref(), Some("Running installer"));
|
||||||
|
assert_eq!(state.progress, None);
|
||||||
|
drop(state);
|
||||||
|
clear();
|
||||||
|
}
|
||||||
@@ -0,0 +1,334 @@
|
|||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use thiserror::Error;
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum ConfigSyncError {
|
||||||
|
#[error("Invalid config sync profile: {0}")]
|
||||||
|
InvalidProfile(String),
|
||||||
|
#[error("Cannot switch config profiles while '{instance}' is running")]
|
||||||
|
InstanceRunning { instance: String },
|
||||||
|
#[error("IO error: {0}")]
|
||||||
|
Io(#[from] std::io::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ConfigSyncLock {
|
||||||
|
file: std::fs::File,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for ConfigSyncLock {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Err(e) = self.file.unlock() {
|
||||||
|
tracing::warn!("Failed to release config sync lock: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn prepare(
|
||||||
|
profile: Option<&str>,
|
||||||
|
meta_dir: &Path,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
) -> Result<bool, ConfigSyncError> {
|
||||||
|
let Some(profile) = profile.and_then(normalize_profile) else {
|
||||||
|
return Ok(false);
|
||||||
|
};
|
||||||
|
validate_profile(profile)?;
|
||||||
|
|
||||||
|
let profile_dir = profile_dir(meta_dir, profile);
|
||||||
|
if !profile_dir.exists() {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
let _lock = acquire_lock(&profile_dir)?;
|
||||||
|
|
||||||
|
if !profile_payload_exists(&profile_dir)? {
|
||||||
|
sync_to_profile(minecraft_dir, &profile_dir)?;
|
||||||
|
} else {
|
||||||
|
sync_from_profile(&profile_dir, minecraft_dir)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn finish(
|
||||||
|
profile: Option<&str>,
|
||||||
|
meta_dir: &Path,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
) -> Result<(), ConfigSyncError> {
|
||||||
|
let Some(profile) = profile.and_then(normalize_profile) else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
validate_profile(profile)?;
|
||||||
|
|
||||||
|
let profile_dir = profile_dir(meta_dir, profile);
|
||||||
|
let _lock = acquire_lock(&profile_dir)?;
|
||||||
|
sync_to_profile(minecraft_dir, &profile_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() {
|
||||||
|
return Ok(profiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
for entry in std::fs::read_dir(root)? {
|
||||||
|
let entry = entry?;
|
||||||
|
if entry.file_type()?.is_dir() {
|
||||||
|
let name = entry.file_name().to_string_lossy().to_string();
|
||||||
|
if validate_profile(&name).is_ok() {
|
||||||
|
profiles.push(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
profiles.sort_unstable();
|
||||||
|
Ok(profiles)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_profile(meta_dir: &Path, profile: &str) -> Result<String, ConfigSyncError> {
|
||||||
|
let Some(profile) = normalize_profile(profile) else {
|
||||||
|
return Err(ConfigSyncError::InvalidProfile(profile.to_string()));
|
||||||
|
};
|
||||||
|
validate_profile(profile)?;
|
||||||
|
std::fs::create_dir_all(profile_dir(meta_dir, profile))?;
|
||||||
|
Ok(profile.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
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)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn switch_profile(
|
||||||
|
instance_name: &str,
|
||||||
|
current_profile: Option<&str>,
|
||||||
|
target_profile: Option<&str>,
|
||||||
|
meta_dir: &Path,
|
||||||
|
instance_dir: &Path,
|
||||||
|
) -> Result<Option<String>, ConfigSyncError> {
|
||||||
|
if crate::instance::runtime::get(instance_name).is_some() {
|
||||||
|
return Err(ConfigSyncError::InstanceRunning {
|
||||||
|
instance: instance_name.to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let current_profile = current_profile.and_then(normalize_profile);
|
||||||
|
let target_profile = target_profile.and_then(normalize_profile);
|
||||||
|
if let Some(profile) = current_profile {
|
||||||
|
validate_profile(profile)?;
|
||||||
|
}
|
||||||
|
if let Some(profile) = target_profile {
|
||||||
|
validate_profile(profile)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
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))?;
|
||||||
|
}
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some(profile) = target_profile else {
|
||||||
|
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)?;
|
||||||
|
}
|
||||||
|
sync_from_profile(&profile_dir, &minecraft_dir(instance_dir))?;
|
||||||
|
|
||||||
|
Ok(Some(profile.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_profile(profile: &str) -> Option<&str> {
|
||||||
|
let trimmed = profile.trim();
|
||||||
|
if trimmed.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(trimmed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn validate_profile(profile: &str) -> Result<(), ConfigSyncError> {
|
||||||
|
if profile.is_empty()
|
||||||
|
|| profile.len() > 64
|
||||||
|
|| profile.starts_with('.')
|
||||||
|
|| profile.contains('/')
|
||||||
|
|| profile.contains('\\')
|
||||||
|
|| 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()));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn profile_dir(meta_dir: &Path, profile: &str) -> PathBuf {
|
||||||
|
profiles_dir(meta_dir).join(profile)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn profiles_dir(meta_dir: &Path) -> PathBuf {
|
||||||
|
crate::storage::MetadataPaths::new(meta_dir).profiles()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn minecraft_dir(instance_dir: &Path) -> PathBuf {
|
||||||
|
instance_dir.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn local_backup_dir(instance_dir: &Path) -> PathBuf {
|
||||||
|
crate::storage::InstancePaths::new(instance_dir).local_config()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn acquire_lock(profile_dir: &Path) -> Result<ConfigSyncLock, ConfigSyncError> {
|
||||||
|
std::fs::create_dir_all(profile_dir)?;
|
||||||
|
let path = profile_dir.join(".lock");
|
||||||
|
let file = std::fs::OpenOptions::new()
|
||||||
|
.read(true)
|
||||||
|
.write(true)
|
||||||
|
.create(true)
|
||||||
|
.truncate(false)
|
||||||
|
.open(path)?;
|
||||||
|
file.lock()?;
|
||||||
|
Ok(ConfigSyncLock { file })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mirror_dir(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
|
||||||
|
if dst.exists() {
|
||||||
|
remove_path(dst)?;
|
||||||
|
}
|
||||||
|
std::fs::create_dir_all(dst)?;
|
||||||
|
|
||||||
|
if !src.exists() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
copy_dir_contents(src, dst)
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mirror_options(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
|
||||||
|
remove_options(dst)?;
|
||||||
|
std::fs::create_dir_all(dst)?;
|
||||||
|
if !src.exists() {
|
||||||
|
return 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))?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove_options(dir: &Path) -> Result<(), ConfigSyncError> {
|
||||||
|
if !dir.exists() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
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())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_options_file(name: &str) -> bool {
|
||||||
|
name == "options.txt" || name.starts_with("options") && name.ends_with(".txt")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove_path(path: &Path) -> Result<(), ConfigSyncError> {
|
||||||
|
let meta = std::fs::symlink_metadata(path)?;
|
||||||
|
if meta.is_dir() {
|
||||||
|
std::fs::remove_dir_all(path)?;
|
||||||
|
} else {
|
||||||
|
std::fs::remove_file(path)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn copy_dir_contents(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
|
||||||
|
for entry in std::fs::read_dir(src)? {
|
||||||
|
let entry = entry?;
|
||||||
|
let source = entry.path();
|
||||||
|
let target = dst.join(entry.file_name());
|
||||||
|
let file_type = entry.file_type()?;
|
||||||
|
|
||||||
|
if file_type.is_dir() {
|
||||||
|
std::fs::create_dir_all(&target)?;
|
||||||
|
copy_dir_contents(&source, &target)?;
|
||||||
|
} else if file_type.is_file() {
|
||||||
|
std::fs::copy(&source, &target)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "tests/config_sync.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
// data pack scanning backed by the same pack.mcmeta reader as resource packs.
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use super::entry::ContentEntry;
|
||||||
|
|
||||||
|
pub fn scan_one_datapack(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||||
|
super::packs::scan_one_pack(path, file_stem, enabled)
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,73 @@
|
|||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use super::icons::IconCell;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum WorldGameMode {
|
||||||
|
Survival,
|
||||||
|
Creative,
|
||||||
|
Adventure,
|
||||||
|
Spectator,
|
||||||
|
Hardcore,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WorldGameMode {
|
||||||
|
pub fn label(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Survival => "Survival",
|
||||||
|
Self::Creative => "Creative",
|
||||||
|
Self::Adventure => "Adventure",
|
||||||
|
Self::Spectator => "Spectator",
|
||||||
|
Self::Hardcore => "Hardcore",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct WorldDetails {
|
||||||
|
pub game_mode: Option<WorldGameMode>,
|
||||||
|
pub last_played: Option<chrono::DateTime<chrono::Utc>>,
|
||||||
|
pub minecraft_version: Option<String>,
|
||||||
|
pub size: Option<String>,
|
||||||
|
pub datapacks: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ContentEntry {
|
||||||
|
pub file_stem: String,
|
||||||
|
pub name: String,
|
||||||
|
pub source_slug: Option<String>,
|
||||||
|
pub installed_path: Option<PathBuf>,
|
||||||
|
pub provider_project: Option<super::manifest::ProviderProject>,
|
||||||
|
pub world_details: Option<WorldDetails>,
|
||||||
|
pub title_suffix: Option<String>,
|
||||||
|
pub footer_label: Option<String>,
|
||||||
|
pub footer_change: Option<(String, String)>,
|
||||||
|
pub description: String,
|
||||||
|
pub enabled: bool,
|
||||||
|
pub icon_bytes: Option<Vec<u8>>,
|
||||||
|
pub provider_icon: bool,
|
||||||
|
pub provider_description: bool,
|
||||||
|
pub path: PathBuf,
|
||||||
|
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))
|
||||||
|
}
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
// 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,
|
||||||
|
pub bg_r: u8,
|
||||||
|
pub bg_g: u8,
|
||||||
|
pub bg_b: u8,
|
||||||
|
pub fg_r: u8,
|
||||||
|
pub fg_g: u8,
|
||||||
|
pub fg_b: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn make_icon_pixels(
|
||||||
|
bytes: &[u8],
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
) -> Option<Vec<Vec<IconCell>>> {
|
||||||
|
let image = image::load_from_memory(bytes).ok()?;
|
||||||
|
Some(make_icon_pixels_from_image(&image, width, height))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn make_icon_pixels_from_image(
|
||||||
|
image: &image::DynamicImage,
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
) -> Vec<Vec<IconCell>> {
|
||||||
|
let resized = image.resize_exact(
|
||||||
|
u32::from(width),
|
||||||
|
u32::from(height) * 2,
|
||||||
|
image::imageops::FilterType::Nearest,
|
||||||
|
);
|
||||||
|
let rgb = resized.to_rgb8();
|
||||||
|
|
||||||
|
let mut rows = Vec::new();
|
||||||
|
for row in 0..height {
|
||||||
|
let mut columns = Vec::new();
|
||||||
|
for column in 0..width {
|
||||||
|
let top_y = u32::from(row) * 2;
|
||||||
|
let bottom_y = (top_y + 1).min(rgb.height().saturating_sub(1));
|
||||||
|
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}',
|
||||||
|
bg_r: br,
|
||||||
|
bg_g: bg,
|
||||||
|
bg_b: bb,
|
||||||
|
fg_r: tr,
|
||||||
|
fg_g: tg,
|
||||||
|
fg_b: tb,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
rows.push(columns);
|
||||||
|
}
|
||||||
|
rows
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn make_icon_quadrants_from_image(
|
||||||
|
image: &image::DynamicImage,
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
) -> Vec<Vec<IconCell>> {
|
||||||
|
let resized = image
|
||||||
|
.resize_exact(
|
||||||
|
u32::from(width) * 2,
|
||||||
|
u32::from(height) * 2,
|
||||||
|
image::imageops::FilterType::Lanczos3,
|
||||||
|
)
|
||||||
|
.to_rgb8();
|
||||||
|
|
||||||
|
(0..height)
|
||||||
|
.map(|row| {
|
||||||
|
(0..width)
|
||||||
|
.map(|column| {
|
||||||
|
let x = u32::from(column) * 2;
|
||||||
|
let y = u32::from(row) * 2;
|
||||||
|
quadrant_cell([
|
||||||
|
resized.get_pixel(x, y).0,
|
||||||
|
resized.get_pixel(x + 1, y).0,
|
||||||
|
resized.get_pixel(x, y + 1).0,
|
||||||
|
resized.get_pixel(x + 1, y + 1).0,
|
||||||
|
])
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn quadrant_cell(pixels: [[u8; 3]; 4]) -> IconCell {
|
||||||
|
let mut pair = (0, 0);
|
||||||
|
let mut max_distance = 0;
|
||||||
|
for left in 0..pixels.len() {
|
||||||
|
for right in (left + 1)..pixels.len() {
|
||||||
|
let distance = color_distance(pixels[left], pixels[right]);
|
||||||
|
if distance > max_distance {
|
||||||
|
max_distance = distance;
|
||||||
|
pair = (left, right);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let bg = pixels[pair.0];
|
||||||
|
let fg = pixels[pair.1];
|
||||||
|
let mask = pixels
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.fold(0_u8, |mask, (index, pixel)| {
|
||||||
|
if color_distance(*pixel, fg) <= color_distance(*pixel, bg) {
|
||||||
|
mask | (1 << index)
|
||||||
|
} else {
|
||||||
|
mask
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let symbol = match mask {
|
||||||
|
0 => ' ',
|
||||||
|
1 => '\u{2598}',
|
||||||
|
2 => '\u{259d}',
|
||||||
|
3 => '\u{2580}',
|
||||||
|
4 => '\u{2596}',
|
||||||
|
5 => '\u{258c}',
|
||||||
|
6 => '\u{259e}',
|
||||||
|
7 => '\u{259b}',
|
||||||
|
8 => '\u{2597}',
|
||||||
|
9 => '\u{259a}',
|
||||||
|
10 => '\u{2590}',
|
||||||
|
11 => '\u{259c}',
|
||||||
|
12 => '\u{2584}',
|
||||||
|
13 => '\u{2599}',
|
||||||
|
14 => '\u{259f}',
|
||||||
|
_ => '\u{2588}',
|
||||||
|
};
|
||||||
|
|
||||||
|
IconCell {
|
||||||
|
symbol,
|
||||||
|
bg_r: bg[0],
|
||||||
|
bg_g: bg[1],
|
||||||
|
bg_b: bg[2],
|
||||||
|
fg_r: fg[0],
|
||||||
|
fg_g: fg[1],
|
||||||
|
fg_b: fg[2],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn color_distance(left: [u8; 3], right: [u8; 3]) -> u32 {
|
||||||
|
left.into_iter()
|
||||||
|
.zip(right)
|
||||||
|
.map(|(left, right)| {
|
||||||
|
let delta = i32::from(left) - i32::from(right);
|
||||||
|
(delta * delta) as u32
|
||||||
|
})
|
||||||
|
.sum()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6 columns by 3 terminal rows is physically square with the usual 1:2 cell ratio.
|
||||||
|
pub(crate) fn fallback_icon() -> Vec<Vec<IconCell>> {
|
||||||
|
const MASK: [[bool; 6]; 6] = [
|
||||||
|
[false, true, true, true, true, false],
|
||||||
|
[true, false, false, false, false, true],
|
||||||
|
[false, false, false, true, true, false],
|
||||||
|
[false, false, true, true, false, false],
|
||||||
|
[false, false, false, false, false, false],
|
||||||
|
[false, false, true, true, false, false],
|
||||||
|
];
|
||||||
|
MASK.chunks_exact(2)
|
||||||
|
.map(|pair| {
|
||||||
|
pair[0]
|
||||||
|
.iter()
|
||||||
|
.zip(pair[1])
|
||||||
|
.map(|(&top, bottom)| fallback_cell(top, bottom))
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fallback_cell(top: bool, bottom: bool) -> IconCell {
|
||||||
|
let background = if top { 150 } else { 45 };
|
||||||
|
let foreground = if bottom { 150 } else { 45 };
|
||||||
|
IconCell {
|
||||||
|
symbol: '\u{2584}',
|
||||||
|
bg_r: background,
|
||||||
|
bg_g: background,
|
||||||
|
bg_b: background,
|
||||||
|
fg_r: foreground,
|
||||||
|
fg_g: foreground,
|
||||||
|
fg_b: foreground,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn fallback_icon_large() -> Vec<Vec<IconCell>> {
|
||||||
|
let background = IconCell {
|
||||||
|
symbol: '\u{2584}',
|
||||||
|
bg_r: 50,
|
||||||
|
bg_g: 50,
|
||||||
|
bg_b: 50,
|
||||||
|
fg_r: 50,
|
||||||
|
fg_g: 50,
|
||||||
|
fg_b: 50,
|
||||||
|
};
|
||||||
|
let bottom = IconCell {
|
||||||
|
symbol: '\u{2584}',
|
||||||
|
bg_r: 50,
|
||||||
|
bg_g: 50,
|
||||||
|
bg_b: 50,
|
||||||
|
fg_r: 130,
|
||||||
|
fg_g: 130,
|
||||||
|
fg_b: 130,
|
||||||
|
};
|
||||||
|
let top = IconCell {
|
||||||
|
symbol: '\u{2584}',
|
||||||
|
bg_r: 130,
|
||||||
|
bg_g: 130,
|
||||||
|
bg_b: 130,
|
||||||
|
fg_r: 50,
|
||||||
|
fg_g: 50,
|
||||||
|
fg_b: 50,
|
||||||
|
};
|
||||||
|
vec![
|
||||||
|
vec![
|
||||||
|
background, background, bottom, bottom, bottom, bottom, bottom, bottom, bottom, bottom,
|
||||||
|
background, background,
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
background, background, bottom, bottom, bottom, bottom, bottom, bottom, bottom, bottom,
|
||||||
|
background, background,
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
background, background, background, background, background, background, top, top, top,
|
||||||
|
top, background, background,
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
background, background, background, background, background, background, top, top, top,
|
||||||
|
top, background, background,
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
background, background, background, background, top, top, top, top, background,
|
||||||
|
background, background, background,
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
background, background, background, background, top, top, top, top, background,
|
||||||
|
background, background, background,
|
||||||
|
],
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/content/icons.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,464 @@
|
|||||||
|
use std::collections::{BTreeMap, HashMap};
|
||||||
|
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()));
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum ContentKind {
|
||||||
|
Mod,
|
||||||
|
ResourcePack,
|
||||||
|
Shader,
|
||||||
|
DataPack,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ContentKind {
|
||||||
|
pub fn directory(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Mod => "mods",
|
||||||
|
Self::ResourcePack => "resourcepacks",
|
||||||
|
Self::Shader => "shaderpacks",
|
||||||
|
Self::DataPack => "datapacks",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn unavailable_message(self, loader: crate::instance::ModLoader) -> Option<&'static str> {
|
||||||
|
if loader != crate::instance::ModLoader::Vanilla {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
match self {
|
||||||
|
Self::Mod => Some("Vanilla does not support mods."),
|
||||||
|
Self::Shader => Some("Vanilla does not support shaders."),
|
||||||
|
Self::ResourcePack | Self::DataPack => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct ProviderProject {
|
||||||
|
pub provider: String,
|
||||||
|
pub project_id: String,
|
||||||
|
pub version_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "status", rename_all = "snake_case")]
|
||||||
|
pub enum Resolution {
|
||||||
|
#[default]
|
||||||
|
Pending,
|
||||||
|
Resolved {
|
||||||
|
project: ProviderProject,
|
||||||
|
},
|
||||||
|
Unmatched {
|
||||||
|
checked_at: i64,
|
||||||
|
providers: Vec<String>,
|
||||||
|
},
|
||||||
|
Ambiguous {
|
||||||
|
candidates: Vec<ProviderProject>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct FileFingerprint {
|
||||||
|
pub size: u64,
|
||||||
|
pub modified_ns: u128,
|
||||||
|
pub hashes: BTreeMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FileFingerprint {
|
||||||
|
pub fn hash(&self, algorithm: &str) -> Option<&str> {
|
||||||
|
self.hashes.get(algorithm).map(String::as_str)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct ContentFileRecord {
|
||||||
|
pub relative_path: PathBuf,
|
||||||
|
pub kind: ContentKind,
|
||||||
|
pub enabled: bool,
|
||||||
|
pub fingerprint: FileFingerprint,
|
||||||
|
#[serde(default)]
|
||||||
|
pub resolution: Resolution,
|
||||||
|
#[serde(default)]
|
||||||
|
pub provider_aliases: Vec<ProviderProject>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub provider_checks: Vec<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub required_dependencies: Vec<ProviderProject>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub automatic_dependency: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub cleanup_eligible: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct ContentManifest {
|
||||||
|
pub version: u32,
|
||||||
|
#[serde(default)]
|
||||||
|
pub files: Vec<ContentFileRecord>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ContentManifest {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
version: MANIFEST_VERSION,
|
||||||
|
files: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ContentManifest {
|
||||||
|
pub fn load(path: &Path) -> Result<Self, ManifestError> {
|
||||||
|
if !path.exists() {
|
||||||
|
return Ok(Self::default());
|
||||||
|
}
|
||||||
|
let bytes = std::fs::read(path)?;
|
||||||
|
let manifest: Self = serde_json::from_slice(&bytes)?;
|
||||||
|
if manifest.version != MANIFEST_VERSION {
|
||||||
|
return Err(ManifestError::UnsupportedVersion(manifest.version));
|
||||||
|
}
|
||||||
|
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(())
|
||||||
|
}
|
||||||
|
|
||||||
|
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 result = update(&mut manifest)?;
|
||||||
|
manifest.save(path)?;
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn record(&self, relative_path: &Path) -> Option<&ContentFileRecord> {
|
||||||
|
self.files
|
||||||
|
.iter()
|
||||||
|
.find(|record| record.relative_path == relative_path)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn upsert(&mut self, record: ContentFileRecord) {
|
||||||
|
if let Some(existing) = self
|
||||||
|
.files
|
||||||
|
.iter_mut()
|
||||||
|
.find(|existing| existing.relative_path == record.relative_path)
|
||||||
|
{
|
||||||
|
*existing = record;
|
||||||
|
} else {
|
||||||
|
self.files.push(record);
|
||||||
|
self.files
|
||||||
|
.sort_by(|left, right| left.relative_path.cmp(&right.relative_path));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove(&mut self, relative_path: &Path) {
|
||||||
|
self.files
|
||||||
|
.retain(|record| record.relative_path != relative_path);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn rename_record(&mut self, from: &Path, to: &Path, enabled: bool) -> bool {
|
||||||
|
let Some(index) = self
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.position(|record| record.relative_path == from || record.relative_path == to)
|
||||||
|
else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let mut record = self.files.remove(index);
|
||||||
|
record.relative_path = to.to_owned();
|
||||||
|
record.enabled = enabled;
|
||||||
|
self.upsert(record);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resolved_project_path(
|
||||||
|
&self,
|
||||||
|
provider: &str,
|
||||||
|
project_id: &str,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
) -> Option<PathBuf> {
|
||||||
|
self.files.iter().find_map(|record| {
|
||||||
|
record
|
||||||
|
.matches_project(provider, project_id)
|
||||||
|
.then(|| minecraft_dir.join(&record.relative_path))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resolved_project_path_under(
|
||||||
|
&self,
|
||||||
|
provider: &str,
|
||||||
|
project_id: &str,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
directory: &Path,
|
||||||
|
) -> Option<PathBuf> {
|
||||||
|
self.files.iter().find_map(|record| {
|
||||||
|
let path = minecraft_dir.join(&record.relative_path);
|
||||||
|
(record.matches_project(provider, project_id) && path.starts_with(directory))
|
||||||
|
.then_some(path)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resolved_project_record(
|
||||||
|
&self,
|
||||||
|
provider: &str,
|
||||||
|
project_id: &str,
|
||||||
|
) -> Option<&ContentFileRecord> {
|
||||||
|
self.files
|
||||||
|
.iter()
|
||||||
|
.find(|record| record.matches_project(provider, project_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn dependent_paths(&self, relative_path: &Path) -> Vec<PathBuf> {
|
||||||
|
let Some(target) = self.record(relative_path) else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
self.files
|
||||||
|
.iter()
|
||||||
|
.filter(|record| record.relative_path != relative_path)
|
||||||
|
.filter(|record| dependency_applies(target, record))
|
||||||
|
.map(|record| record.relative_path.clone())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn orphaned_dependencies_after_removing(&self, relative_path: &Path) -> Vec<PathBuf> {
|
||||||
|
self.orphaned_dependencies_with_removed(std::iter::once(relative_path.to_owned()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn orphaned_dependencies(&self) -> Vec<PathBuf> {
|
||||||
|
self.orphaned_dependencies_with_removed(std::iter::empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn orphaned_dependencies_with_removed(
|
||||||
|
&self,
|
||||||
|
removed: impl IntoIterator<Item = PathBuf>,
|
||||||
|
) -> Vec<PathBuf> {
|
||||||
|
let mut removed = removed
|
||||||
|
.into_iter()
|
||||||
|
.collect::<std::collections::HashSet<_>>();
|
||||||
|
let mut orphans = Vec::new();
|
||||||
|
loop {
|
||||||
|
let mut found = false;
|
||||||
|
for candidate in &self.files {
|
||||||
|
if !candidate.automatic_dependency
|
||||||
|
|| !candidate.cleanup_eligible
|
||||||
|
|| removed.contains(&candidate.relative_path)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let still_required = self
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.filter(|record| !removed.contains(&record.relative_path))
|
||||||
|
.any(|record| dependency_applies(candidate, record));
|
||||||
|
if !still_required {
|
||||||
|
removed.insert(candidate.relative_path.clone());
|
||||||
|
orphans.push(candidate.relative_path.clone());
|
||||||
|
found = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
orphans
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dependency_applies(candidate: &ContentFileRecord, dependent: &ContentFileRecord) -> bool {
|
||||||
|
let matches = dependent
|
||||||
|
.required_dependencies
|
||||||
|
.iter()
|
||||||
|
.any(|dependency| candidate.matches_project(&dependency.provider, &dependency.project_id));
|
||||||
|
if !matches || candidate.kind != ContentKind::DataPack {
|
||||||
|
return matches;
|
||||||
|
}
|
||||||
|
datapack_world(&candidate.relative_path) == datapack_world(&dependent.relative_path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn datapack_world(path: &Path) -> Option<&std::ffi::OsStr> {
|
||||||
|
let mut components = path.components();
|
||||||
|
(components.next()?.as_os_str() == "saves")
|
||||||
|
.then(|| components.next().map(std::path::Component::as_os_str))
|
||||||
|
.flatten()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ContentFileRecord {
|
||||||
|
pub fn resolved_project(&self) -> Option<&ProviderProject> {
|
||||||
|
match &self.resolution {
|
||||||
|
Resolution::Resolved { project } => Some(project),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn matches_project(&self, provider: &str, project_id: &str) -> bool {
|
||||||
|
self.resolved_project()
|
||||||
|
.into_iter()
|
||||||
|
.chain(self.provider_aliases.iter())
|
||||||
|
.any(|project| project.provider == provider && project.project_id == project_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn project_for_provider(
|
||||||
|
&self,
|
||||||
|
provider: &str,
|
||||||
|
project_id: &str,
|
||||||
|
) -> Option<&ProviderProject> {
|
||||||
|
self.resolved_project()
|
||||||
|
.into_iter()
|
||||||
|
.chain(self.provider_aliases.iter())
|
||||||
|
.find(|project| project.provider == provider && project.project_id == project_id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum ManifestError {
|
||||||
|
#[error("I/O error: {0}")]
|
||||||
|
Io(#[from] std::io::Error),
|
||||||
|
#[error("JSON error: {0}")]
|
||||||
|
Json(#[from] serde_json::Error),
|
||||||
|
#[error("Unsupported content manifest version {0}")]
|
||||||
|
UnsupportedVersion(u32),
|
||||||
|
#[error("Invalid manifest path: {0}")]
|
||||||
|
InvalidPath(String),
|
||||||
|
#[error("Content manifest lock was poisoned")]
|
||||||
|
LockPoisoned,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fingerprint(path: &Path) -> Result<FileFingerprint, std::io::Error> {
|
||||||
|
let metadata = std::fs::metadata(path)?;
|
||||||
|
let modified_ns = metadata
|
||||||
|
.modified()
|
||||||
|
.unwrap_or(SystemTime::UNIX_EPOCH)
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.unwrap_or_default()
|
||||||
|
.as_nanos();
|
||||||
|
let mut file = std::fs::File::open(path)?;
|
||||||
|
let mut sha1 = sha1::Sha1::new();
|
||||||
|
let mut sha512 = sha2::Sha512::new();
|
||||||
|
let mut curseforge_len = 0u32;
|
||||||
|
let mut buffer = [0u8; 64 * 1024];
|
||||||
|
loop {
|
||||||
|
let read = file.read(&mut buffer)?;
|
||||||
|
if read == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
sha1.update(&buffer[..read]);
|
||||||
|
sha512.update(&buffer[..read]);
|
||||||
|
curseforge_len = curseforge_len.saturating_add(
|
||||||
|
buffer[..read]
|
||||||
|
.iter()
|
||||||
|
.filter(|byte| !matches!(byte, b'\t' | b'\n' | b'\r' | b' '))
|
||||||
|
.count() as u32,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
file.rewind()?;
|
||||||
|
let hashes = BTreeMap::from([
|
||||||
|
("sha1".to_owned(), format!("{:x}", sha1.finalize())),
|
||||||
|
("sha512".to_owned(), format!("{:x}", sha512.finalize())),
|
||||||
|
(
|
||||||
|
"curseforge".to_owned(),
|
||||||
|
curseforge_fingerprint(&mut file, curseforge_len)?.to_string(),
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
Ok(FileFingerprint {
|
||||||
|
size: metadata.len(),
|
||||||
|
modified_ns,
|
||||||
|
hashes,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn curseforge_fingerprint(reader: &mut impl Read, length: u32) -> 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 {
|
||||||
|
let read = reader.read(&mut buffer)?;
|
||||||
|
if read == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
for &byte in &buffer[..read] {
|
||||||
|
if matches!(byte, b'\t' | b'\n' | b'\r' | b' ') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
block[block_len] = byte;
|
||||||
|
block_len += 1;
|
||||||
|
if block_len == 4 {
|
||||||
|
let mut value = u32::from_le_bytes(block);
|
||||||
|
value = value.wrapping_mul(M);
|
||||||
|
value ^= value >> 24;
|
||||||
|
value = value.wrapping_mul(M);
|
||||||
|
hash = hash.wrapping_mul(M) ^ value;
|
||||||
|
block_len = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match block_len {
|
||||||
|
3 => {
|
||||||
|
hash ^= u32::from(block[2]) << 16;
|
||||||
|
hash ^= u32::from(block[1]) << 8;
|
||||||
|
hash ^= u32::from(block[0]);
|
||||||
|
hash = hash.wrapping_mul(M);
|
||||||
|
}
|
||||||
|
2 => {
|
||||||
|
hash ^= u32::from(block[1]) << 8;
|
||||||
|
hash ^= u32::from(block[0]);
|
||||||
|
hash = hash.wrapping_mul(M);
|
||||||
|
}
|
||||||
|
1 => {
|
||||||
|
hash ^= u32::from(block[0]);
|
||||||
|
hash = hash.wrapping_mul(M);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
hash ^= hash >> 13;
|
||||||
|
hash = hash.wrapping_mul(M);
|
||||||
|
hash ^= hash >> 15;
|
||||||
|
Ok(hash)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fingerprint_metadata(path: &Path) -> Result<FileFingerprint, std::io::Error> {
|
||||||
|
let metadata = std::fs::metadata(path)?;
|
||||||
|
let modified_ns = metadata
|
||||||
|
.modified()
|
||||||
|
.unwrap_or(SystemTime::UNIX_EPOCH)
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.unwrap_or_default()
|
||||||
|
.as_nanos();
|
||||||
|
Ok(FileFingerprint {
|
||||||
|
size: metadata.len(),
|
||||||
|
modified_ns,
|
||||||
|
hashes: BTreeMap::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/content/manifest.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -1,16 +1,29 @@
|
|||||||
// scanning and toggling instance content (mods, resource packs, shaders, worlds).
|
// 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.
|
// 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 mod manifest;
|
||||||
pub mod mods;
|
pub mod mods;
|
||||||
|
mod packs;
|
||||||
|
pub mod provider;
|
||||||
|
pub mod reconcile;
|
||||||
pub mod resource_packs;
|
pub mod resource_packs;
|
||||||
pub mod shaders;
|
pub mod shaders;
|
||||||
|
pub mod updates;
|
||||||
pub mod worlds;
|
pub mod worlds;
|
||||||
|
|
||||||
pub use mods::{ContentEntry, scan_mods, toggle_entry};
|
pub use datapacks::scan_one_datapack;
|
||||||
pub use mods::scan_one_mod;
|
pub(crate) use icons::{
|
||||||
pub use resource_packs::{scan_resource_packs, scan_one_resource_pack};
|
IconCell, fallback_icon, fallback_icon_large, make_icon_pixels, make_icon_pixels_from_image,
|
||||||
pub use shaders::{scan_shaders, scan_one_shader};
|
make_icon_quadrants_from_image,
|
||||||
pub use worlds::{scan_worlds, scan_one_world};
|
};
|
||||||
|
pub use mods::{scan_mods, scan_one_mod};
|
||||||
|
pub use resource_packs::{scan_one_resource_pack, scan_resource_packs};
|
||||||
|
pub use shaders::{scan_one_shader, scan_shaders};
|
||||||
|
pub use worlds::{scan_one_world, scan_worlds};
|
||||||
|
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
|
|
||||||
|
|||||||
+76
-453
@@ -1,36 +1,16 @@
|
|||||||
// mod scanning, metadata extraction, and icon rendering for the content list.
|
// mod scanning and loader-specific metadata extraction.
|
||||||
// jar files are just zips, so it cracks them open looking for loader-specific
|
// 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
|
// 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
|
// 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.
|
// root-level icon paths (logo.png, icon.png, pack.png) or just the filename.
|
||||||
|
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::Path;
|
||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
// a single "pixel" in the terminal icon. uses the unicode half-block trick
|
use super::entry::ContentEntry;
|
||||||
// where each character cell shows two vertical pixels (fg = top, bg = bottom)
|
use super::icons::{fallback_icon, make_icon_pixels};
|
||||||
#[derive(Debug, Clone, Copy)]
|
|
||||||
pub struct IconCell {
|
|
||||||
pub bg_r: u8,
|
|
||||||
pub bg_g: u8,
|
|
||||||
pub bg_b: u8,
|
|
||||||
pub fg_r: u8,
|
|
||||||
pub fg_g: u8,
|
|
||||||
pub fg_b: u8,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct ContentEntry {
|
|
||||||
pub file_stem: String,
|
|
||||||
pub name: String,
|
|
||||||
pub description: String,
|
|
||||||
pub enabled: bool,
|
|
||||||
pub icon_bytes: Option<Vec<u8>>,
|
|
||||||
pub path: PathBuf,
|
|
||||||
pub icon_lines: Option<Vec<Vec<IconCell>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize, Default)]
|
#[derive(Deserialize, Default)]
|
||||||
struct FabricModJson {
|
struct FabricModJson {
|
||||||
@@ -39,6 +19,8 @@ struct FabricModJson {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
description: String,
|
description: String,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
version: String,
|
||||||
|
#[serde(default)]
|
||||||
icon: serde_json::Value,
|
icon: serde_json::Value,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,6 +53,8 @@ struct QuiltModJson {
|
|||||||
|
|
||||||
#[derive(Deserialize, Default)]
|
#[derive(Deserialize, Default)]
|
||||||
struct QuiltLoader {
|
struct QuiltLoader {
|
||||||
|
#[serde(default)]
|
||||||
|
version: String,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
metadata: QuiltMetadata,
|
metadata: QuiltMetadata,
|
||||||
}
|
}
|
||||||
@@ -92,7 +76,7 @@ impl QuiltMetadata {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn scan_one_mod(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
pub fn scan_one_mod(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||||
let (name, description, icon_bytes) = read_mod_metadata(path);
|
let (name, description, version, icon_bytes) = read_mod_metadata(path);
|
||||||
let icon_lines = icon_bytes
|
let icon_lines = icon_bytes
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
|
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
|
||||||
@@ -107,9 +91,18 @@ pub fn scan_one_mod(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry
|
|||||||
ContentEntry {
|
ContentEntry {
|
||||||
file_stem: file_stem.to_owned(),
|
file_stem: file_stem.to_owned(),
|
||||||
name: display_name,
|
name: display_name,
|
||||||
|
source_slug: None,
|
||||||
|
installed_path: None,
|
||||||
|
provider_project: None,
|
||||||
|
world_details: None,
|
||||||
|
title_suffix: None,
|
||||||
|
footer_label: display_version(version),
|
||||||
|
footer_change: None,
|
||||||
description,
|
description,
|
||||||
enabled,
|
enabled,
|
||||||
icon_bytes,
|
icon_bytes,
|
||||||
|
provider_icon: false,
|
||||||
|
provider_description: false,
|
||||||
path: path.to_path_buf(),
|
path: path.to_path_buf(),
|
||||||
icon_lines,
|
icon_lines,
|
||||||
}
|
}
|
||||||
@@ -118,7 +111,7 @@ pub fn scan_one_mod(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry
|
|||||||
pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||||
let mods_dir = instances_dir
|
let mods_dir = instances_dir
|
||||||
.join(instance_name)
|
.join(instance_name)
|
||||||
.join(".minecraft")
|
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||||
.join("mods");
|
.join("mods");
|
||||||
|
|
||||||
let read_dir = match std::fs::read_dir(&mods_dir) {
|
let read_dir = match std::fs::read_dir(&mods_dir) {
|
||||||
@@ -150,20 +143,31 @@ pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry>
|
|||||||
// checks fabric.mod.json, quilt.mod.json, META-INF/mods.toml (forge),
|
// 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
|
// META-INF/neoforge.mods.toml, and mcmod.info (legacy forge). if none of
|
||||||
// those yield an icon, falls back to common root-level paths.
|
// those yield an icon, falls back to common root-level paths.
|
||||||
fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
|
fn read_mod_metadata(jar_path: &Path) -> (String, String, String, Option<Vec<u8>>) {
|
||||||
let file = match std::fs::File::open(jar_path) {
|
let file = match std::fs::File::open(jar_path) {
|
||||||
Ok(file) => file,
|
Ok(file) => file,
|
||||||
Err(_) => return (String::new(), String::new(), None),
|
Err(e) => {
|
||||||
|
tracing::trace!("Failed to open mod JAR {}: {}", jar_path.display(), e);
|
||||||
|
return (String::new(), String::new(), String::new(), None);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut archive = match zip::ZipArchive::new(file) {
|
let mut archive = match zip::ZipArchive::new(file) {
|
||||||
Ok(archive) => archive,
|
Ok(archive) => archive,
|
||||||
Err(_) => return (String::new(), String::new(), None),
|
Err(e) => {
|
||||||
|
tracing::trace!(
|
||||||
|
"Failed to read mod JAR as ZIP {}: {}",
|
||||||
|
jar_path.display(),
|
||||||
|
e
|
||||||
|
);
|
||||||
|
return (String::new(), String::new(), String::new(), None);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// try each loader's metadata in order. if we get metadata but the
|
// try each loader's metadata in order. if we get metadata but the
|
||||||
// declared icon path is missing, fall back to common root-level icons.
|
// declared icon path is missing, fall back to common root-level icons.
|
||||||
type MetaReader = fn(&mut zip::ZipArchive<std::fs::File>) -> Option<(String, String, String)>;
|
type MetaReader =
|
||||||
|
fn(&mut zip::ZipArchive<std::fs::File>) -> Option<(String, String, String, String)>;
|
||||||
let readers: [MetaReader; 4] = [
|
let readers: [MetaReader; 4] = [
|
||||||
read_fabric_meta,
|
read_fabric_meta,
|
||||||
read_quilt_meta,
|
read_quilt_meta,
|
||||||
@@ -172,7 +176,7 @@ fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
|
|||||||
];
|
];
|
||||||
|
|
||||||
for reader in &readers {
|
for reader in &readers {
|
||||||
if let Some((name, description, icon_path)) = reader(&mut archive) {
|
if let Some((name, description, version, icon_path)) = reader(&mut archive) {
|
||||||
let icon_path = icon_path.trim_start_matches('/');
|
let icon_path = icon_path.trim_start_matches('/');
|
||||||
let icon = if icon_path.is_empty() {
|
let icon = if icon_path.is_empty() {
|
||||||
None
|
None
|
||||||
@@ -180,13 +184,29 @@ fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
|
|||||||
read_zip_bytes(&mut archive, icon_path)
|
read_zip_bytes(&mut archive, icon_path)
|
||||||
}
|
}
|
||||||
.or_else(|| try_fallback_icons(&mut archive));
|
.or_else(|| try_fallback_icons(&mut archive));
|
||||||
return (name, description, icon);
|
tracing::trace!(
|
||||||
|
"Read mod metadata from {}: name='{}' icon_declared={}",
|
||||||
|
jar_path.display(),
|
||||||
|
name,
|
||||||
|
!icon_path.is_empty()
|
||||||
|
);
|
||||||
|
return (name, description, version, icon);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// no recognized metadata at all, try common icon paths
|
// no recognized metadata at all, try common icon paths
|
||||||
let icon_bytes = try_fallback_icons(&mut archive);
|
let icon_bytes = try_fallback_icons(&mut archive);
|
||||||
(String::new(), String::new(), icon_bytes)
|
tracing::trace!(
|
||||||
|
"No recognized mod metadata in {}; fallback_icon={}",
|
||||||
|
jar_path.display(),
|
||||||
|
icon_bytes.is_some()
|
||||||
|
);
|
||||||
|
(String::new(), String::new(), String::new(), icon_bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn display_version(version: String) -> Option<String> {
|
||||||
|
let version = version.trim();
|
||||||
|
(!version.is_empty() && !version.contains("${")).then(|| version.to_owned())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn try_fallback_icons(archive: &mut zip::ZipArchive<std::fs::File>) -> Option<Vec<u8>> {
|
fn try_fallback_icons(archive: &mut zip::ZipArchive<std::fs::File>) -> Option<Vec<u8>> {
|
||||||
@@ -200,27 +220,28 @@ fn try_fallback_icons(archive: &mut zip::ZipArchive<std::fs::File>) -> Option<Ve
|
|||||||
|
|
||||||
fn read_fabric_meta(
|
fn read_fabric_meta(
|
||||||
archive: &mut zip::ZipArchive<std::fs::File>,
|
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||||
) -> Option<(String, String, String)> {
|
) -> Option<(String, String, String, String)> {
|
||||||
let mut entry = archive.by_name("fabric.mod.json").ok()?;
|
let mut entry = archive.by_name("fabric.mod.json").ok()?;
|
||||||
let mut raw = String::new();
|
let mut raw = String::new();
|
||||||
entry.read_to_string(&mut raw).ok()?;
|
entry.read_to_string(&mut raw).ok()?;
|
||||||
let sanitized = sanitize_json_strings(&raw);
|
let sanitized = sanitize_json_strings(&raw);
|
||||||
let data: FabricModJson = serde_json::from_str(&sanitized).ok()?;
|
let data: FabricModJson = serde_json::from_str(&sanitized).ok()?;
|
||||||
let icon = data.icon_path();
|
let icon = data.icon_path();
|
||||||
Some((data.name, data.description, icon))
|
Some((data.name, data.description, data.version, icon))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_quilt_meta(
|
fn read_quilt_meta(
|
||||||
archive: &mut zip::ZipArchive<std::fs::File>,
|
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||||
) -> Option<(String, String, String)> {
|
) -> Option<(String, String, String, String)> {
|
||||||
let mut entry = archive.by_name("quilt.mod.json").ok()?;
|
let mut entry = archive.by_name("quilt.mod.json").ok()?;
|
||||||
let mut raw = String::new();
|
let mut raw = String::new();
|
||||||
entry.read_to_string(&mut raw).ok()?;
|
entry.read_to_string(&mut raw).ok()?;
|
||||||
let sanitized = sanitize_json_strings(&raw);
|
let sanitized = sanitize_json_strings(&raw);
|
||||||
let data: QuiltModJson = serde_json::from_str(&sanitized).ok()?;
|
let data: QuiltModJson = serde_json::from_str(&sanitized).ok()?;
|
||||||
|
let version = data.quilt_loader.version;
|
||||||
let meta = data.quilt_loader.metadata;
|
let meta = data.quilt_loader.metadata;
|
||||||
let icon = meta.icon_path();
|
let icon = meta.icon_path();
|
||||||
Some((meta.name, meta.description, icon))
|
Some((meta.name, meta.description, version, icon))
|
||||||
}
|
}
|
||||||
|
|
||||||
// forge (META-INF/mods.toml) and neoforge (META-INF/neoforge.mods.toml)
|
// forge (META-INF/mods.toml) and neoforge (META-INF/neoforge.mods.toml)
|
||||||
@@ -230,7 +251,7 @@ fn read_quilt_meta(
|
|||||||
// but no [[mods]] section. we still want the icon in that case.
|
// but no [[mods]] section. we still want the icon in that case.
|
||||||
fn read_forge_toml_meta(
|
fn read_forge_toml_meta(
|
||||||
archive: &mut zip::ZipArchive<std::fs::File>,
|
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||||
) -> Option<(String, String, String)> {
|
) -> Option<(String, String, String, String)> {
|
||||||
let raw = read_zip_string(archive, "META-INF/neoforge.mods.toml")
|
let raw = read_zip_string(archive, "META-INF/neoforge.mods.toml")
|
||||||
.or_else(|| read_zip_string(archive, "META-INF/mods.toml"))?;
|
.or_else(|| read_zip_string(archive, "META-INF/mods.toml"))?;
|
||||||
let table: toml::Table = raw.parse().ok()?;
|
let table: toml::Table = raw.parse().ok()?;
|
||||||
@@ -239,7 +260,7 @@ fn read_forge_toml_meta(
|
|||||||
.and_then(|v| v.as_str())
|
.and_then(|v| v.as_str())
|
||||||
.unwrap_or("")
|
.unwrap_or("")
|
||||||
.to_owned();
|
.to_owned();
|
||||||
let (name, description) = table
|
let (name, description, version) = table
|
||||||
.get("mods")
|
.get("mods")
|
||||||
.and_then(|v| v.as_array())
|
.and_then(|v| v.as_array())
|
||||||
.and_then(|a| a.first())
|
.and_then(|a| a.first())
|
||||||
@@ -256,17 +277,22 @@ fn read_forge_toml_meta(
|
|||||||
.unwrap_or("")
|
.unwrap_or("")
|
||||||
.trim()
|
.trim()
|
||||||
.to_owned();
|
.to_owned();
|
||||||
(n, d)
|
let version = first
|
||||||
|
.get("version")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_owned();
|
||||||
|
(n, d, version)
|
||||||
})
|
})
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
Some((name, description, logo))
|
Some((name, description, version, logo))
|
||||||
}
|
}
|
||||||
|
|
||||||
// legacy forge mcmod.info is either a bare json array of mod entries
|
// legacy forge mcmod.info is either a bare json array of mod entries
|
||||||
// or an object with a "modList" key wrapping the array
|
// or an object with a "modList" key wrapping the array
|
||||||
fn read_mcmod_info(
|
fn read_mcmod_info(
|
||||||
archive: &mut zip::ZipArchive<std::fs::File>,
|
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||||
) -> Option<(String, String, String)> {
|
) -> Option<(String, String, String, String)> {
|
||||||
let mut entry = archive.by_name("mcmod.info").ok()?;
|
let mut entry = archive.by_name("mcmod.info").ok()?;
|
||||||
let mut raw = String::new();
|
let mut raw = String::new();
|
||||||
entry.read_to_string(&mut raw).ok()?;
|
entry.read_to_string(&mut raw).ok()?;
|
||||||
@@ -287,12 +313,17 @@ fn read_mcmod_info(
|
|||||||
.and_then(|v| v.as_str())
|
.and_then(|v| v.as_str())
|
||||||
.unwrap_or("")
|
.unwrap_or("")
|
||||||
.to_owned();
|
.to_owned();
|
||||||
|
let version = first
|
||||||
|
.get("version")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_owned();
|
||||||
let logo = first
|
let logo = first
|
||||||
.get("logoFile")
|
.get("logoFile")
|
||||||
.and_then(|v| v.as_str())
|
.and_then(|v| v.as_str())
|
||||||
.unwrap_or("")
|
.unwrap_or("")
|
||||||
.to_owned();
|
.to_owned();
|
||||||
Some((name, description, logo))
|
Some((name, description, version, logo))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_zip_string(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> Option<String> {
|
fn read_zip_string(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> Option<String> {
|
||||||
@@ -346,414 +377,6 @@ fn read_zip_bytes(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> O
|
|||||||
Some(bytes)
|
Some(bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
// downscales an icon to terminal resolution. resizes to height*2 because each
|
|
||||||
// terminal cell renders two vertical pixels using half-block characters (▀)
|
|
||||||
pub(crate) fn make_icon_pixels(
|
|
||||||
bytes: &[u8],
|
|
||||||
width: u16,
|
|
||||||
height: u16,
|
|
||||||
) -> Option<Vec<Vec<IconCell>>> {
|
|
||||||
let img = image::load_from_memory(bytes).ok()?;
|
|
||||||
let resized = img.resize_exact(
|
|
||||||
u32::from(width),
|
|
||||||
u32::from(height) * 2,
|
|
||||||
image::imageops::FilterType::Nearest,
|
|
||||||
);
|
|
||||||
let rgb = resized.to_rgb8();
|
|
||||||
|
|
||||||
let mut rows = Vec::new();
|
|
||||||
for row in 0..height {
|
|
||||||
let mut cols = Vec::new();
|
|
||||||
for col in 0..width {
|
|
||||||
let top_y = u32::from(row) * 2;
|
|
||||||
let bottom_y = (u32::from(row) * 2 + 1).min(rgb.height().saturating_sub(1));
|
|
||||||
let [tr, tg, tb] = rgb.get_pixel(u32::from(col), top_y).0;
|
|
||||||
let [br, bg, bb] = rgb.get_pixel(u32::from(col), bottom_y).0;
|
|
||||||
cols.push(IconCell {
|
|
||||||
bg_r: br,
|
|
||||||
bg_g: bg,
|
|
||||||
bg_b: bb,
|
|
||||||
fg_r: tr,
|
|
||||||
fg_g: tg,
|
|
||||||
fg_b: tb,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
rows.push(cols);
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(rows)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 6x3 fallback icon showing a "?" pattern for mods without icons.
|
|
||||||
pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
|
|
||||||
let b = IconCell {
|
|
||||||
bg_r: 50,
|
|
||||||
bg_g: 50,
|
|
||||||
bg_b: 50,
|
|
||||||
fg_r: 50,
|
|
||||||
fg_g: 50,
|
|
||||||
fg_b: 50,
|
|
||||||
};
|
|
||||||
let tb = IconCell {
|
|
||||||
bg_r: 50,
|
|
||||||
bg_g: 50,
|
|
||||||
bg_b: 50,
|
|
||||||
fg_r: 130,
|
|
||||||
fg_g: 130,
|
|
||||||
fg_b: 130,
|
|
||||||
};
|
|
||||||
let bt = IconCell {
|
|
||||||
bg_r: 130,
|
|
||||||
bg_g: 130,
|
|
||||||
bg_b: 130,
|
|
||||||
fg_r: 50,
|
|
||||||
fg_g: 50,
|
|
||||||
fg_b: 50,
|
|
||||||
};
|
|
||||||
vec![
|
|
||||||
vec![b, tb, tb, tb, tb, b],
|
|
||||||
vec![b, b, b, bt, bt, b],
|
|
||||||
vec![b, b, bt, bt, b, b],
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
// 12x6 fallback icon showing a "?" pattern for worlds without icons.
|
|
||||||
pub(super) fn fallback_icon_large() -> Vec<Vec<IconCell>> {
|
|
||||||
let b = IconCell {
|
|
||||||
bg_r: 50,
|
|
||||||
bg_g: 50,
|
|
||||||
bg_b: 50,
|
|
||||||
fg_r: 50,
|
|
||||||
fg_g: 50,
|
|
||||||
fg_b: 50,
|
|
||||||
};
|
|
||||||
let tb = IconCell {
|
|
||||||
bg_r: 50,
|
|
||||||
bg_g: 50,
|
|
||||||
bg_b: 50,
|
|
||||||
fg_r: 130,
|
|
||||||
fg_g: 130,
|
|
||||||
fg_b: 130,
|
|
||||||
};
|
|
||||||
let bt = IconCell {
|
|
||||||
bg_r: 130,
|
|
||||||
bg_g: 130,
|
|
||||||
bg_b: 130,
|
|
||||||
fg_r: 50,
|
|
||||||
fg_g: 50,
|
|
||||||
fg_b: 50,
|
|
||||||
};
|
|
||||||
vec![
|
|
||||||
vec![b, b, tb, tb, tb, tb, tb, tb, tb, tb, b, b],
|
|
||||||
vec![b, b, tb, tb, tb, tb, tb, tb, tb, tb, b, b],
|
|
||||||
vec![b, b, b, b, b, b, bt, bt, bt, bt, b, b],
|
|
||||||
vec![b, b, b, b, b, b, bt, bt, bt, bt, b, b],
|
|
||||||
vec![b, b, b, b, bt, bt, bt, bt, b, b, b, b],
|
|
||||||
vec![b, b, b, b, bt, bt, bt, bt, b, b, b, b],
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
// enable/disable by renaming the file with/without ".disabled" suffix.
|
|
||||||
// the minecraft way, apparently.
|
|
||||||
pub fn toggle_entry(entry: &ContentEntry) -> Result<(), std::io::Error> {
|
|
||||||
let file_name = match entry.path.file_name().and_then(|name| name.to_str()) {
|
|
||||||
Some(name) => name,
|
|
||||||
None => return Ok(()),
|
|
||||||
};
|
|
||||||
|
|
||||||
let new_name = if entry.enabled {
|
|
||||||
format!("{file_name}.disabled")
|
|
||||||
} else {
|
|
||||||
file_name.trim_end_matches(".disabled").to_string()
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut new_path = entry.path.clone();
|
|
||||||
new_path.set_file_name(new_name);
|
|
||||||
std::fs::rename(&entry.path, new_path)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "../tests/content/mods.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
fn setup_mods_dir(tmp: &Path, instance: &str) -> PathBuf {
|
|
||||||
let dir = tmp.join(instance).join(".minecraft").join("mods");
|
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
|
||||||
dir
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_empty_dir() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
setup_mods_dir(tmp.path(), "inst");
|
|
||||||
let mods = scan_mods(tmp.path(), "inst");
|
|
||||||
assert!(mods.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_missing_dir_returns_empty() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mods = scan_mods(tmp.path(), "ghost");
|
|
||||||
assert!(mods.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_finds_jar_files() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("cool-mod.jar"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::write(dir.join("other-mod.jar.disabled"), b"PK\x03\x04").unwrap();
|
|
||||||
let mods = scan_mods(tmp.path(), "inst");
|
|
||||||
assert_eq!(mods.len(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_enabled_disabled_flags() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("active.jar"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::write(dir.join("inactive.jar.disabled"), b"PK\x03\x04").unwrap();
|
|
||||||
let mods = scan_mods(tmp.path(), "inst");
|
|
||||||
let active = mods.iter().find(|m| m.file_stem == "active").unwrap();
|
|
||||||
let inactive = mods.iter().find(|m| m.file_stem == "inactive").unwrap();
|
|
||||||
assert!(active.enabled);
|
|
||||||
assert!(!inactive.enabled);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_ignores_non_jar() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("readme.txt"), "not a mod").unwrap();
|
|
||||||
std::fs::write(dir.join("config.json"), "{}").unwrap();
|
|
||||||
std::fs::write(dir.join("real.jar"), b"PK\x03\x04").unwrap();
|
|
||||||
let mods = scan_mods(tmp.path(), "inst");
|
|
||||||
assert_eq!(mods.len(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_sorted_case_insensitive() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("Zebra.jar"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::write(dir.join("alpha.jar"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::write(dir.join("Beta.jar"), b"PK\x03\x04").unwrap();
|
|
||||||
let mods = scan_mods(tmp.path(), "inst");
|
|
||||||
let names: Vec<&str> = mods.iter().map(|m| m.name.as_str()).collect();
|
|
||||||
assert_eq!(names, vec!["alpha", "Beta", "Zebra"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn toggle_entry_enable() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
let disabled_path = dir.join("mymod.jar.disabled");
|
|
||||||
std::fs::write(&disabled_path, b"PK\x03\x04").unwrap();
|
|
||||||
|
|
||||||
let entry = ContentEntry {
|
|
||||||
file_stem: "mymod".to_string(),
|
|
||||||
name: "mymod".to_string(),
|
|
||||||
description: String::new(),
|
|
||||||
enabled: false,
|
|
||||||
icon_bytes: None,
|
|
||||||
path: disabled_path.clone(),
|
|
||||||
icon_lines: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
toggle_entry(&entry).unwrap();
|
|
||||||
assert!(!disabled_path.exists());
|
|
||||||
assert!(dir.join("mymod.jar").exists());
|
|
||||||
}
|
|
||||||
|
|
||||||
use std::io::Write as _;
|
|
||||||
|
|
||||||
// helper to create a jar (zip) file with the given entries
|
|
||||||
fn make_jar(dir: &Path, name: &str, entries: &[(&str, &[u8])]) {
|
|
||||||
let path = dir.join(name);
|
|
||||||
let file = std::fs::File::create(&path).unwrap();
|
|
||||||
let mut zip = zip::ZipWriter::new(file);
|
|
||||||
let options: zip::write::FileOptions<()> =
|
|
||||||
zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored);
|
|
||||||
for (entry_name, data) in entries {
|
|
||||||
zip.start_file(*entry_name, options).unwrap();
|
|
||||||
zip.write_all(data).unwrap();
|
|
||||||
}
|
|
||||||
zip.finish().unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_reads_fabric_metadata() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
let meta = r#"{"name":"Fabric Mod","description":"A fabric mod","icon":"icon.png"}"#;
|
|
||||||
make_jar(
|
|
||||||
&dir,
|
|
||||||
"fabric-mod.jar",
|
|
||||||
&[("fabric.mod.json", meta.as_bytes())],
|
|
||||||
);
|
|
||||||
let mods = scan_mods(tmp.path(), "inst");
|
|
||||||
assert_eq!(mods.len(), 1);
|
|
||||||
assert_eq!(mods[0].name, "Fabric Mod");
|
|
||||||
assert_eq!(mods[0].description, "A fabric mod");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_reads_quilt_metadata() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
let meta =
|
|
||||||
r#"{"quilt_loader":{"metadata":{"name":"Quilt Mod","description":"A quilt mod"}}}"#;
|
|
||||||
make_jar(
|
|
||||||
&dir,
|
|
||||||
"quilt-mod.jar",
|
|
||||||
&[("quilt.mod.json", meta.as_bytes())],
|
|
||||||
);
|
|
||||||
let mods = scan_mods(tmp.path(), "inst");
|
|
||||||
assert_eq!(mods.len(), 1);
|
|
||||||
assert_eq!(mods[0].name, "Quilt Mod");
|
|
||||||
assert_eq!(mods[0].description, "A quilt mod");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_reads_forge_toml_metadata() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
let meta = r#"
|
|
||||||
logoFile = "logo.png"
|
|
||||||
|
|
||||||
[[mods]]
|
|
||||||
displayName = "Forge Mod"
|
|
||||||
description = "A forge mod"
|
|
||||||
"#;
|
|
||||||
make_jar(
|
|
||||||
&dir,
|
|
||||||
"forge-mod.jar",
|
|
||||||
&[("META-INF/mods.toml", meta.as_bytes())],
|
|
||||||
);
|
|
||||||
let mods = scan_mods(tmp.path(), "inst");
|
|
||||||
assert_eq!(mods.len(), 1);
|
|
||||||
assert_eq!(mods[0].name, "Forge Mod");
|
|
||||||
assert_eq!(mods[0].description, "A forge mod");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_reads_neoforge_toml_metadata() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
let meta = r#"
|
|
||||||
logoFile = "logo.png"
|
|
||||||
|
|
||||||
[[mods]]
|
|
||||||
displayName = "NeoForge Mod"
|
|
||||||
description = "A neoforge mod"
|
|
||||||
"#;
|
|
||||||
make_jar(
|
|
||||||
&dir,
|
|
||||||
"neoforge-mod.jar",
|
|
||||||
&[("META-INF/neoforge.mods.toml", meta.as_bytes())],
|
|
||||||
);
|
|
||||||
let mods = scan_mods(tmp.path(), "inst");
|
|
||||||
assert_eq!(mods.len(), 1);
|
|
||||||
assert_eq!(mods[0].name, "NeoForge Mod");
|
|
||||||
assert_eq!(mods[0].description, "A neoforge mod");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_reads_mcmod_info_array() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
let meta = r#"[{"name":"Legacy Mod","description":"An old forge mod"}]"#;
|
|
||||||
make_jar(&dir, "legacy-mod.jar", &[("mcmod.info", meta.as_bytes())]);
|
|
||||||
let mods = scan_mods(tmp.path(), "inst");
|
|
||||||
assert_eq!(mods.len(), 1);
|
|
||||||
assert_eq!(mods[0].name, "Legacy Mod");
|
|
||||||
assert_eq!(mods[0].description, "An old forge mod");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_reads_mcmod_info_modlist() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
let meta = r#"{"modList":[{"name":"Wrapped Mod","description":"Has modList wrapper"}]}"#;
|
|
||||||
make_jar(&dir, "wrapped-mod.jar", &[("mcmod.info", meta.as_bytes())]);
|
|
||||||
let mods = scan_mods(tmp.path(), "inst");
|
|
||||||
assert_eq!(mods.len(), 1);
|
|
||||||
assert_eq!(mods[0].name, "Wrapped Mod");
|
|
||||||
assert_eq!(mods[0].description, "Has modList wrapper");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_prefers_fabric_over_forge() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
let fabric = r#"{"name":"Fabric Name","description":"fabric desc"}"#;
|
|
||||||
let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n";
|
|
||||||
make_jar(
|
|
||||||
&dir,
|
|
||||||
"multi.jar",
|
|
||||||
&[
|
|
||||||
("fabric.mod.json", fabric.as_bytes()),
|
|
||||||
("META-INF/mods.toml", forge.as_bytes()),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
let mods = scan_mods(tmp.path(), "inst");
|
|
||||||
assert_eq!(mods[0].name, "Fabric Name");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_fallback_icon_paths() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
// jar with no metadata but has logo.png
|
|
||||||
let png_bytes = b"\x89PNG fake";
|
|
||||||
make_jar(&dir, "no-meta.jar", &[("logo.png", png_bytes)]);
|
|
||||||
let mods = scan_mods(tmp.path(), "inst");
|
|
||||||
assert_eq!(mods.len(), 1);
|
|
||||||
// should use filename as name since no metadata
|
|
||||||
assert_eq!(mods[0].name, "no-meta");
|
|
||||||
// icon_bytes should contain the logo.png content
|
|
||||||
assert_eq!(mods[0].icon_bytes.as_deref(), Some(png_bytes.as_slice()));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn icon_path_from_value_string() {
|
|
||||||
let val = serde_json::json!("assets/icon.png");
|
|
||||||
assert_eq!(icon_path_from_value(&val), "assets/icon.png");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn icon_path_from_value_map() {
|
|
||||||
let val = serde_json::json!({"64": "icon_64.png", "128": "icon_128.png"});
|
|
||||||
let result = icon_path_from_value(&val);
|
|
||||||
// should return one of the values
|
|
||||||
assert!(result == "icon_64.png" || result == "icon_128.png");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn icon_path_from_value_null() {
|
|
||||||
let val = serde_json::Value::Null;
|
|
||||||
assert_eq!(icon_path_from_value(&val), "");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn toggle_entry_disable() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
let enabled_path = dir.join("mymod.jar");
|
|
||||||
std::fs::write(&enabled_path, b"PK\x03\x04").unwrap();
|
|
||||||
|
|
||||||
let entry = ContentEntry {
|
|
||||||
file_stem: "mymod".to_string(),
|
|
||||||
name: "mymod".to_string(),
|
|
||||||
description: String::new(),
|
|
||||||
enabled: true,
|
|
||||||
icon_bytes: None,
|
|
||||||
path: enabled_path.clone(),
|
|
||||||
icon_lines: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
toggle_entry(&entry).unwrap();
|
|
||||||
assert!(!enabled_path.exists());
|
|
||||||
assert!(dir.join("mymod.jar.disabled").exists());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
// shared pack.mcmeta scanning for resource packs and shader packs.
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use super::entry::ContentEntry;
|
||||||
|
use super::{fallback_icon, make_icon_pixels};
|
||||||
|
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
struct PackMcMeta {
|
||||||
|
#[serde(default)]
|
||||||
|
pack: PackInfo,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
struct PackInfo {
|
||||||
|
#[serde(default)]
|
||||||
|
description: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn extract_description(value: &serde_json::Value) -> String {
|
||||||
|
match value {
|
||||||
|
serde_json::Value::String(text) => text.clone(),
|
||||||
|
serde_json::Value::Object(object) => object
|
||||||
|
.get("text")
|
||||||
|
.and_then(|value| value.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_owned(),
|
||||||
|
serde_json::Value::Array(values) => values
|
||||||
|
.iter()
|
||||||
|
.filter_map(|value| match value {
|
||||||
|
serde_json::Value::String(text) => Some(text.as_str()),
|
||||||
|
serde_json::Value::Object(object) => {
|
||||||
|
object.get("text").and_then(|value| value.as_str())
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(""),
|
||||||
|
_ => String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn scan_one_pack(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||||
|
let (description, icon_bytes) = if path.is_dir() {
|
||||||
|
read_metadata_from_dir(path)
|
||||||
|
} else {
|
||||||
|
read_metadata_from_zip(path)
|
||||||
|
};
|
||||||
|
let icon_lines = icon_bytes
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
|
||||||
|
.or_else(|| Some(fallback_icon()));
|
||||||
|
|
||||||
|
ContentEntry {
|
||||||
|
file_stem: file_stem.to_owned(),
|
||||||
|
name: file_stem.to_owned(),
|
||||||
|
source_slug: None,
|
||||||
|
installed_path: None,
|
||||||
|
provider_project: None,
|
||||||
|
world_details: None,
|
||||||
|
title_suffix: None,
|
||||||
|
footer_label: None,
|
||||||
|
footer_change: None,
|
||||||
|
description,
|
||||||
|
enabled,
|
||||||
|
icon_bytes,
|
||||||
|
provider_icon: false,
|
||||||
|
provider_description: false,
|
||||||
|
path: path.to_path_buf(),
|
||||||
|
icon_lines,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn scan_packs(
|
||||||
|
instances_dir: &Path,
|
||||||
|
instance_name: &str,
|
||||||
|
directory: &str,
|
||||||
|
) -> Vec<ContentEntry> {
|
||||||
|
let directory = instances_dir
|
||||||
|
.join(instance_name)
|
||||||
|
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||||
|
.join(directory);
|
||||||
|
let Ok(entries) = std::fs::read_dir(directory) else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let mut packs = entries
|
||||||
|
.flatten()
|
||||||
|
.filter_map(|entry| {
|
||||||
|
let path = entry.path();
|
||||||
|
let file_name = path.file_name()?.to_str()?;
|
||||||
|
let (enabled, file_stem) = if path.is_dir() {
|
||||||
|
super::parse_enabled_stem_dir(file_name)
|
||||||
|
} else {
|
||||||
|
super::parse_enabled_stem(file_name, ".zip")?
|
||||||
|
};
|
||||||
|
Some(scan_one_pack(&path, &file_stem, enabled))
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
packs.sort_by_cached_key(|entry| entry.name.to_lowercase());
|
||||||
|
packs
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_metadata_from_zip(path: &Path) -> (String, Option<Vec<u8>>) {
|
||||||
|
let Some(mut archive) = super::open_zip(path) else {
|
||||||
|
return (String::new(), None);
|
||||||
|
};
|
||||||
|
let description = archive
|
||||||
|
.by_name("pack.mcmeta")
|
||||||
|
.ok()
|
||||||
|
.and_then(|entry| serde_json::from_reader::<_, PackMcMeta>(entry).ok())
|
||||||
|
.map(|meta| extract_description(&meta.pack.description))
|
||||||
|
.unwrap_or_default();
|
||||||
|
let icon_bytes = super::read_icon_from_zip(&mut archive);
|
||||||
|
(description, icon_bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_metadata_from_dir(path: &Path) -> (String, Option<Vec<u8>>) {
|
||||||
|
let description = std::fs::read_to_string(path.join("pack.mcmeta"))
|
||||||
|
.ok()
|
||||||
|
.and_then(|content| serde_json::from_str::<PackMcMeta>(&content).ok())
|
||||||
|
.map(|meta| extract_description(&meta.pack.description))
|
||||||
|
.unwrap_or_default();
|
||||||
|
(description, std::fs::read(path.join("pack.png")).ok())
|
||||||
|
}
|
||||||
@@ -0,0 +1,425 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
|
||||||
|
use crate::instance::content::manifest::{ContentKind, FileFingerprint, ProviderProject};
|
||||||
|
use crate::instance::{InstanceConfig, ModLoader};
|
||||||
|
use crate::net::modrinth::{DiscoveryResults, VersionInfo};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct FingerprintQuery {
|
||||||
|
pub key: String,
|
||||||
|
pub kind: ContentKind,
|
||||||
|
pub fingerprint: FileFingerprint,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ResolvedFile {
|
||||||
|
pub key: String,
|
||||||
|
pub project: ProviderProject,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait ContentProvider: Send + Sync {
|
||||||
|
fn id(&self) -> &'static str;
|
||||||
|
|
||||||
|
async fn search(
|
||||||
|
&self,
|
||||||
|
kind: ContentKind,
|
||||||
|
query: &str,
|
||||||
|
instance: &InstanceConfig,
|
||||||
|
offset: usize,
|
||||||
|
limit: usize,
|
||||||
|
) -> Result<DiscoveryResults, crate::net::NetError>;
|
||||||
|
|
||||||
|
async fn search_modpacks(
|
||||||
|
&self,
|
||||||
|
query: &str,
|
||||||
|
offset: usize,
|
||||||
|
limit: usize,
|
||||||
|
) -> Result<DiscoveryResults, crate::net::NetError>;
|
||||||
|
|
||||||
|
async fn resolve_files(
|
||||||
|
&self,
|
||||||
|
files: &[FingerprintQuery],
|
||||||
|
) -> Result<Vec<ResolvedFile>, crate::net::NetError>;
|
||||||
|
|
||||||
|
async fn project(
|
||||||
|
&self,
|
||||||
|
project_id: &str,
|
||||||
|
) -> Result<crate::net::modrinth::ProjectInfo, crate::net::NetError>;
|
||||||
|
|
||||||
|
async fn compatible_versions(
|
||||||
|
&self,
|
||||||
|
project_id: &str,
|
||||||
|
kind: ContentKind,
|
||||||
|
game_version: &str,
|
||||||
|
loader: ModLoader,
|
||||||
|
) -> Result<Vec<VersionInfo>, crate::net::NetError>;
|
||||||
|
|
||||||
|
async fn version(&self, version_id: &str) -> Result<VersionInfo, crate::net::NetError>;
|
||||||
|
|
||||||
|
async fn icon(&self, url: &str) -> Result<Vec<u8>, crate::net::NetError>;
|
||||||
|
|
||||||
|
async fn download_version(
|
||||||
|
&self,
|
||||||
|
version: &VersionInfo,
|
||||||
|
destination: &std::path::Path,
|
||||||
|
installed_path: Option<&std::path::Path>,
|
||||||
|
) -> Result<crate::net::modrinth::DownloadOutcome, crate::net::NetError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ModrinthProvider {
|
||||||
|
client: crate::net::HttpClient,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ModrinthProvider {
|
||||||
|
pub fn new(client: crate::net::HttpClient) -> Self {
|
||||||
|
Self { client }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl ContentProvider for ModrinthProvider {
|
||||||
|
fn id(&self) -> &'static str {
|
||||||
|
"modrinth"
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn search(
|
||||||
|
&self,
|
||||||
|
kind: ContentKind,
|
||||||
|
query: &str,
|
||||||
|
instance: &InstanceConfig,
|
||||||
|
offset: usize,
|
||||||
|
limit: usize,
|
||||||
|
) -> Result<DiscoveryResults, crate::net::NetError> {
|
||||||
|
crate::net::modrinth::search_discovery(
|
||||||
|
&self.client,
|
||||||
|
kind,
|
||||||
|
query,
|
||||||
|
&instance.game_version,
|
||||||
|
instance.loader,
|
||||||
|
offset,
|
||||||
|
limit,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn search_modpacks(
|
||||||
|
&self,
|
||||||
|
query: &str,
|
||||||
|
offset: usize,
|
||||||
|
limit: usize,
|
||||||
|
) -> Result<DiscoveryResults, crate::net::NetError> {
|
||||||
|
crate::net::modrinth::search_modpacks(&self.client, query, offset, limit).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn resolve_files(
|
||||||
|
&self,
|
||||||
|
files: &[FingerprintQuery],
|
||||||
|
) -> Result<Vec<ResolvedFile>, crate::net::NetError> {
|
||||||
|
let mut by_hash = HashMap::<String, Vec<String>>::new();
|
||||||
|
for file in files {
|
||||||
|
if let Some(hash) = file.fingerprint.hash("sha512") {
|
||||||
|
by_hash
|
||||||
|
.entry(hash.to_owned())
|
||||||
|
.or_default()
|
||||||
|
.push(file.key.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let hashes = by_hash.keys().cloned().collect::<Vec<_>>();
|
||||||
|
let versions =
|
||||||
|
crate::net::modrinth::resolve_version_files(&self.client, &hashes, "sha512").await?;
|
||||||
|
Ok(versions
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|(hash, version)| {
|
||||||
|
let keys = by_hash.get(&hash).cloned().unwrap_or_default();
|
||||||
|
if version.project_id.is_empty() {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
keys.into_iter()
|
||||||
|
.map(|key| ResolvedFile {
|
||||||
|
key,
|
||||||
|
project: ProviderProject {
|
||||||
|
provider: self.id().to_owned(),
|
||||||
|
project_id: version.project_id.clone(),
|
||||||
|
version_id: version.id.clone(),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn project(
|
||||||
|
&self,
|
||||||
|
project_id: &str,
|
||||||
|
) -> Result<crate::net::modrinth::ProjectInfo, crate::net::NetError> {
|
||||||
|
crate::net::modrinth::fetch_project(&self.client, project_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn compatible_versions(
|
||||||
|
&self,
|
||||||
|
project_id: &str,
|
||||||
|
kind: ContentKind,
|
||||||
|
game_version: &str,
|
||||||
|
loader: ModLoader,
|
||||||
|
) -> Result<Vec<VersionInfo>, crate::net::NetError> {
|
||||||
|
crate::net::modrinth::fetch_content_versions(
|
||||||
|
&self.client,
|
||||||
|
project_id,
|
||||||
|
kind,
|
||||||
|
game_version,
|
||||||
|
loader,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn version(&self, version_id: &str) -> Result<VersionInfo, crate::net::NetError> {
|
||||||
|
crate::net::modrinth::fetch_version(&self.client, version_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn icon(&self, url: &str) -> Result<Vec<u8>, crate::net::NetError> {
|
||||||
|
self.client
|
||||||
|
.get_bytes_limited(url, crate::net::MAX_PROVIDER_ASSET_BYTES)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn download_version(
|
||||||
|
&self,
|
||||||
|
version: &VersionInfo,
|
||||||
|
destination: &std::path::Path,
|
||||||
|
installed_path: Option<&std::path::Path>,
|
||||||
|
) -> Result<crate::net::modrinth::DownloadOutcome, crate::net::NetError> {
|
||||||
|
if let Some(installed_path) = installed_path {
|
||||||
|
crate::net::modrinth::download_version_file_for_update(
|
||||||
|
&self.client,
|
||||||
|
version,
|
||||||
|
destination,
|
||||||
|
installed_path,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
} else {
|
||||||
|
crate::net::modrinth::download_version_file(&self.client, version, destination).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct CurseForgeProvider {
|
||||||
|
client: crate::net::HttpClient,
|
||||||
|
api_key: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CurseForgeProvider {
|
||||||
|
pub fn new(client: crate::net::HttpClient, api_key: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
client,
|
||||||
|
api_key: api_key.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl ContentProvider for CurseForgeProvider {
|
||||||
|
fn id(&self) -> &'static str {
|
||||||
|
"curseforge"
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn search(
|
||||||
|
&self,
|
||||||
|
kind: ContentKind,
|
||||||
|
query: &str,
|
||||||
|
instance: &InstanceConfig,
|
||||||
|
offset: usize,
|
||||||
|
limit: usize,
|
||||||
|
) -> Result<DiscoveryResults, crate::net::NetError> {
|
||||||
|
crate::net::curseforge::search_discovery(
|
||||||
|
&self.client,
|
||||||
|
&self.api_key,
|
||||||
|
kind,
|
||||||
|
query,
|
||||||
|
&instance.game_version,
|
||||||
|
instance.loader,
|
||||||
|
offset,
|
||||||
|
limit,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn search_modpacks(
|
||||||
|
&self,
|
||||||
|
query: &str,
|
||||||
|
offset: usize,
|
||||||
|
limit: usize,
|
||||||
|
) -> Result<DiscoveryResults, crate::net::NetError> {
|
||||||
|
crate::net::curseforge::search_modpacks(&self.client, &self.api_key, query, offset, limit)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn resolve_files(
|
||||||
|
&self,
|
||||||
|
files: &[FingerprintQuery],
|
||||||
|
) -> Result<Vec<ResolvedFile>, crate::net::NetError> {
|
||||||
|
let mut by_fingerprint = HashMap::<u32, Vec<String>>::new();
|
||||||
|
for file in files {
|
||||||
|
if let Some(fingerprint) = file
|
||||||
|
.fingerprint
|
||||||
|
.hash("curseforge")
|
||||||
|
.and_then(|value| value.parse().ok())
|
||||||
|
{
|
||||||
|
by_fingerprint
|
||||||
|
.entry(fingerprint)
|
||||||
|
.or_default()
|
||||||
|
.push(file.key.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let fingerprints = by_fingerprint.keys().copied().collect::<Vec<_>>();
|
||||||
|
let matches = crate::net::curseforge::resolve_fingerprints(
|
||||||
|
&self.client,
|
||||||
|
&self.api_key,
|
||||||
|
&fingerprints,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
Ok(matches
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|(fingerprint, project_id, version_id)| {
|
||||||
|
by_fingerprint
|
||||||
|
.get(&fingerprint)
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.into_iter()
|
||||||
|
.map(move |key| ResolvedFile {
|
||||||
|
key,
|
||||||
|
project: ProviderProject {
|
||||||
|
provider: self.id().to_owned(),
|
||||||
|
project_id: project_id.clone(),
|
||||||
|
version_id: version_id.clone(),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn project(
|
||||||
|
&self,
|
||||||
|
project_id: &str,
|
||||||
|
) -> Result<crate::net::modrinth::ProjectInfo, crate::net::NetError> {
|
||||||
|
crate::net::curseforge::fetch_project(&self.client, &self.api_key, project_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn compatible_versions(
|
||||||
|
&self,
|
||||||
|
project_id: &str,
|
||||||
|
kind: ContentKind,
|
||||||
|
game_version: &str,
|
||||||
|
loader: ModLoader,
|
||||||
|
) -> Result<Vec<VersionInfo>, crate::net::NetError> {
|
||||||
|
crate::net::curseforge::fetch_versions(
|
||||||
|
&self.client,
|
||||||
|
&self.api_key,
|
||||||
|
project_id,
|
||||||
|
game_version,
|
||||||
|
(kind == ContentKind::Mod).then_some(loader),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn version(&self, version_id: &str) -> Result<VersionInfo, crate::net::NetError> {
|
||||||
|
let id = version_id.parse::<u64>().map_err(|_| {
|
||||||
|
crate::net::NetError::Parse(format!("Invalid CurseForge file id '{version_id}'"))
|
||||||
|
})?;
|
||||||
|
crate::net::curseforge::fetch_file_versions(&self.client, &self.api_key, &[id])
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.next()
|
||||||
|
.ok_or_else(|| {
|
||||||
|
crate::net::NetError::Parse(format!("CurseForge file '{version_id}' was not found"))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn icon(&self, url: &str) -> Result<Vec<u8>, crate::net::NetError> {
|
||||||
|
self.client
|
||||||
|
.get_bytes_limited(url, crate::net::MAX_PROVIDER_ASSET_BYTES)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn download_version(
|
||||||
|
&self,
|
||||||
|
version: &VersionInfo,
|
||||||
|
destination: &std::path::Path,
|
||||||
|
installed_path: Option<&std::path::Path>,
|
||||||
|
) -> Result<crate::net::modrinth::DownloadOutcome, crate::net::NetError> {
|
||||||
|
let mut version = version.clone();
|
||||||
|
crate::net::curseforge::ensure_download_url(&self.client, &self.api_key, &mut version)
|
||||||
|
.await?;
|
||||||
|
if let Some(installed_path) = installed_path {
|
||||||
|
crate::net::modrinth::download_version_file_for_update(
|
||||||
|
&self.client,
|
||||||
|
&version,
|
||||||
|
destination,
|
||||||
|
installed_path,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
} else {
|
||||||
|
crate::net::modrinth::download_version_file(&self.client, &version, destination).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ProviderRegistry {
|
||||||
|
providers: Vec<Box<dyn ContentProvider>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn has_newer_compatible_version(
|
||||||
|
versions: &[VersionInfo],
|
||||||
|
installed_version_id: &str,
|
||||||
|
) -> bool {
|
||||||
|
versions
|
||||||
|
.iter()
|
||||||
|
.position(|version| version.id == installed_version_id)
|
||||||
|
.is_some_and(|position| position > 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProviderRegistry {
|
||||||
|
pub(crate) fn new(providers: Vec<Box<dyn ContentProvider>>) -> Self {
|
||||||
|
Self { providers }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn modrinth(client: crate::net::HttpClient) -> Self {
|
||||||
|
Self::new(vec![Box::new(ModrinthProvider::new(client))])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn configured(client: crate::net::HttpClient) -> Self {
|
||||||
|
let mut providers: Vec<Box<dyn ContentProvider>> =
|
||||||
|
vec![Box::new(ModrinthProvider::new(client.clone()))];
|
||||||
|
if let Some(api_key) = crate::net::curseforge::api_key() {
|
||||||
|
providers.push(Box::new(CurseForgeProvider::new(client, api_key)));
|
||||||
|
}
|
||||||
|
Self::new(providers)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn providers(&self) -> &[Box<dyn ContentProvider>] {
|
||||||
|
&self.providers
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn preferred(&self, id: &str) -> Option<&dyn ContentProvider> {
|
||||||
|
self.providers
|
||||||
|
.iter()
|
||||||
|
.find(|provider| provider.id() == id)
|
||||||
|
.map(Box::as_ref)
|
||||||
|
.or_else(|| self.providers.first().map(Box::as_ref))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self, id: &str) -> Option<&dyn ContentProvider> {
|
||||||
|
self.providers
|
||||||
|
.iter()
|
||||||
|
.find(|provider| provider.id() == id)
|
||||||
|
.map(Box::as_ref)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/content/provider.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,673 @@
|
|||||||
|
use std::collections::{HashMap, HashSet, VecDeque};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::{Arc, LazyLock, Mutex};
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use crate::feedback::progress::{ProgressTask, ProgressTaskHandle};
|
||||||
|
use crate::instance::InstanceConfig;
|
||||||
|
use crate::instance::content::manifest::{
|
||||||
|
ContentFileRecord, ContentKind, ContentManifest, FileFingerprint, ProviderProject, Resolution,
|
||||||
|
fingerprint, fingerprint_metadata,
|
||||||
|
};
|
||||||
|
use crate::instance::content::provider::{FingerprintQuery, ProviderRegistry};
|
||||||
|
use crate::storage::InstancePaths;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ReconcileResult {
|
||||||
|
pub instance_name: String,
|
||||||
|
pub instance_created: chrono::DateTime<chrono::Utc>,
|
||||||
|
pub manifest: ContentManifest,
|
||||||
|
pub error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub static PENDING_RECONCILIATIONS: LazyLock<Arc<Mutex<Vec<ReconcileResult>>>> =
|
||||||
|
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct ReconcileJob {
|
||||||
|
instance: InstanceConfig,
|
||||||
|
instances_dir: PathBuf,
|
||||||
|
client: crate::net::HttpClient,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct ReconcileCoordinator {
|
||||||
|
queue: VecDeque<ReconcileJob>,
|
||||||
|
scheduled: HashSet<(String, chrono::DateTime<chrono::Utc>)>,
|
||||||
|
rerun: HashSet<(String, chrono::DateTime<chrono::Utc>)>,
|
||||||
|
worker_running: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ReconcileCoordinator {
|
||||||
|
fn enqueue(&mut self, job: ReconcileJob, rerun_if_scheduled: bool) -> bool {
|
||||||
|
let instance = (job.instance.name.clone(), job.instance.created);
|
||||||
|
if !self.scheduled.insert(instance.clone()) {
|
||||||
|
if rerun_if_scheduled {
|
||||||
|
self.rerun.insert(instance);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
self.queue.push_back(job);
|
||||||
|
if self.worker_running {
|
||||||
|
false
|
||||||
|
} else {
|
||||||
|
self.worker_running = true;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static RECONCILE_COORDINATOR: LazyLock<Mutex<ReconcileCoordinator>> =
|
||||||
|
LazyLock::new(|| Mutex::new(ReconcileCoordinator::default()));
|
||||||
|
|
||||||
|
pub fn spawn(instance: InstanceConfig, instances_dir: PathBuf, client: crate::net::HttpClient) {
|
||||||
|
schedule(instance, instances_dir, client, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn spawn_after_change(
|
||||||
|
instance: InstanceConfig,
|
||||||
|
instances_dir: PathBuf,
|
||||||
|
client: crate::net::HttpClient,
|
||||||
|
) {
|
||||||
|
schedule(instance, instances_dir, client, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn schedule(
|
||||||
|
instance: InstanceConfig,
|
||||||
|
instances_dir: PathBuf,
|
||||||
|
client: crate::net::HttpClient,
|
||||||
|
rerun_if_scheduled: bool,
|
||||||
|
) {
|
||||||
|
let start_worker = {
|
||||||
|
let Ok(mut coordinator) = RECONCILE_COORDINATOR.lock() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
coordinator.enqueue(
|
||||||
|
ReconcileJob {
|
||||||
|
instance,
|
||||||
|
instances_dir,
|
||||||
|
client,
|
||||||
|
},
|
||||||
|
rerun_if_scheduled,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
if start_worker {
|
||||||
|
tokio::spawn(reconcile_worker());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn reconcile_worker() {
|
||||||
|
let task = ProgressTask::start("Preparing content index");
|
||||||
|
loop {
|
||||||
|
let job = {
|
||||||
|
let Ok(mut coordinator) = RECONCILE_COORDINATOR.lock() else {
|
||||||
|
task.finish();
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
match coordinator.queue.pop_front() {
|
||||||
|
Some(job) => job,
|
||||||
|
None => {
|
||||||
|
coordinator.worker_running = false;
|
||||||
|
task.finish();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
if let Ok(mut coordinator) = RECONCILE_COORDINATOR.lock() {
|
||||||
|
if coordinator.rerun.remove(&instance) {
|
||||||
|
coordinator.queue.push_back(rerun_job);
|
||||||
|
} else {
|
||||||
|
coordinator.scheduled.remove(&instance);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
crate::feedback::request_redraw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult {
|
||||||
|
let ReconcileJob {
|
||||||
|
instance,
|
||||||
|
instances_dir,
|
||||||
|
client,
|
||||||
|
} = job;
|
||||||
|
let instance_name = instance.name;
|
||||||
|
let instance_created = instance.created;
|
||||||
|
task.set_action(format!("Checking content for {instance_name}"));
|
||||||
|
task.set_sub_action("Reading saved content index");
|
||||||
|
task.set_progress(0, 1);
|
||||||
|
let paths = InstancePaths::new(instances_dir.join(&instance_name));
|
||||||
|
let manifest_path = paths.content_manifest();
|
||||||
|
let minecraft_dir = paths.minecraft();
|
||||||
|
let retry_hours = crate::config::SETTINGS.content.unmatched_retry_hours;
|
||||||
|
let max_fingerprint_size_mib = crate::config::SETTINGS.content.max_fingerprint_size_mib;
|
||||||
|
let inventory_progress = task.handle();
|
||||||
|
let inventory_minecraft_dir = minecraft_dir.clone();
|
||||||
|
let inventory = tokio::task::spawn_blocking(move || {
|
||||||
|
reconcile_inventory(
|
||||||
|
&manifest_path,
|
||||||
|
&inventory_minecraft_dir,
|
||||||
|
retry_hours,
|
||||||
|
max_fingerprint_size_mib,
|
||||||
|
&inventory_progress,
|
||||||
|
)
|
||||||
|
.map(|result| (result, manifest_path))
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
|
||||||
|
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 =
|
||||||
|
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(
|
||||||
|
&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()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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(),
|
||||||
|
error: Some(error.to_string()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save_reconciled_manifest(
|
||||||
|
manifest_path: &Path,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
reconciled: ContentManifest,
|
||||||
|
) -> Result<ContentManifest, crate::instance::content::manifest::ManifestError> {
|
||||||
|
let reconciled_paths = reconciled
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.map(|record| record.relative_path.clone())
|
||||||
|
.collect::<HashSet<_>>();
|
||||||
|
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 {
|
||||||
|
let keep_resolved = current
|
||||||
|
.record(&record.relative_path)
|
||||||
|
.is_some_and(|existing| {
|
||||||
|
existing.fingerprint == record.fingerprint
|
||||||
|
&& existing.resolved_project().is_some_and(|current| {
|
||||||
|
record.resolved_project().is_none_or(|resolved| {
|
||||||
|
current.provider != resolved.provider
|
||||||
|
|| current.project_id != resolved.project_id
|
||||||
|
})
|
||||||
|
})
|
||||||
|
});
|
||||||
|
if !keep_resolved {
|
||||||
|
current.upsert(record);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(current.clone())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Inventory {
|
||||||
|
manifest: ContentManifest,
|
||||||
|
queries: Vec<FingerprintQuery>,
|
||||||
|
}
|
||||||
|
|
||||||
|
trait InventoryProgress {
|
||||||
|
fn set_sub_action(&self, text: &str);
|
||||||
|
fn set_progress(&self, current: u64, total: u64);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InventoryProgress for ProgressTaskHandle {
|
||||||
|
fn set_sub_action(&self, text: &str) {
|
||||||
|
ProgressTaskHandle::set_sub_action(self, text);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_progress(&self, current: u64, total: u64) {
|
||||||
|
ProgressTaskHandle::set_progress(self, current, total);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reconcile_inventory(
|
||||||
|
manifest_path: &Path,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
unmatched_retry_hours: u64,
|
||||||
|
max_fingerprint_size_mib: u64,
|
||||||
|
task: &impl InventoryProgress,
|
||||||
|
) -> Result<Inventory, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let previous = ContentManifest::load(manifest_path)?;
|
||||||
|
let files = content_files(minecraft_dir)?;
|
||||||
|
let file_count = files.len() as u64;
|
||||||
|
if file_count == 0 {
|
||||||
|
task.set_sub_action("No local content files");
|
||||||
|
task.set_progress(1, 1);
|
||||||
|
} else {
|
||||||
|
task.set_progress(0, file_count);
|
||||||
|
}
|
||||||
|
let now = chrono::Utc::now().timestamp();
|
||||||
|
let retry_seconds = unmatched_retry_hours.saturating_mul(60 * 60) as i64;
|
||||||
|
let mut manifest = ContentManifest::default();
|
||||||
|
let mut queries = Vec::new();
|
||||||
|
|
||||||
|
for (index, (kind, path)) in files.into_iter().enumerate() {
|
||||||
|
task.set_sub_action(
|
||||||
|
path.file_name()
|
||||||
|
.and_then(|name| name.to_str())
|
||||||
|
.unwrap_or("content"),
|
||||||
|
);
|
||||||
|
let relative_path = path.strip_prefix(minecraft_dir)?.to_path_buf();
|
||||||
|
let enabled = !path
|
||||||
|
.file_name()
|
||||||
|
.and_then(|name| name.to_str())
|
||||||
|
.is_some_and(|name| name.ends_with(".disabled"));
|
||||||
|
let metadata = std::fs::metadata(&path)?;
|
||||||
|
let is_directory = metadata.is_dir();
|
||||||
|
let metadata_fingerprint = if is_directory {
|
||||||
|
directory_fingerprint_metadata(&path)?
|
||||||
|
} else {
|
||||||
|
fingerprint_metadata(&path)?
|
||||||
|
};
|
||||||
|
let modified_ns = metadata_fingerprint.modified_ns;
|
||||||
|
let existing = previous.record(&relative_path);
|
||||||
|
let unchanged = existing.is_some_and(|record| {
|
||||||
|
record.fingerprint.size == metadata_fingerprint.size
|
||||||
|
&& record.fingerprint.modified_ns == modified_ns
|
||||||
|
});
|
||||||
|
let oversized = !is_directory
|
||||||
|
&& max_fingerprint_size_mib > 0
|
||||||
|
&& metadata.len() > max_fingerprint_size_mib.saturating_mul(1024 * 1024);
|
||||||
|
let mut record = if unchanged {
|
||||||
|
existing.cloned().unwrap()
|
||||||
|
} else if is_directory {
|
||||||
|
ContentFileRecord {
|
||||||
|
relative_path: relative_path.clone(),
|
||||||
|
kind,
|
||||||
|
enabled,
|
||||||
|
fingerprint: metadata_fingerprint,
|
||||||
|
resolution: Resolution::Unmatched {
|
||||||
|
checked_at: now,
|
||||||
|
providers: Vec::new(),
|
||||||
|
},
|
||||||
|
provider_aliases: Vec::new(),
|
||||||
|
provider_checks: Vec::new(),
|
||||||
|
required_dependencies: Vec::new(),
|
||||||
|
automatic_dependency: false,
|
||||||
|
cleanup_eligible: false,
|
||||||
|
}
|
||||||
|
} else if oversized {
|
||||||
|
tracing::debug!(
|
||||||
|
"Skipping automatic provider matching for {} ({} bytes exceeds {} MiB limit)",
|
||||||
|
path.display(),
|
||||||
|
metadata.len(),
|
||||||
|
max_fingerprint_size_mib
|
||||||
|
);
|
||||||
|
ContentFileRecord {
|
||||||
|
relative_path: relative_path.clone(),
|
||||||
|
kind,
|
||||||
|
enabled,
|
||||||
|
fingerprint: fingerprint_metadata(&path)?,
|
||||||
|
resolution: Resolution::Unmatched {
|
||||||
|
checked_at: now,
|
||||||
|
providers: Vec::new(),
|
||||||
|
},
|
||||||
|
provider_aliases: Vec::new(),
|
||||||
|
provider_checks: Vec::new(),
|
||||||
|
required_dependencies: Vec::new(),
|
||||||
|
automatic_dependency: false,
|
||||||
|
cleanup_eligible: false,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ContentFileRecord {
|
||||||
|
relative_path: relative_path.clone(),
|
||||||
|
kind,
|
||||||
|
enabled,
|
||||||
|
fingerprint: fingerprint(&path)?,
|
||||||
|
resolution: Resolution::Pending,
|
||||||
|
provider_aliases: Vec::new(),
|
||||||
|
provider_checks: Vec::new(),
|
||||||
|
required_dependencies: Vec::new(),
|
||||||
|
automatic_dependency: false,
|
||||||
|
cleanup_eligible: false,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
record.kind = kind;
|
||||||
|
record.enabled = enabled;
|
||||||
|
|
||||||
|
if oversized && matches!(record.resolution, Resolution::Pending) {
|
||||||
|
record.resolution = Resolution::Unmatched {
|
||||||
|
checked_at: now,
|
||||||
|
providers: Vec::new(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let provider_unchecked = ["modrinth", "curseforge"].into_iter().any(|provider| {
|
||||||
|
crate::config::SETTINGS
|
||||||
|
.content
|
||||||
|
.discovery_provider_enabled(provider)
|
||||||
|
&& provider_was_not_checked(&record, provider)
|
||||||
|
});
|
||||||
|
if !is_directory
|
||||||
|
&& !oversized
|
||||||
|
&& provider_unchecked
|
||||||
|
&& record.fingerprint.hash("curseforge").is_none()
|
||||||
|
{
|
||||||
|
record.fingerprint = fingerprint(&path)?;
|
||||||
|
}
|
||||||
|
let should_query = !is_directory
|
||||||
|
&& !oversized
|
||||||
|
&& (provider_unchecked
|
||||||
|
|| match &record.resolution {
|
||||||
|
Resolution::Pending => true,
|
||||||
|
Resolution::Unmatched { checked_at, .. } => {
|
||||||
|
now.saturating_sub(*checked_at) >= retry_seconds
|
||||||
|
}
|
||||||
|
Resolution::Resolved { .. } | Resolution::Ambiguous { .. } => false,
|
||||||
|
});
|
||||||
|
if should_query {
|
||||||
|
if !matches!(&record.resolution, Resolution::Resolved { .. }) {
|
||||||
|
record.resolution = Resolution::Pending;
|
||||||
|
}
|
||||||
|
queries.push(FingerprintQuery {
|
||||||
|
key: relative_path.to_string_lossy().into_owned(),
|
||||||
|
kind,
|
||||||
|
fingerprint: record.fingerprint.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
manifest.upsert(record);
|
||||||
|
task.set_progress(index as u64 + 1, file_count);
|
||||||
|
}
|
||||||
|
Ok(Inventory { manifest, queries })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn provider_was_not_checked(record: &ContentFileRecord, provider: &str) -> bool {
|
||||||
|
let identified = record
|
||||||
|
.resolved_project()
|
||||||
|
.into_iter()
|
||||||
|
.chain(record.provider_aliases.iter())
|
||||||
|
.any(|project| project.provider == provider);
|
||||||
|
let checked_as_unmatched = matches!(
|
||||||
|
&record.resolution,
|
||||||
|
Resolution::Unmatched { providers, .. }
|
||||||
|
if providers.iter().any(|checked| checked == provider)
|
||||||
|
);
|
||||||
|
!identified
|
||||||
|
&& !checked_as_unmatched
|
||||||
|
&& !record
|
||||||
|
.provider_checks
|
||||||
|
.iter()
|
||||||
|
.any(|checked| checked == provider)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn resolve_queries(
|
||||||
|
registry: &ProviderRegistry,
|
||||||
|
queries: &[FingerprintQuery],
|
||||||
|
manifest: &mut ContentManifest,
|
||||||
|
) -> Result<(), crate::net::NetError> {
|
||||||
|
if queries.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
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 provider_id = provider.id();
|
||||||
|
match tokio::time::timeout(
|
||||||
|
std::time::Duration::from_secs(10),
|
||||||
|
provider.resolve_files(queries),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(Ok(resolved_files)) => {
|
||||||
|
checked.push(provider_id.to_owned());
|
||||||
|
for resolved in resolved_files {
|
||||||
|
matches
|
||||||
|
.entry(resolved.key)
|
||||||
|
.or_default()
|
||||||
|
.push(resolved.project);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Err(error)) => {
|
||||||
|
tracing::warn!(
|
||||||
|
"Skipping {provider_id} content matching after provider error: {error}"
|
||||||
|
);
|
||||||
|
last_error = Some(error.to_string());
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
tracing::warn!(
|
||||||
|
"Skipping {provider_id} content matching after the 10 second timeout"
|
||||||
|
);
|
||||||
|
last_error = Some(format!("{provider_id} content matching timed out"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if checked.is_empty() {
|
||||||
|
return Err(crate::net::NetError::TaskFailed(last_error.unwrap_or_else(
|
||||||
|
|| "No content providers are available".to_owned(),
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let query_keys = queries
|
||||||
|
.iter()
|
||||||
|
.map(|query| query.key.as_str())
|
||||||
|
.collect::<HashSet<_>>();
|
||||||
|
let checked_at = chrono::Utc::now().timestamp();
|
||||||
|
for record in &mut manifest.files {
|
||||||
|
let key = record.relative_path.to_string_lossy();
|
||||||
|
if !query_keys.contains(key.as_ref()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let installed = record.resolved_project().cloned();
|
||||||
|
let mut candidates = matches.remove(key.as_ref()).unwrap_or_default();
|
||||||
|
for alias in &record.provider_aliases {
|
||||||
|
if !candidates.iter().any(|candidate| {
|
||||||
|
candidate.provider == alias.provider && candidate.project_id == alias.project_id
|
||||||
|
}) {
|
||||||
|
candidates.push(alias.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let (resolution, aliases) = if let Some(installed) = installed {
|
||||||
|
let project = candidates
|
||||||
|
.iter()
|
||||||
|
.find(|candidate| {
|
||||||
|
candidate.provider == installed.provider
|
||||||
|
&& candidate.project_id == installed.project_id
|
||||||
|
})
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or(installed);
|
||||||
|
candidates.retain(|candidate| {
|
||||||
|
candidate.provider != project.provider || candidate.project_id != project.project_id
|
||||||
|
});
|
||||||
|
(Resolution::Resolved { project }, candidates)
|
||||||
|
} else {
|
||||||
|
match candidates.as_slice() {
|
||||||
|
[] => (
|
||||||
|
Resolution::Unmatched {
|
||||||
|
checked_at,
|
||||||
|
providers: checked.clone(),
|
||||||
|
},
|
||||||
|
Vec::new(),
|
||||||
|
),
|
||||||
|
[project] => (
|
||||||
|
Resolution::Resolved {
|
||||||
|
project: project.clone(),
|
||||||
|
},
|
||||||
|
Vec::new(),
|
||||||
|
),
|
||||||
|
_ if !crate::config::SETTINGS.content.ask_on_provider_conflict => {
|
||||||
|
let preferred = crate::config::SETTINGS.content.preferred_provider();
|
||||||
|
if let Some(project) = candidates
|
||||||
|
.iter()
|
||||||
|
.find(|project| project.provider == preferred)
|
||||||
|
{
|
||||||
|
(
|
||||||
|
Resolution::Resolved {
|
||||||
|
project: project.clone(),
|
||||||
|
},
|
||||||
|
candidates
|
||||||
|
.iter()
|
||||||
|
.filter(|candidate| *candidate != project)
|
||||||
|
.cloned()
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(Resolution::Ambiguous { candidates }, Vec::new())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => (Resolution::Ambiguous { candidates }, Vec::new()),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
record.resolution = resolution;
|
||||||
|
record.provider_aliases = aliases;
|
||||||
|
for provider in &checked {
|
||||||
|
if !record.provider_checks.contains(provider) {
|
||||||
|
record.provider_checks.push(provider.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn content_files(minecraft_dir: &Path) -> std::io::Result<Vec<(ContentKind, PathBuf)>> {
|
||||||
|
let mut files = Vec::new();
|
||||||
|
for kind in [
|
||||||
|
ContentKind::Mod,
|
||||||
|
ContentKind::ResourcePack,
|
||||||
|
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 path = entry.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 {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let path = entry.path();
|
||||||
|
if supported_content_path(ContentKind::DataPack, &path) {
|
||||||
|
files.push((ContentKind::DataPack, path));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
files.sort_by(|left, right| left.1.cmp(&right.1));
|
||||||
|
Ok(files)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supported_content_path(kind: ContentKind, path: &Path) -> bool {
|
||||||
|
if path.is_dir() {
|
||||||
|
return matches!(
|
||||||
|
kind,
|
||||||
|
ContentKind::ResourcePack | ContentKind::Shader | ContentKind::DataPack
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if !path.is_file() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
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(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/content/reconcile.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -1,265 +1,17 @@
|
|||||||
// resource pack scanning. packs can be either .zip files or plain directories,
|
// resource pack scanner backed by the shared pack.mcmeta reader.
|
||||||
// and metadata lives in pack.mcmeta (which mojang decided should have like 3
|
|
||||||
// different ways to encode a description, because why not)
|
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use serde::Deserialize;
|
use super::entry::ContentEntry;
|
||||||
|
|
||||||
use super::mods::{ContentEntry, make_icon_pixels};
|
|
||||||
|
|
||||||
#[derive(Deserialize, Default)]
|
|
||||||
pub(crate) struct PackMcMeta {
|
|
||||||
#[serde(default)]
|
|
||||||
pub pack: PackInfo,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize, Default)]
|
|
||||||
pub(crate) struct PackInfo {
|
|
||||||
#[serde(default)]
|
|
||||||
pub description: serde_json::Value,
|
|
||||||
}
|
|
||||||
|
|
||||||
// description can be a plain string, a chat component object with "text",
|
|
||||||
// or an array mixing both. thanks mojang, very cool.
|
|
||||||
pub(crate) fn extract_description(value: &serde_json::Value) -> String {
|
|
||||||
match value {
|
|
||||||
serde_json::Value::String(s) => s.clone(),
|
|
||||||
serde_json::Value::Object(obj) => obj
|
|
||||||
.get("text")
|
|
||||||
.and_then(|v| v.as_str())
|
|
||||||
.unwrap_or("")
|
|
||||||
.to_string(),
|
|
||||||
serde_json::Value::Array(arr) => arr
|
|
||||||
.iter()
|
|
||||||
.filter_map(|v| match v {
|
|
||||||
serde_json::Value::String(s) => Some(s.as_str()),
|
|
||||||
serde_json::Value::Object(obj) => obj.get("text").and_then(|v| v.as_str()),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join(""),
|
|
||||||
_ => String::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn scan_one_resource_pack(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
pub fn scan_one_resource_pack(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||||
let is_dir = path.is_dir();
|
super::packs::scan_one_pack(path, file_stem, enabled)
|
||||||
let (name, description, icon_bytes) = if is_dir {
|
|
||||||
read_pack_metadata_from_dir(path)
|
|
||||||
} else {
|
|
||||||
read_pack_metadata_from_zip(path)
|
|
||||||
};
|
|
||||||
|
|
||||||
let icon_lines = icon_bytes
|
|
||||||
.as_ref()
|
|
||||||
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
|
|
||||||
.or_else(|| Some(super::mods::fallback_icon()));
|
|
||||||
|
|
||||||
let display_name = if name.is_empty() {
|
|
||||||
file_stem.to_owned()
|
|
||||||
} else {
|
|
||||||
name
|
|
||||||
};
|
|
||||||
|
|
||||||
ContentEntry {
|
|
||||||
file_stem: file_stem.to_owned(),
|
|
||||||
name: display_name,
|
|
||||||
description,
|
|
||||||
enabled,
|
|
||||||
icon_bytes,
|
|
||||||
path: path.to_path_buf(),
|
|
||||||
icon_lines,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||||
let packs_dir = instances_dir
|
super::packs::scan_packs(instances_dir, instance_name, "resourcepacks")
|
||||||
.join(instance_name)
|
|
||||||
.join(".minecraft")
|
|
||||||
.join("resourcepacks");
|
|
||||||
|
|
||||||
let read_dir = match std::fs::read_dir(&packs_dir) {
|
|
||||||
Ok(rd) => rd,
|
|
||||||
Err(_) => return Vec::new(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut entries = Vec::new();
|
|
||||||
|
|
||||||
for entry in read_dir.flatten() {
|
|
||||||
let path = entry.path();
|
|
||||||
let file_name = match path.file_name().and_then(|n| n.to_str()) {
|
|
||||||
Some(n) => n.to_string(),
|
|
||||||
None => continue,
|
|
||||||
};
|
|
||||||
|
|
||||||
let (enabled, file_stem) = if path.is_dir() {
|
|
||||||
super::parse_enabled_stem_dir(&file_name)
|
|
||||||
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
|
|
||||||
pair
|
|
||||||
} else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
entries.push(scan_one_resource_pack(&path, &file_stem, enabled));
|
|
||||||
}
|
|
||||||
|
|
||||||
entries.sort_by_cached_key(|e| e.name.to_lowercase());
|
|
||||||
entries
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_pack_metadata_from_zip(zip_path: &Path) -> (String, String, Option<Vec<u8>>) {
|
|
||||||
let Some(mut archive) = super::open_zip(zip_path) else {
|
|
||||||
return (String::new(), String::new(), None);
|
|
||||||
};
|
|
||||||
let description = read_pack_description(&mut archive);
|
|
||||||
let icon_bytes = super::read_icon_from_zip(&mut archive);
|
|
||||||
(String::new(), description, icon_bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_pack_description(archive: &mut zip::ZipArchive<std::fs::File>) -> String {
|
|
||||||
archive
|
|
||||||
.by_name("pack.mcmeta")
|
|
||||||
.ok()
|
|
||||||
.and_then(|entry| serde_json::from_reader::<_, PackMcMeta>(entry).ok())
|
|
||||||
.map(|meta| extract_description(&meta.pack.description))
|
|
||||||
.unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_pack_metadata_from_dir(dir: &Path) -> (String, String, Option<Vec<u8>>) {
|
|
||||||
let description = std::fs::read_to_string(dir.join("pack.mcmeta"))
|
|
||||||
.ok()
|
|
||||||
.and_then(|content| serde_json::from_str::<PackMcMeta>(&content).ok())
|
|
||||||
.map(|meta| extract_description(&meta.pack.description))
|
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
let icon_bytes = std::fs::read(dir.join("pack.png")).ok();
|
|
||||||
|
|
||||||
(String::new(), description, icon_bytes)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "../tests/content/resource_packs.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_string() {
|
|
||||||
let val = serde_json::json!("Simple pack");
|
|
||||||
assert_eq!(extract_description(&val), "Simple pack");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_object_with_text() {
|
|
||||||
let val = serde_json::json!({"text": "Hello world"});
|
|
||||||
assert_eq!(extract_description(&val), "Hello world");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_object_without_text() {
|
|
||||||
let val = serde_json::json!({"color": "red"});
|
|
||||||
assert_eq!(extract_description(&val), "");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_array_of_strings() {
|
|
||||||
let val = serde_json::json!(["Hello", " ", "world"]);
|
|
||||||
assert_eq!(extract_description(&val), "Hello world");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_array_of_objects() {
|
|
||||||
let val = serde_json::json!([{"text": "A"}, {"text": "B"}]);
|
|
||||||
assert_eq!(extract_description(&val), "AB");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_mixed_array() {
|
|
||||||
let val = serde_json::json!(["Prefix ", {"text": "suffix"}]);
|
|
||||||
assert_eq!(extract_description(&val), "Prefix suffix");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_empty_array() {
|
|
||||||
let val = serde_json::json!([]);
|
|
||||||
assert_eq!(extract_description(&val), "");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_null() {
|
|
||||||
let val = serde_json::Value::Null;
|
|
||||||
assert_eq!(extract_description(&val), "");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_number() {
|
|
||||||
let val = serde_json::json!(42);
|
|
||||||
assert_eq!(extract_description(&val), "");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_bool() {
|
|
||||||
let val = serde_json::json!(true);
|
|
||||||
assert_eq!(extract_description(&val), "");
|
|
||||||
}
|
|
||||||
|
|
||||||
fn setup_packs_dir(tmp: &std::path::Path, instance: &str) -> std::path::PathBuf {
|
|
||||||
let dir = tmp.join(instance).join(".minecraft").join("resourcepacks");
|
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
|
||||||
dir
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_resource_packs_empty_dir() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
setup_packs_dir(tmp.path(), "inst");
|
|
||||||
let packs = scan_resource_packs(tmp.path(), "inst");
|
|
||||||
assert!(packs.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_resource_packs_missing_dir_returns_empty() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let packs = scan_resource_packs(tmp.path(), "ghost");
|
|
||||||
assert!(packs.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_resource_packs_finds_zips_and_dirs() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_packs_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("pack-a.zip"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::create_dir(dir.join("pack-b")).unwrap();
|
|
||||||
let packs = scan_resource_packs(tmp.path(), "inst");
|
|
||||||
assert_eq!(packs.len(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_resource_packs_disabled_variants() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_packs_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("on.zip"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::write(dir.join("off.zip.disabled"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::create_dir(dir.join("diron")).unwrap();
|
|
||||||
std::fs::create_dir(dir.join("diroff.disabled")).unwrap();
|
|
||||||
let packs = scan_resource_packs(tmp.path(), "inst");
|
|
||||||
assert_eq!(packs.len(), 4);
|
|
||||||
let on_zip = packs.iter().find(|p| p.file_stem == "on").unwrap();
|
|
||||||
let off_zip = packs.iter().find(|p| p.file_stem == "off").unwrap();
|
|
||||||
let on_dir = packs.iter().find(|p| p.file_stem == "diron").unwrap();
|
|
||||||
let off_dir = packs.iter().find(|p| p.file_stem == "diroff").unwrap();
|
|
||||||
assert!(on_zip.enabled);
|
|
||||||
assert!(!off_zip.enabled);
|
|
||||||
assert!(on_dir.enabled);
|
|
||||||
assert!(!off_dir.enabled);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_resource_packs_ignores_non_pack_files() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_packs_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("notes.txt"), "not a pack").unwrap();
|
|
||||||
std::fs::write(dir.join("valid.zip"), b"PK\x03\x04").unwrap();
|
|
||||||
let packs = scan_resource_packs(tmp.path(), "inst");
|
|
||||||
assert_eq!(packs.len(), 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,153 +1,13 @@
|
|||||||
// shader pack scanning. structurally almost identical to resource packs
|
// shader pack scanner backed by the shared pack.mcmeta reader.
|
||||||
// (zip or dir, pack.mcmeta for metadata, pack.png for icon)
|
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use super::mods::{ContentEntry, make_icon_pixels};
|
use super::entry::ContentEntry;
|
||||||
use super::resource_packs::{PackMcMeta, extract_description};
|
|
||||||
|
|
||||||
pub fn scan_one_shader(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
pub fn scan_one_shader(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||||
let is_dir = path.is_dir();
|
super::packs::scan_one_pack(path, file_stem, enabled)
|
||||||
let (description, icon_bytes) = if is_dir {
|
|
||||||
read_shader_metadata_from_dir(path)
|
|
||||||
} else {
|
|
||||||
read_shader_metadata_from_zip(path)
|
|
||||||
};
|
|
||||||
|
|
||||||
let icon_lines = icon_bytes
|
|
||||||
.as_ref()
|
|
||||||
.and_then(|bytes| make_icon_pixels(bytes, 6, 3));
|
|
||||||
|
|
||||||
ContentEntry {
|
|
||||||
file_stem: file_stem.to_owned(),
|
|
||||||
name: file_stem.to_owned(),
|
|
||||||
description,
|
|
||||||
enabled,
|
|
||||||
icon_bytes,
|
|
||||||
path: path.to_path_buf(),
|
|
||||||
icon_lines,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||||
let shaders_dir = instances_dir
|
super::packs::scan_packs(instances_dir, instance_name, "shaderpacks")
|
||||||
.join(instance_name)
|
|
||||||
.join(".minecraft")
|
|
||||||
.join("shaderpacks");
|
|
||||||
|
|
||||||
let read_dir = match std::fs::read_dir(&shaders_dir) {
|
|
||||||
Ok(rd) => rd,
|
|
||||||
Err(_) => return Vec::new(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut entries = Vec::new();
|
|
||||||
|
|
||||||
for entry in read_dir.flatten() {
|
|
||||||
let path = entry.path();
|
|
||||||
let file_name = match path.file_name().and_then(|n| n.to_str()) {
|
|
||||||
Some(n) => n.to_string(),
|
|
||||||
None => continue,
|
|
||||||
};
|
|
||||||
|
|
||||||
let (enabled, file_stem) = if path.is_dir() {
|
|
||||||
super::parse_enabled_stem_dir(&file_name)
|
|
||||||
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
|
|
||||||
pair
|
|
||||||
} else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
entries.push(scan_one_shader(&path, &file_stem, enabled));
|
|
||||||
}
|
|
||||||
|
|
||||||
entries.sort_by_cached_key(|e| e.name.to_lowercase());
|
|
||||||
entries
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_shader_metadata_from_zip(zip_path: &Path) -> (String, Option<Vec<u8>>) {
|
|
||||||
let Some(mut archive) = super::open_zip(zip_path) else {
|
|
||||||
return (String::new(), None);
|
|
||||||
};
|
|
||||||
let description = archive
|
|
||||||
.by_name("pack.mcmeta")
|
|
||||||
.ok()
|
|
||||||
.and_then(|entry| serde_json::from_reader::<_, PackMcMeta>(entry).ok())
|
|
||||||
.map(|meta| extract_description(&meta.pack.description))
|
|
||||||
.unwrap_or_default();
|
|
||||||
let icon_bytes = super::read_icon_from_zip(&mut archive);
|
|
||||||
(description, icon_bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_shader_metadata_from_dir(dir: &Path) -> (String, Option<Vec<u8>>) {
|
|
||||||
let description = std::fs::read_to_string(dir.join("pack.mcmeta"))
|
|
||||||
.ok()
|
|
||||||
.and_then(|content| serde_json::from_str::<PackMcMeta>(&content).ok())
|
|
||||||
.map(|meta| extract_description(&meta.pack.description))
|
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
let icon_bytes = std::fs::read(dir.join("pack.png")).ok();
|
|
||||||
|
|
||||||
(description, icon_bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn setup_shaders_dir(tmp: &std::path::Path, instance: &str) -> std::path::PathBuf {
|
|
||||||
let dir = tmp.join(instance).join(".minecraft").join("shaderpacks");
|
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
|
||||||
dir
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_shaders_empty_dir() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
setup_shaders_dir(tmp.path(), "inst");
|
|
||||||
let shaders = scan_shaders(tmp.path(), "inst");
|
|
||||||
assert!(shaders.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_shaders_missing_dir_returns_empty() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let shaders = scan_shaders(tmp.path(), "ghost");
|
|
||||||
assert!(shaders.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_shaders_finds_zip_and_dir() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_shaders_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("shader-a.zip"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::create_dir(dir.join("shader-b")).unwrap();
|
|
||||||
let shaders = scan_shaders(tmp.path(), "inst");
|
|
||||||
assert_eq!(shaders.len(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_shaders_disabled_variants() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_shaders_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("active.zip"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::write(dir.join("off.zip.disabled"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::create_dir(dir.join("dirshader.disabled")).unwrap();
|
|
||||||
let shaders = scan_shaders(tmp.path(), "inst");
|
|
||||||
let active = shaders.iter().find(|s| s.file_stem == "active").unwrap();
|
|
||||||
let off = shaders.iter().find(|s| s.file_stem == "off").unwrap();
|
|
||||||
let diroff = shaders.iter().find(|s| s.file_stem == "dirshader").unwrap();
|
|
||||||
assert!(active.enabled);
|
|
||||||
assert!(!off.enabled);
|
|
||||||
assert!(!diroff.enabled);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_shaders_ignores_non_shader_files() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_shaders_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("readme.txt"), "not a shader").unwrap();
|
|
||||||
std::fs::write(dir.join("valid.zip"), b"PK\x03\x04").unwrap();
|
|
||||||
let shaders = scan_shaders(tmp.path(), "inst");
|
|
||||||
assert_eq!(shaders.len(), 1);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,488 @@
|
|||||||
|
use std::sync::{Arc, LazyLock, Mutex};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::instance::{ContentKind, ContentManifest, InstanceConfig, ModLoader, ProviderProject};
|
||||||
|
use crate::net::modrinth::VersionInfo;
|
||||||
|
|
||||||
|
use super::dependencies::{DependencyPlan, InstallRoot};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct AvailableUpdate {
|
||||||
|
pub installed: ProviderProject,
|
||||||
|
#[serde(default)]
|
||||||
|
pub current: Option<VersionInfo>,
|
||||||
|
pub target: VersionInfo,
|
||||||
|
pub kind: ContentKind,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct UpdateSnapshot {
|
||||||
|
pub game_version: String,
|
||||||
|
pub loader: ModLoader,
|
||||||
|
#[serde(default)]
|
||||||
|
pub inventory: Vec<ProviderProject>,
|
||||||
|
pub updates: Vec<AvailableUpdate>,
|
||||||
|
pub failures: Vec<UpdateCheckFailure>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct UpdateCheckFailure {
|
||||||
|
pub installed: ProviderProject,
|
||||||
|
pub kind: ContentKind,
|
||||||
|
pub reason: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct PendingUpdateSnapshot {
|
||||||
|
pub instance_name: String,
|
||||||
|
pub instance_created: chrono::DateTime<chrono::Utc>,
|
||||||
|
pub snapshot: UpdateSnapshot,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct UpdateRequest {
|
||||||
|
pub title: String,
|
||||||
|
pub installed_path: std::path::PathBuf,
|
||||||
|
pub target_world: Option<std::path::PathBuf>,
|
||||||
|
pub update: AvailableUpdate,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct PlannedRootUpdate {
|
||||||
|
pub title: String,
|
||||||
|
pub installed_path: std::path::PathBuf,
|
||||||
|
pub current_version: String,
|
||||||
|
pub target: VersionInfo,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct UpdateConflict {
|
||||||
|
pub title: String,
|
||||||
|
pub installed_path: std::path::PathBuf,
|
||||||
|
pub reason: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct BulkUpdatePlan {
|
||||||
|
pub dependency_plan: DependencyPlan,
|
||||||
|
pub roots: Vec<PlannedRootUpdate>,
|
||||||
|
pub conflicts: Vec<UpdateConflict>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub static PENDING_UPDATE_SNAPSHOTS: LazyLock<Arc<Mutex<Vec<PendingUpdateSnapshot>>>> =
|
||||||
|
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
|
||||||
|
|
||||||
|
impl UpdateSnapshot {
|
||||||
|
pub fn load(path: &std::path::Path) -> Option<Self> {
|
||||||
|
std::fs::read(path)
|
||||||
|
.ok()
|
||||||
|
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn applies_to(&self, instance: &InstanceConfig) -> bool {
|
||||||
|
self.game_version == instance.game_version && self.loader == instance.loader
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn matches_manifest(&self, manifest: &ContentManifest) -> bool {
|
||||||
|
self.inventory == resolved_inventory(manifest)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update_for(&self, installed: &ProviderProject) -> Option<&AvailableUpdate> {
|
||||||
|
self.updates.iter().find(|update| {
|
||||||
|
update.installed.provider == installed.provider
|
||||||
|
&& update.installed.project_id == installed.project_id
|
||||||
|
&& update.installed.version_id == installed.version_id
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn spawn(instance: InstanceConfig, manifest: ContentManifest, path: std::path::PathBuf) {
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let snapshot = scan(&instance, &manifest).await;
|
||||||
|
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 async fn scan(instance: &InstanceConfig, manifest: &ContentManifest) -> UpdateSnapshot {
|
||||||
|
let mut projects = manifest
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.filter_map(|record| {
|
||||||
|
record
|
||||||
|
.resolved_project()
|
||||||
|
.cloned()
|
||||||
|
.map(|project| (project, record.kind))
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
projects.sort_by(|left, right| {
|
||||||
|
(&left.0.provider, &left.0.project_id, &left.0.version_id).cmp(&(
|
||||||
|
&right.0.provider,
|
||||||
|
&right.0.project_id,
|
||||||
|
&right.0.version_id,
|
||||||
|
))
|
||||||
|
});
|
||||||
|
projects.dedup_by(|left, right| {
|
||||||
|
left.0.provider == right.0.provider
|
||||||
|
&& left.0.project_id == right.0.project_id
|
||||||
|
&& left.0.version_id == right.0.version_id
|
||||||
|
});
|
||||||
|
let inventory = projects
|
||||||
|
.iter()
|
||||||
|
.map(|(project, _)| project.clone())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let slots = Arc::new(tokio::sync::Semaphore::new(8));
|
||||||
|
let mut tasks = tokio::task::JoinSet::new();
|
||||||
|
for (installed, kind) in projects {
|
||||||
|
let slots = slots.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 registry = crate::instance::content::provider::ProviderRegistry::configured(
|
||||||
|
crate::net::HttpClient::new(),
|
||||||
|
);
|
||||||
|
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 current = versions
|
||||||
|
.iter()
|
||||||
|
.find(|version| version.id == installed.version_id)
|
||||||
|
.cloned();
|
||||||
|
let target = versions.first().cloned().filter(|_| {
|
||||||
|
crate::instance::content::provider::has_newer_compatible_version(
|
||||||
|
&versions,
|
||||||
|
&installed.version_id,
|
||||||
|
)
|
||||||
|
});
|
||||||
|
Ok::<_, String>(target.map(|target| (current, target)))
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
(installed, kind, result)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut updates = Vec::new();
|
||||||
|
let mut failures = Vec::new();
|
||||||
|
while let Some(result) = tasks.join_next().await {
|
||||||
|
match result {
|
||||||
|
Ok((installed, kind, Ok(Some((current, target))))) => updates.push(AvailableUpdate {
|
||||||
|
installed,
|
||||||
|
current,
|
||||||
|
target,
|
||||||
|
kind,
|
||||||
|
}),
|
||||||
|
Ok((_, _, Ok(None))) => {}
|
||||||
|
Ok((installed, kind, Err(reason))) => failures.push(UpdateCheckFailure {
|
||||||
|
installed,
|
||||||
|
kind,
|
||||||
|
reason,
|
||||||
|
}),
|
||||||
|
Err(error) => tracing::debug!("Content update task failed: {error}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
updates.sort_by(|left, right| {
|
||||||
|
(&left.installed.provider, &left.installed.project_id)
|
||||||
|
.cmp(&(&right.installed.provider, &right.installed.project_id))
|
||||||
|
});
|
||||||
|
UpdateSnapshot {
|
||||||
|
game_version: instance.game_version.clone(),
|
||||||
|
loader: instance.loader,
|
||||||
|
inventory,
|
||||||
|
updates,
|
||||||
|
failures,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolved_inventory(manifest: &ContentManifest) -> Vec<ProviderProject> {
|
||||||
|
let mut inventory = manifest
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.filter_map(|record| record.resolved_project().cloned())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
inventory.sort_by(|left, right| {
|
||||||
|
(&left.provider, &left.project_id, &left.version_id).cmp(&(
|
||||||
|
&right.provider,
|
||||||
|
&right.project_id,
|
||||||
|
&right.version_id,
|
||||||
|
))
|
||||||
|
});
|
||||||
|
inventory.dedup();
|
||||||
|
inventory
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn plan_bulk(
|
||||||
|
instance: &InstanceConfig,
|
||||||
|
manifest: &ContentManifest,
|
||||||
|
minecraft_dir: &std::path::Path,
|
||||||
|
requests: Vec<UpdateRequest>,
|
||||||
|
mut conflicts: Vec<UpdateConflict>,
|
||||||
|
) -> 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)
|
||||||
|
{
|
||||||
|
projected.resolution = current.resolution.clone();
|
||||||
|
}
|
||||||
|
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 {
|
||||||
|
items: Vec::new(),
|
||||||
|
root_count: 0,
|
||||||
|
optional_dependencies: 0,
|
||||||
|
}),
|
||||||
|
roots,
|
||||||
|
conflicts,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn project_updates(
|
||||||
|
manifest: &ContentManifest,
|
||||||
|
minecraft_dir: &std::path::Path,
|
||||||
|
requests: &[UpdateRequest],
|
||||||
|
) -> ContentManifest {
|
||||||
|
let mut projected = manifest.clone();
|
||||||
|
for request in requests {
|
||||||
|
let Ok(relative_path) = request.installed_path.strip_prefix(minecraft_dir) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(record) = projected
|
||||||
|
.files
|
||||||
|
.iter_mut()
|
||||||
|
.find(|record| record.relative_path == relative_path)
|
||||||
|
else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
record.resolution = crate::instance::Resolution::Resolved {
|
||||||
|
project: ProviderProject {
|
||||||
|
provider: request.update.installed.provider.clone(),
|
||||||
|
project_id: request.update.installed.project_id.clone(),
|
||||||
|
version_id: request.update.target.id.clone(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
projected
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::net::modrinth::{VersionFile, VersionType};
|
||||||
|
|
||||||
|
fn version(id: &str) -> VersionInfo {
|
||||||
|
VersionInfo {
|
||||||
|
id: id.to_owned(),
|
||||||
|
project_id: "project".to_owned(),
|
||||||
|
name: id.to_owned(),
|
||||||
|
version_number: id.to_owned(),
|
||||||
|
game_versions: vec!["1.21.1".to_owned()],
|
||||||
|
loaders: vec!["fabric".to_owned()],
|
||||||
|
version_type: VersionType::Release,
|
||||||
|
dependencies: Vec::new(),
|
||||||
|
date_published: String::new(),
|
||||||
|
files: Vec::<VersionFile>::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cached_updates_match_the_exact_installed_version() {
|
||||||
|
let installed = ProviderProject {
|
||||||
|
provider: "modrinth".to_owned(),
|
||||||
|
project_id: "project".to_owned(),
|
||||||
|
version_id: "old".to_owned(),
|
||||||
|
};
|
||||||
|
let snapshot = UpdateSnapshot {
|
||||||
|
game_version: "1.21.1".to_owned(),
|
||||||
|
loader: ModLoader::Fabric,
|
||||||
|
inventory: vec![installed.clone()],
|
||||||
|
updates: vec![AvailableUpdate {
|
||||||
|
installed: installed.clone(),
|
||||||
|
current: Some(version("old")),
|
||||||
|
target: version("new"),
|
||||||
|
kind: ContentKind::Mod,
|
||||||
|
}],
|
||||||
|
failures: Vec::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(snapshot.update_for(&installed).is_some());
|
||||||
|
assert!(
|
||||||
|
snapshot
|
||||||
|
.update_for(&ProviderProject {
|
||||||
|
version_id: "different".to_owned(),
|
||||||
|
..installed
|
||||||
|
})
|
||||||
|
.is_none()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cached_updates_require_the_same_content_inventory() {
|
||||||
|
let project = ProviderProject {
|
||||||
|
provider: "modrinth".to_owned(),
|
||||||
|
project_id: "project".to_owned(),
|
||||||
|
version_id: "old".to_owned(),
|
||||||
|
};
|
||||||
|
let snapshot = UpdateSnapshot {
|
||||||
|
game_version: "1.21.1".to_owned(),
|
||||||
|
loader: ModLoader::Fabric,
|
||||||
|
inventory: vec![project.clone()],
|
||||||
|
updates: Vec::new(),
|
||||||
|
failures: Vec::new(),
|
||||||
|
};
|
||||||
|
let mut manifest = ContentManifest::default();
|
||||||
|
manifest.files.push(crate::instance::ContentFileRecord {
|
||||||
|
relative_path: "mods/example.jar".into(),
|
||||||
|
kind: ContentKind::Mod,
|
||||||
|
enabled: true,
|
||||||
|
fingerprint: crate::instance::FileFingerprint {
|
||||||
|
size: 0,
|
||||||
|
modified_ns: 0,
|
||||||
|
hashes: Default::default(),
|
||||||
|
},
|
||||||
|
resolution: crate::instance::Resolution::Resolved { project },
|
||||||
|
provider_aliases: Vec::new(),
|
||||||
|
provider_checks: vec!["modrinth".to_owned()],
|
||||||
|
required_dependencies: Vec::new(),
|
||||||
|
automatic_dependency: false,
|
||||||
|
cleanup_eligible: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert!(snapshot.matches_manifest(&manifest));
|
||||||
|
manifest.files[0].resolution = crate::instance::Resolution::Unmatched {
|
||||||
|
checked_at: 0,
|
||||||
|
providers: Vec::new(),
|
||||||
|
};
|
||||||
|
assert!(!snapshot.matches_manifest(&manifest));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bulk_planning_projects_other_selected_updates() {
|
||||||
|
let minecraft = std::path::Path::new("/instance/minecraft");
|
||||||
|
let installed = ProviderProject {
|
||||||
|
provider: "modrinth".to_owned(),
|
||||||
|
project_id: "library".to_owned(),
|
||||||
|
version_id: "old".to_owned(),
|
||||||
|
};
|
||||||
|
let mut manifest = ContentManifest::default();
|
||||||
|
manifest.files.push(crate::instance::ContentFileRecord {
|
||||||
|
relative_path: "mods/library.jar".into(),
|
||||||
|
kind: ContentKind::Mod,
|
||||||
|
enabled: true,
|
||||||
|
fingerprint: crate::instance::FileFingerprint {
|
||||||
|
size: 1,
|
||||||
|
modified_ns: 1,
|
||||||
|
hashes: Default::default(),
|
||||||
|
},
|
||||||
|
resolution: crate::instance::Resolution::Resolved {
|
||||||
|
project: installed.clone(),
|
||||||
|
},
|
||||||
|
provider_aliases: Vec::new(),
|
||||||
|
provider_checks: vec!["modrinth".to_owned()],
|
||||||
|
required_dependencies: Vec::new(),
|
||||||
|
automatic_dependency: true,
|
||||||
|
cleanup_eligible: true,
|
||||||
|
});
|
||||||
|
let requests = vec![UpdateRequest {
|
||||||
|
title: "Library".to_owned(),
|
||||||
|
installed_path: minecraft.join("mods/library.jar"),
|
||||||
|
target_world: None,
|
||||||
|
update: AvailableUpdate {
|
||||||
|
installed,
|
||||||
|
current: Some(version("old")),
|
||||||
|
target: version("new"),
|
||||||
|
kind: ContentKind::Mod,
|
||||||
|
},
|
||||||
|
}];
|
||||||
|
|
||||||
|
let projected = project_updates(&manifest, minecraft, &requests);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
projected.files[0].resolved_project().unwrap().version_id,
|
||||||
|
"new"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
manifest.files[0].resolved_project().unwrap().version_id,
|
||||||
|
"old"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+132
-115
@@ -2,34 +2,88 @@
|
|||||||
// their icon as icon.png. also computes an approximate size from top-level
|
// 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.
|
// files + region data so the user gets some sense of how chonky their world is.
|
||||||
|
|
||||||
use std::path::Path;
|
use std::{fs::File, path::Path};
|
||||||
|
|
||||||
use super::mods::{ContentEntry, make_icon_pixels};
|
use flate2::read::GzDecoder;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
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 {
|
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 = std::fs::read(path.join("icon.png")).ok();
|
||||||
let icon_lines = icon_bytes
|
let icon_lines = icon_bytes
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(|bytes| make_icon_pixels(bytes, 12, 6))
|
.and_then(|bytes| make_icon_pixels(bytes, 12, 6))
|
||||||
.or_else(|| Some(super::mods::fallback_icon_large()));
|
.or_else(|| Some(fallback_icon_large()));
|
||||||
|
|
||||||
let description = world_description(path);
|
let metadata = read_world_metadata(path);
|
||||||
|
let last_played = world_last_played(path, metadata.as_ref());
|
||||||
|
let size = dir_size_approx(path);
|
||||||
|
let world_details = WorldDetails {
|
||||||
|
game_mode: metadata.as_ref().and_then(WorldMetadata::game_mode),
|
||||||
|
last_played,
|
||||||
|
minecraft_version: metadata
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|metadata| metadata.version.as_ref())
|
||||||
|
.and_then(|version| version.name.as_deref())
|
||||||
|
.filter(|version| !version.trim().is_empty())
|
||||||
|
.map(str::to_owned),
|
||||||
|
size: (size > 0).then(|| format_size(size)),
|
||||||
|
datapacks: datapack_names(path),
|
||||||
|
};
|
||||||
|
|
||||||
ContentEntry {
|
ContentEntry {
|
||||||
name: file_stem.to_owned(),
|
name: metadata
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|metadata| metadata.level_name.as_deref())
|
||||||
|
.filter(|name| !name.trim().is_empty())
|
||||||
|
.unwrap_or(file_stem)
|
||||||
|
.to_owned(),
|
||||||
file_stem: file_stem.to_owned(),
|
file_stem: file_stem.to_owned(),
|
||||||
description,
|
source_slug: None,
|
||||||
|
installed_path: None,
|
||||||
|
provider_project: None,
|
||||||
|
world_details: Some(world_details),
|
||||||
|
title_suffix: None,
|
||||||
|
footer_label: None,
|
||||||
|
footer_change: None,
|
||||||
|
description: String::new(),
|
||||||
enabled,
|
enabled,
|
||||||
icon_bytes,
|
icon_bytes,
|
||||||
|
provider_icon: false,
|
||||||
|
provider_description: false,
|
||||||
path: path.to_path_buf(),
|
path: path.to_path_buf(),
|
||||||
icon_lines,
|
icon_lines,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn datapack_names(world: &Path) -> Vec<String> {
|
||||||
|
let Ok(entries) = std::fs::read_dir(world.join("datapacks")) else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let mut names = entries
|
||||||
|
.flatten()
|
||||||
|
.filter_map(|entry| {
|
||||||
|
let path = entry.path();
|
||||||
|
let name = path.file_name()?.to_str()?;
|
||||||
|
if path.is_dir() {
|
||||||
|
Some(name.trim_end_matches(".disabled").to_owned())
|
||||||
|
} else {
|
||||||
|
name.strip_suffix(".zip")
|
||||||
|
.or_else(|| name.strip_suffix(".zip.disabled"))
|
||||||
|
.map(str::to_owned)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
names.sort_by_key(|name| name.to_lowercase());
|
||||||
|
names
|
||||||
|
}
|
||||||
|
|
||||||
pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||||
let saves_dir = instances_dir
|
let saves_dir = instances_dir
|
||||||
.join(instance_name)
|
.join(instance_name)
|
||||||
.join(".minecraft")
|
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||||
.join("saves");
|
.join("saves");
|
||||||
|
|
||||||
let read_dir = match std::fs::read_dir(&saves_dir) {
|
let read_dir = match std::fs::read_dir(&saves_dir) {
|
||||||
@@ -58,44 +112,80 @@ pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntr
|
|||||||
entries
|
entries
|
||||||
}
|
}
|
||||||
|
|
||||||
fn world_description(world_dir: &Path) -> String {
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct LevelDat {
|
||||||
|
#[serde(rename = "Data")]
|
||||||
|
data: WorldMetadata,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct WorldMetadata {
|
||||||
|
#[serde(rename = "LevelName")]
|
||||||
|
level_name: Option<String>,
|
||||||
|
#[serde(rename = "GameType")]
|
||||||
|
game_type: Option<i32>,
|
||||||
|
#[serde(rename = "hardcore")]
|
||||||
|
hardcore: Option<i8>,
|
||||||
|
#[serde(rename = "LastPlayed")]
|
||||||
|
last_played: Option<i64>,
|
||||||
|
#[serde(rename = "Version")]
|
||||||
|
version: Option<WorldVersion>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct WorldVersion {
|
||||||
|
#[serde(rename = "Name")]
|
||||||
|
name: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WorldMetadata {
|
||||||
|
fn game_mode(&self) -> Option<WorldGameMode> {
|
||||||
|
if self.hardcore.is_some_and(|hardcore| hardcore != 0) {
|
||||||
|
return Some(WorldGameMode::Hardcore);
|
||||||
|
}
|
||||||
|
Some(match self.game_type? {
|
||||||
|
0 => WorldGameMode::Survival,
|
||||||
|
1 => WorldGameMode::Creative,
|
||||||
|
2 => WorldGameMode::Adventure,
|
||||||
|
3 => WorldGameMode::Spectator,
|
||||||
|
_ => return None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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)) {
|
||||||
|
Ok(level) => Some(level.data),
|
||||||
|
Err(error) => {
|
||||||
|
tracing::debug!(
|
||||||
|
"Could not read world metadata from {}: {error}",
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn world_last_played(
|
||||||
|
world_dir: &Path,
|
||||||
|
metadata: Option<&WorldMetadata>,
|
||||||
|
) -> Option<chrono::DateTime<chrono::Utc>> {
|
||||||
let level_dat = world_dir.join("level.dat");
|
let level_dat = world_dir.join("level.dat");
|
||||||
|
metadata
|
||||||
let created = world_dir
|
.and_then(|metadata| metadata.last_played)
|
||||||
.metadata()
|
.filter(|millis| *millis > 0)
|
||||||
.ok()
|
.map(|millis| millis / 1000)
|
||||||
.and_then(|m| m.created().ok().or_else(|| m.modified().ok()))
|
.or_else(|| {
|
||||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
level_dat
|
||||||
.map(|d| d.as_secs());
|
|
||||||
|
|
||||||
let modified = level_dat
|
|
||||||
.metadata()
|
.metadata()
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|m| m.modified().ok())
|
.and_then(|m| m.modified().ok())
|
||||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||||
.map(|d| d.as_secs());
|
.map(|d| d.as_secs() as i64)
|
||||||
|
})
|
||||||
let dir_size = dir_size_approx(world_dir);
|
.and_then(|seconds| chrono::DateTime::from_timestamp(seconds, 0))
|
||||||
|
|
||||||
let mut lines = Vec::new();
|
|
||||||
|
|
||||||
if let Some(secs) = created
|
|
||||||
&& let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0)
|
|
||||||
{
|
|
||||||
lines.push(format!("Created: {}", dt.format("%Y-%m-%d %H:%M")));
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(secs) = modified
|
|
||||||
&& let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0)
|
|
||||||
{
|
|
||||||
lines.push(format!("Played: {}", dt.format("%Y-%m-%d %H:%M")));
|
|
||||||
}
|
|
||||||
|
|
||||||
if dir_size > 0 {
|
|
||||||
lines.push(format!("Size: {}", format_size(dir_size)));
|
|
||||||
}
|
|
||||||
|
|
||||||
lines.join("\n")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// only counts top-level files + region/ contents, not a full recursive walk.
|
// only counts top-level files + region/ contents, not a full recursive walk.
|
||||||
@@ -136,78 +226,5 @@ fn format_size(bytes: u64) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "../tests/content/worlds.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
fn setup_saves_dir(tmp: &Path, instance: &str) -> std::path::PathBuf {
|
|
||||||
let dir = tmp.join(instance).join(".minecraft").join("saves");
|
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
|
||||||
dir
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_worlds_empty_dir() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
setup_saves_dir(tmp.path(), "inst");
|
|
||||||
let worlds = scan_worlds(tmp.path(), "inst");
|
|
||||||
assert!(worlds.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_worlds_missing_dir_returns_empty() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let worlds = scan_worlds(tmp.path(), "ghost");
|
|
||||||
assert!(worlds.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_worlds_finds_directories() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_saves_dir(tmp.path(), "inst");
|
|
||||||
std::fs::create_dir(dir.join("My World")).unwrap();
|
|
||||||
std::fs::create_dir(dir.join("Creative")).unwrap();
|
|
||||||
let worlds = scan_worlds(tmp.path(), "inst");
|
|
||||||
assert_eq!(worlds.len(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_worlds_ignores_files() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_saves_dir(tmp.path(), "inst");
|
|
||||||
std::fs::create_dir(dir.join("World1")).unwrap();
|
|
||||||
std::fs::write(dir.join("stray-file.txt"), "not a world").unwrap();
|
|
||||||
let worlds = scan_worlds(tmp.path(), "inst");
|
|
||||||
assert_eq!(worlds.len(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_worlds_disabled_world() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_saves_dir(tmp.path(), "inst");
|
|
||||||
std::fs::create_dir(dir.join("ActiveWorld")).unwrap();
|
|
||||||
std::fs::create_dir(dir.join("HiddenWorld.disabled")).unwrap();
|
|
||||||
let worlds = scan_worlds(tmp.path(), "inst");
|
|
||||||
let active = worlds
|
|
||||||
.iter()
|
|
||||||
.find(|w| w.file_stem == "ActiveWorld")
|
|
||||||
.unwrap();
|
|
||||||
let hidden = worlds
|
|
||||||
.iter()
|
|
||||||
.find(|w| w.file_stem == "HiddenWorld")
|
|
||||||
.unwrap();
|
|
||||||
assert!(active.enabled);
|
|
||||||
assert!(!hidden.enabled);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_worlds_sorted_case_insensitive() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_saves_dir(tmp.path(), "inst");
|
|
||||||
std::fs::create_dir(dir.join("Zeta")).unwrap();
|
|
||||||
std::fs::create_dir(dir.join("alpha")).unwrap();
|
|
||||||
std::fs::create_dir(dir.join("Beta")).unwrap();
|
|
||||||
let worlds = scan_worlds(tmp.path(), "inst");
|
|
||||||
let names: Vec<&str> = worlds.iter().map(|w| w.name.as_str()).collect();
|
|
||||||
assert_eq!(names, vec!["alpha", "Beta", "Zeta"]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+12
-48
@@ -20,7 +20,7 @@ pub fn desktop_path(name: &str) -> Option<PathBuf> {
|
|||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
{
|
{
|
||||||
dirs::desktop_dir().map(|d| d.join(format!("Minecraft - {sanitized}.bat")))
|
dirs::desktop_dir().map(|d| d.join(format!("Minecraft - {sanitized}.vbs")))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
@@ -141,7 +141,7 @@ fn build_content(name: &str, icon: Option<&Path>) -> String {
|
|||||||
fn build_linux_desktop(name: &str, icon: Option<&Path>) -> String {
|
fn build_linux_desktop(name: &str, icon: Option<&Path>) -> String {
|
||||||
let mut out = String::new();
|
let mut out = String::new();
|
||||||
out.push_str("[Desktop Entry]\n");
|
out.push_str("[Desktop Entry]\n");
|
||||||
out.push_str("Version=1.0\n");
|
out.push_str("Version=0.3.1\n");
|
||||||
out.push_str("Type=Application\n");
|
out.push_str("Type=Application\n");
|
||||||
out.push_str(&format!("Name=Minecraft - {name}\n"));
|
out.push_str(&format!("Name=Minecraft - {name}\n"));
|
||||||
out.push_str(&format!("Comment=Launch {name} Minecraft instance\n"));
|
out.push_str(&format!("Comment=Launch {name} Minecraft instance\n"));
|
||||||
@@ -149,18 +149,21 @@ fn build_linux_desktop(name: &str, icon: Option<&Path>) -> String {
|
|||||||
if let Some(icon) = icon {
|
if let Some(icon) = icon {
|
||||||
out.push_str(&format!("Icon={}\n", icon.display()));
|
out.push_str(&format!("Icon={}\n", icon.display()));
|
||||||
}
|
}
|
||||||
out.push_str("Terminal=true\n");
|
out.push_str("Terminal=false\n");
|
||||||
out.push_str("Categories=Game;\n");
|
out.push_str("Categories=Game;\n");
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
fn build_windows_shortcut(name: &str) -> String {
|
fn build_windows_shortcut(name: &str) -> String {
|
||||||
|
let escaped_name = name.replace('"', "\"\"");
|
||||||
|
|
||||||
let mut out = String::new();
|
let mut out = String::new();
|
||||||
out.push_str("@echo off\r\n");
|
out.push_str("Set shell = CreateObject(\"WScript.Shell\")\r\n");
|
||||||
out.push_str(&format!("title Minecraft - {name}\r\n"));
|
out.push_str(&format!(
|
||||||
out.push_str(&format!("rmcl instance launch \"{name}\"\r\n"));
|
"shell.Run \"rmcl instance launch \"\"{}\"\"\", 0, False\r\n",
|
||||||
out.push_str("pause\r\n");
|
escaped_name
|
||||||
|
));
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -187,44 +190,5 @@ fn sanitize(name: &str) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/desktop.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn sanitize_keeps_alphanumeric() {
|
|
||||||
assert_eq!(sanitize("my-instance_123"), "my-instance_123");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn sanitize_replaces_special_chars() {
|
|
||||||
assert_eq!(sanitize("my instance!"), "my_instance_");
|
|
||||||
assert_eq!(sanitize("path/traversal"), "path_traversal");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn desktop_path_returns_some() {
|
|
||||||
let path = desktop_path("TestPack");
|
|
||||||
if let Some(p) = path {
|
|
||||||
let name = p.file_name().unwrap().to_str().unwrap();
|
|
||||||
assert!(name.contains("TestPack"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
fn build_content_linux() {
|
|
||||||
let content = build_content("TestPack", None);
|
|
||||||
assert!(content.contains("Name=Minecraft - TestPack"));
|
|
||||||
assert!(content.contains("Exec=rmcl instance launch \"TestPack\""));
|
|
||||||
assert!(content.contains("Terminal=true"));
|
|
||||||
assert!(content.contains("Categories=Game;"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
fn build_content_linux_with_icon() {
|
|
||||||
let icon = PathBuf::from("/tmp/icon.png");
|
|
||||||
let content = build_content("TestPack", Some(&icon));
|
|
||||||
assert!(content.contains("Icon=/tmp/icon.png"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
// 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 crate::feedback::progress;
|
||||||
|
use crate::instance::{InstanceConfig, InstanceManager, ModLoader};
|
||||||
|
|
||||||
|
use super::{ImportSummary, PackFormat};
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct Manifest {
|
||||||
|
name: String,
|
||||||
|
version: String,
|
||||||
|
minecraft: Minecraft,
|
||||||
|
#[serde(default)]
|
||||||
|
files: Vec<ManifestFile>,
|
||||||
|
#[serde(default = "default_overrides")]
|
||||||
|
overrides: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct Minecraft {
|
||||||
|
version: String,
|
||||||
|
#[serde(default)]
|
||||||
|
mod_loaders: Vec<ManifestLoader>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct ManifestLoader {
|
||||||
|
id: String,
|
||||||
|
#[serde(default)]
|
||||||
|
primary: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct ManifestFile {
|
||||||
|
#[serde(rename = "projectID")]
|
||||||
|
_project_id: u64,
|
||||||
|
#[serde(rename = "fileID")]
|
||||||
|
file_id: u64,
|
||||||
|
#[serde(default = "required_by_default")]
|
||||||
|
required: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_overrides() -> String {
|
||||||
|
"overrides".to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn required_by_default() -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse(path: &Path) -> Result<Manifest, 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 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}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn loader(manifest: &Manifest) -> (ModLoader, Option<String>) {
|
||||||
|
let id = manifest
|
||||||
|
.minecraft
|
||||||
|
.mod_loaders
|
||||||
|
.iter()
|
||||||
|
.find(|loader| loader.primary)
|
||||||
|
.or_else(|| manifest.minecraft.mod_loaders.first())
|
||||||
|
.map(|loader| loader.id.as_str());
|
||||||
|
let Some(id) = id else {
|
||||||
|
return (ModLoader::Vanilla, None);
|
||||||
|
};
|
||||||
|
let (name, version) = id.split_once('-').unwrap_or((id, ""));
|
||||||
|
let loader = match name.to_ascii_lowercase().as_str() {
|
||||||
|
"fabric" => ModLoader::Fabric,
|
||||||
|
"forge" => ModLoader::Forge,
|
||||||
|
"neoforge" => ModLoader::NeoForge,
|
||||||
|
"quilt" => ModLoader::Quilt,
|
||||||
|
_ => ModLoader::Vanilla,
|
||||||
|
};
|
||||||
|
(
|
||||||
|
loader,
|
||||||
|
(!version.is_empty() && loader != ModLoader::Vanilla).then(|| version.to_owned()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
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)?;
|
||||||
|
Ok(ImportSummary {
|
||||||
|
name: manifest.name,
|
||||||
|
pack_version: manifest.version,
|
||||||
|
game_version: manifest.minecraft.version,
|
||||||
|
loader,
|
||||||
|
loader_version,
|
||||||
|
mod_count: manifest.files.iter().filter(|file| file.required).count(),
|
||||||
|
override_count,
|
||||||
|
format: PackFormat::CurseForge,
|
||||||
|
archive_path: path.to_owned(),
|
||||||
|
source: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
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) })?;
|
||||||
|
let minecraft_dir = manager
|
||||||
|
.instances_dir
|
||||||
|
.join(&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)
|
||||||
|
}
|
||||||
|
|
||||||
|
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<_>>();
|
||||||
|
let versions = crate::net::curseforge::fetch_file_versions(&client, api_key, &ids).await?;
|
||||||
|
if versions.len() != ids.len() {
|
||||||
|
return Err(format!(
|
||||||
|
"CurseForge returned {} of {} required pack files",
|
||||||
|
versions.len(),
|
||||||
|
ids.len()
|
||||||
|
)
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
let mods_dir = minecraft_dir.join("mods");
|
||||||
|
tokio::fs::create_dir_all(&mods_dir).await?;
|
||||||
|
let total = versions.len();
|
||||||
|
progress::set_action(format!("Downloading mods... 0/{total}"));
|
||||||
|
let completed = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||||
|
let slots = std::sync::Arc::new(tokio::sync::Semaphore::new(10));
|
||||||
|
let mut tasks = tokio::task::JoinSet::new();
|
||||||
|
for mut version in versions {
|
||||||
|
let client = client.clone();
|
||||||
|
let api_key = api_key.to_owned();
|
||||||
|
let mods_dir = mods_dir.clone();
|
||||||
|
let completed = completed.clone();
|
||||||
|
let slots = slots.clone();
|
||||||
|
tasks.spawn(async move {
|
||||||
|
let _permit = slots.acquire_owned().await?;
|
||||||
|
crate::net::curseforge::ensure_download_url(&client, &api_key, &mut version).await?;
|
||||||
|
crate::net::modrinth::download_version_file(&client, &version, &mods_dir).await?;
|
||||||
|
let finished = completed.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
|
||||||
|
progress::set_action(format!("Downloading mods... {finished}/{total}"));
|
||||||
|
Ok::<(), Box<dyn std::error::Error + Send + Sync>>(())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
while let Some(result) = tasks.join_next().await {
|
||||||
|
result??;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
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 ids = manifest
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.filter(|file| file.required)
|
||||||
|
.map(|file| file.file_id)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let versions =
|
||||||
|
crate::net::curseforge::fetch_file_versions(&crate::net::HttpClient::new(), api_key, &ids)
|
||||||
|
.await
|
||||||
|
.map_err(|error| error.to_string())?;
|
||||||
|
if versions.len() != ids.len() {
|
||||||
|
return Err(format!(
|
||||||
|
"CurseForge returned {} of {} required pack files",
|
||||||
|
versions.len(),
|
||||||
|
ids.len()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
versions
|
||||||
|
.into_iter()
|
||||||
|
.map(|version| {
|
||||||
|
version
|
||||||
|
.files
|
||||||
|
.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))
|
||||||
|
})
|
||||||
|
.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())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extract_overrides(
|
||||||
|
path: &Path,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
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(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/import/curseforge.rs"]
|
||||||
|
mod tests;
|
||||||
+82
-47
@@ -4,9 +4,9 @@
|
|||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
|
use crate::feedback::progress;
|
||||||
use crate::instance::manager::InstanceManager;
|
use crate::instance::manager::InstanceManager;
|
||||||
use crate::instance::models::ModLoader;
|
use crate::instance::models::ModLoader;
|
||||||
use crate::tui::progress;
|
|
||||||
|
|
||||||
use super::{ImportSummary, PackFormat};
|
use super::{ImportSummary, PackFormat};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
@@ -51,6 +51,11 @@ impl MmcPack {
|
|||||||
|
|
||||||
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||||
let pack = parse_mmc_pack(path)?;
|
let pack = parse_mmc_pack(path)?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Parsed MultiMC pack {} with {} component(s)",
|
||||||
|
path.display(),
|
||||||
|
pack.components.len()
|
||||||
|
);
|
||||||
|
|
||||||
let game_version = pack
|
let game_version = pack
|
||||||
.game_version()
|
.game_version()
|
||||||
@@ -62,6 +67,15 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
|||||||
let name = instance_name_from_cfg(path).unwrap_or_else(|| "Imported Pack".to_string());
|
let name = instance_name_from_cfg(path).unwrap_or_else(|| "Imported Pack".to_string());
|
||||||
|
|
||||||
let (mod_count, override_count) = count_content_files(path)?;
|
let (mod_count, override_count) = count_content_files(path)?;
|
||||||
|
tracing::trace!(
|
||||||
|
"MultiMC summary: name='{}' game_version={} loader={:?} loader_version={:?} mods={} overrides={}",
|
||||||
|
name,
|
||||||
|
game_version,
|
||||||
|
loader,
|
||||||
|
loader_version,
|
||||||
|
mod_count,
|
||||||
|
override_count
|
||||||
|
);
|
||||||
|
|
||||||
Ok(ImportSummary {
|
Ok(ImportSummary {
|
||||||
name,
|
name,
|
||||||
@@ -73,6 +87,7 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
|||||||
override_count,
|
override_count,
|
||||||
format: PackFormat::Mmc,
|
format: PackFormat::Mmc,
|
||||||
archive_path: path.to_path_buf(),
|
archive_path: path.to_path_buf(),
|
||||||
|
source: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,6 +96,11 @@ pub async fn execute_import(
|
|||||||
manager: &InstanceManager,
|
manager: &InstanceManager,
|
||||||
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
|
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
let name = super::unique_instance_name(&summary.name, &manager.instances_dir);
|
let name = super::unique_instance_name(&summary.name, &manager.instances_dir);
|
||||||
|
tracing::info!(
|
||||||
|
"Importing MultiMC/Prism pack '{}' as instance '{}'",
|
||||||
|
summary.name,
|
||||||
|
name
|
||||||
|
);
|
||||||
|
|
||||||
progress::set_action(format!("Importing '{name}'..."));
|
progress::set_action(format!("Importing '{name}'..."));
|
||||||
progress::set_sub_action(format!("{} {}", summary.game_version, summary.loader));
|
progress::set_sub_action(format!("{} {}", summary.game_version, summary.loader));
|
||||||
@@ -95,10 +115,21 @@ pub async fn execute_import(
|
|||||||
.await
|
.await
|
||||||
.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) })?;
|
||||||
|
|
||||||
let minecraft_dir = manager.instances_dir.join(&name).join(".minecraft");
|
let minecraft_dir = manager
|
||||||
extract_mmc_archive(&summary.archive_path, &minecraft_dir)?;
|
.instances_dir
|
||||||
|
.join(&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);
|
||||||
|
}
|
||||||
|
|
||||||
progress::clear();
|
progress::clear();
|
||||||
|
tracing::info!(
|
||||||
|
"Imported MultiMC/Prism pack '{}' as '{}'",
|
||||||
|
summary.name,
|
||||||
|
name
|
||||||
|
);
|
||||||
Ok(config)
|
Ok(config)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,18 +148,41 @@ fn extract_mmc_archive(
|
|||||||
|
|
||||||
let prefix = find_archive_prefix(&archive);
|
let prefix = find_archive_prefix(&archive);
|
||||||
let minecraft_prefix = format!("{prefix}.minecraft/");
|
let minecraft_prefix = format!("{prefix}.minecraft/");
|
||||||
|
tracing::debug!(
|
||||||
|
"Extracting MultiMC archive {} with prefix '{}' into {}",
|
||||||
|
archive_path.display(),
|
||||||
|
prefix,
|
||||||
|
minecraft_dir.display()
|
||||||
|
);
|
||||||
|
|
||||||
let total = archive.len();
|
let total = archive.len();
|
||||||
|
let mut extracted = 0usize;
|
||||||
|
let mut dirs = 0usize;
|
||||||
for i in 0..total {
|
for i in 0..total {
|
||||||
let mut entry = archive.by_index(i)?;
|
let mut entry = archive.by_index(i)?;
|
||||||
let entry_name = entry.name().to_string();
|
let entry_name = entry.name().to_string();
|
||||||
|
|
||||||
let Some(relative) = entry_name.strip_prefix(&minecraft_prefix) else {
|
if !entry_name.starts_with(&minecraft_prefix) {
|
||||||
continue;
|
continue;
|
||||||
};
|
}
|
||||||
|
let enclosed = entry.enclosed_name().ok_or_else(|| {
|
||||||
|
std::io::Error::new(
|
||||||
|
std::io::ErrorKind::InvalidData,
|
||||||
|
format!("Unsafe archive path: {entry_name}"),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let relative = enclosed
|
||||||
|
.strip_prefix(minecraft_prefix.trim_end_matches('/'))
|
||||||
|
.map_err(|_| {
|
||||||
|
std::io::Error::new(
|
||||||
|
std::io::ErrorKind::InvalidData,
|
||||||
|
format!("Invalid archive path: {entry_name}"),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
if relative.is_empty() || entry_name.ends_with('/') {
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,14 +191,30 @@ fn extract_mmc_archive(
|
|||||||
std::fs::create_dir_all(parent)?;
|
std::fs::create_dir_all(parent)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let filename = relative.rsplit('/').next().unwrap_or(relative);
|
let filename = relative
|
||||||
|
.file_name()
|
||||||
|
.and_then(|name| name.to_str())
|
||||||
|
.unwrap_or_default();
|
||||||
progress::set_sub_action(filename.to_string());
|
progress::set_sub_action(filename.to_string());
|
||||||
|
|
||||||
let mut buf = Vec::new();
|
let mut buf = Vec::new();
|
||||||
entry.read_to_end(&mut buf)?;
|
entry.read_to_end(&mut buf)?;
|
||||||
|
tracing::trace!(
|
||||||
|
"Extracting MultiMC entry {} to {} ({} bytes)",
|
||||||
|
entry_name,
|
||||||
|
dest.display(),
|
||||||
|
buf.len()
|
||||||
|
);
|
||||||
std::fs::write(&dest, &buf)?;
|
std::fs::write(&dest, &buf)?;
|
||||||
|
extracted += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tracing::debug!(
|
||||||
|
"Extracted {} files and {} directories from MultiMC archive {}",
|
||||||
|
extracted,
|
||||||
|
dirs,
|
||||||
|
archive_path.display()
|
||||||
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,6 +237,7 @@ fn instance_name_from_cfg(path: &Path) -> Option<String> {
|
|||||||
let mut archive = zip::ZipArchive::new(file).ok()?;
|
let mut archive = zip::ZipArchive::new(file).ok()?;
|
||||||
|
|
||||||
let entry_name = find_entry(&archive, "instance.cfg")?;
|
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 entry = archive.by_name(&entry_name).ok()?;
|
||||||
|
|
||||||
let reader = std::io::BufRead::lines(std::io::BufReader::new(entry));
|
let reader = std::io::BufRead::lines(std::io::BufReader::new(entry));
|
||||||
@@ -174,6 +245,7 @@ fn instance_name_from_cfg(path: &Path) -> Option<String> {
|
|||||||
if let Some(value) = line.strip_prefix("name=") {
|
if let Some(value) = line.strip_prefix("name=") {
|
||||||
let name = value.trim().to_string();
|
let name = value.trim().to_string();
|
||||||
if !name.is_empty() {
|
if !name.is_empty() {
|
||||||
|
tracing::debug!("Read MultiMC instance name '{}' from instance.cfg", name);
|
||||||
return Some(name);
|
return Some(name);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -181,7 +253,7 @@ fn instance_name_from_cfg(path: &Path) -> Option<String> {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
// finds the prefix for the archive — empty for flat zips, "DirName/" for nested
|
// finds the prefix for the archive: empty for flat zips, "DirName/" for nested
|
||||||
fn find_archive_prefix(archive: &zip::ZipArchive<std::fs::File>) -> String {
|
fn find_archive_prefix(archive: &zip::ZipArchive<std::fs::File>) -> String {
|
||||||
for name in archive.file_names() {
|
for name in archive.file_names() {
|
||||||
if name.ends_with("mmc-pack.json") {
|
if name.ends_with("mmc-pack.json") {
|
||||||
@@ -231,42 +303,5 @@ fn count_content_files(path: &Path) -> Result<(usize, usize), String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "../tests/import/mmc.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parse_mmc_pack_json() {
|
|
||||||
let json = r#"{
|
|
||||||
"formatVersion": 1,
|
|
||||||
"components": [
|
|
||||||
{
|
|
||||||
"uid": "net.minecraft",
|
|
||||||
"version": "1.7.10",
|
|
||||||
"cachedName": "Minecraft"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"uid": "net.minecraftforge",
|
|
||||||
"version": "10.13.4.1614",
|
|
||||||
"cachedName": "Forge"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}"#;
|
|
||||||
let pack: MmcPack = serde_json::from_str(json).unwrap();
|
|
||||||
assert_eq!(pack.game_version(), Some("1.7.10".to_string()));
|
|
||||||
let (loader, version) = pack.loader();
|
|
||||||
assert_eq!(loader, Some(ModLoader::Forge));
|
|
||||||
assert_eq!(version, Some("10.13.4.1614".to_string()));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parse_mmc_pack_vanilla() {
|
|
||||||
let json = r#"{
|
|
||||||
"formatVersion": 1,
|
|
||||||
"components": [
|
|
||||||
{"uid": "net.minecraft", "version": "1.21.4"}
|
|
||||||
]
|
|
||||||
}"#;
|
|
||||||
let pack: MmcPack = serde_json::from_str(json).unwrap();
|
|
||||||
assert!(pack.loader().0.is_none());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+152
-97
@@ -1,8 +1,10 @@
|
|||||||
// modpack importing: parses user input, detects pack format from zip contents,
|
// modpack importing: parses user input, detects pack format from zip contents,
|
||||||
// builds a summary, and delegates the actual import to format-specific modules.
|
// builds a summary, and delegates the actual import to format-specific modules.
|
||||||
|
|
||||||
|
pub mod curseforge;
|
||||||
pub mod mmc;
|
pub mod mmc;
|
||||||
pub mod mrpack;
|
pub mod mrpack;
|
||||||
|
pub mod refresh;
|
||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
@@ -11,6 +13,7 @@ use crate::instance::models::ModLoader;
|
|||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum PackFormat {
|
pub enum PackFormat {
|
||||||
|
CurseForge,
|
||||||
Mrpack,
|
Mrpack,
|
||||||
Mmc,
|
Mmc,
|
||||||
}
|
}
|
||||||
@@ -33,6 +36,7 @@ pub fn parse_import_input(input: &str) -> ImportInput {
|
|||||||
|| input.starts_with('/')
|
|| input.starts_with('/')
|
||||||
|| input.starts_with("~/")
|
|| input.starts_with("~/")
|
||||||
{
|
{
|
||||||
|
tracing::debug!("Import input resolved as local file: {}", input);
|
||||||
return ImportInput::LocalFile(input.to_string());
|
return ImportInput::LocalFile(input.to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,7 +45,7 @@ pub fn parse_import_input(input: &str) -> ImportInput {
|
|||||||
.or_else(|| input.strip_prefix("http://modrinth.com/modpack/"))
|
.or_else(|| input.strip_prefix("http://modrinth.com/modpack/"))
|
||||||
{
|
{
|
||||||
let parts: Vec<&str> = rest.split('/').filter(|s| !s.is_empty()).collect();
|
let parts: Vec<&str> = rest.split('/').filter(|s| !s.is_empty()).collect();
|
||||||
return match parts.as_slice() {
|
let parsed = match parts.as_slice() {
|
||||||
[slug, "version", version_id, ..] => ImportInput::VersionId {
|
[slug, "version", version_id, ..] => ImportInput::VersionId {
|
||||||
slug: slug.to_string(),
|
slug: slug.to_string(),
|
||||||
version_id: version_id.to_string(),
|
version_id: version_id.to_string(),
|
||||||
@@ -49,8 +53,11 @@ pub fn parse_import_input(input: &str) -> ImportInput {
|
|||||||
[slug, ..] => ImportInput::ProjectSlug(slug.to_string()),
|
[slug, ..] => ImportInput::ProjectSlug(slug.to_string()),
|
||||||
[] => ImportInput::ProjectSlug(String::new()),
|
[] => ImportInput::ProjectSlug(String::new()),
|
||||||
};
|
};
|
||||||
|
tracing::debug!("Import input resolved as Modrinth URL: {:?}", parsed);
|
||||||
|
return parsed;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tracing::debug!("Import input resolved as Modrinth project slug: {}", input);
|
||||||
ImportInput::ProjectSlug(input.to_string())
|
ImportInput::ProjectSlug(input.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,40 +72,67 @@ pub struct ImportSummary {
|
|||||||
pub override_count: usize,
|
pub override_count: usize,
|
||||||
pub format: PackFormat,
|
pub format: PackFormat,
|
||||||
pub archive_path: PathBuf,
|
pub archive_path: PathBuf,
|
||||||
|
pub source: Option<crate::instance::ProviderProject>,
|
||||||
}
|
}
|
||||||
|
|
||||||
// peeks inside a zip to figure out what format it is.
|
// peeks inside a zip to figure out what format it is.
|
||||||
// checks for modrinth.index.json first, then mmc-pack.json.
|
// checks provider manifests first, then mmc-pack.json.
|
||||||
pub fn detect_format(path: &Path) -> Result<PackFormat, String> {
|
pub fn detect_format(path: &Path) -> Result<PackFormat, String> {
|
||||||
|
tracing::debug!("Detecting modpack format for {}", path.display());
|
||||||
let file =
|
let file =
|
||||||
std::fs::File::open(path).map_err(|e| format!("Cannot open '{}': {e}", path.display()))?;
|
std::fs::File::open(path).map_err(|e| format!("Cannot open '{}': {e}", path.display()))?;
|
||||||
let archive =
|
let archive =
|
||||||
zip::ZipArchive::new(file).map_err(|e| format!("Invalid ZIP '{}': {e}", path.display()))?;
|
zip::ZipArchive::new(file).map_err(|e| format!("Invalid ZIP '{}': {e}", path.display()))?;
|
||||||
|
|
||||||
if archive.file_names().any(|n| n == "modrinth.index.json") {
|
if archive.file_names().any(|n| n == "modrinth.index.json") {
|
||||||
|
tracing::debug!("Detected Modrinth .mrpack archive: {}", path.display());
|
||||||
return Ok(PackFormat::Mrpack);
|
return Ok(PackFormat::Mrpack);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if archive.file_names().any(|name| name == "manifest.json") {
|
||||||
|
tracing::debug!("Detected CurseForge archive: {}", path.display());
|
||||||
|
return Ok(PackFormat::CurseForge);
|
||||||
|
}
|
||||||
|
|
||||||
// mmc-pack.json can be at root or one directory deep
|
// mmc-pack.json can be at root or one directory deep
|
||||||
if archive
|
if archive
|
||||||
.file_names()
|
.file_names()
|
||||||
.any(|n| n == "mmc-pack.json" || n.ends_with("/mmc-pack.json"))
|
.any(|n| n == "mmc-pack.json" || n.ends_with("/mmc-pack.json"))
|
||||||
{
|
{
|
||||||
|
tracing::debug!("Detected MultiMC/Prism archive: {}", path.display());
|
||||||
return Ok(PackFormat::Mmc);
|
return Ok(PackFormat::Mmc);
|
||||||
}
|
}
|
||||||
|
|
||||||
Err("Unknown pack format: no modrinth.index.json or mmc-pack.json found".to_string())
|
tracing::warn!("Unknown modpack archive format: {}", path.display());
|
||||||
|
Err(
|
||||||
|
"Unknown pack format: no modrinth.index.json, manifest.json, or mmc-pack.json found"
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||||
if !path.exists() {
|
if !path.exists() {
|
||||||
|
tracing::warn!("Cannot import missing file {}", path.display());
|
||||||
return Err(format!("File not found: {}", path.display()));
|
return Err(format!("File not found: {}", path.display()));
|
||||||
}
|
}
|
||||||
let format = detect_format(path)?;
|
let format = detect_format(path)?;
|
||||||
match format {
|
let summary = match format {
|
||||||
|
PackFormat::CurseForge => curseforge::build_summary(path),
|
||||||
PackFormat::Mrpack => mrpack::build_summary(path),
|
PackFormat::Mrpack => mrpack::build_summary(path),
|
||||||
PackFormat::Mmc => mmc::build_summary(path),
|
PackFormat::Mmc => mmc::build_summary(path),
|
||||||
}
|
}?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Built import summary for {}: name='{}' format={:?} mc={} loader={} loader_version={:?} mods={} overrides={}",
|
||||||
|
path.display(),
|
||||||
|
summary.name,
|
||||||
|
summary.format,
|
||||||
|
summary.game_version,
|
||||||
|
summary.loader,
|
||||||
|
summary.loader_version,
|
||||||
|
summary.mod_count,
|
||||||
|
summary.override_count
|
||||||
|
);
|
||||||
|
Ok(summary)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
|
pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
|
||||||
@@ -108,6 +142,7 @@ pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
|
|||||||
.join("instance.json")
|
.join("instance.json")
|
||||||
.exists()
|
.exists()
|
||||||
{
|
{
|
||||||
|
tracing::trace!("Import instance name '{}' is available", candidate);
|
||||||
return candidate;
|
return candidate;
|
||||||
}
|
}
|
||||||
for n in 2..100 {
|
for n in 2..100 {
|
||||||
@@ -117,9 +152,18 @@ pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
|
|||||||
.join("instance.json")
|
.join("instance.json")
|
||||||
.exists()
|
.exists()
|
||||||
{
|
{
|
||||||
|
tracing::debug!(
|
||||||
|
"Import instance name '{}' collided; using '{}'",
|
||||||
|
base,
|
||||||
|
candidate
|
||||||
|
);
|
||||||
return candidate;
|
return candidate;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
tracing::warn!(
|
||||||
|
"Import instance name '{}' had many collisions; using fallback suffix",
|
||||||
|
base
|
||||||
|
);
|
||||||
format!("{base} (import)")
|
format!("{base} (import)")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,101 +171,112 @@ pub async fn execute_import(
|
|||||||
summary: &ImportSummary,
|
summary: &ImportSummary,
|
||||||
manager: &InstanceManager,
|
manager: &InstanceManager,
|
||||||
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
|
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
match summary.format {
|
tracing::info!(
|
||||||
|
"Executing {:?} import '{}' from {}",
|
||||||
|
summary.format,
|
||||||
|
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::Mrpack => mrpack::execute_import(summary, manager).await,
|
||||||
PackFormat::Mmc => mmc::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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(config)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn provider_versions(
|
||||||
|
source: &crate::instance::ProviderProject,
|
||||||
|
) -> Result<Vec<crate::net::modrinth::VersionInfo>, crate::net::NetError> {
|
||||||
|
let client = crate::net::HttpClient::new();
|
||||||
|
match source.provider.as_str() {
|
||||||
|
"curseforge" => {
|
||||||
|
let api_key = crate::net::curseforge::api_key().ok_or_else(|| {
|
||||||
|
crate::net::NetError::Parse("CurseForge API key is not configured".to_owned())
|
||||||
|
})?;
|
||||||
|
crate::net::curseforge::fetch_versions(&client, api_key, &source.project_id, "", None)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
"modrinth" => crate::net::modrinth::fetch_versions(&client, &source.project_id).await,
|
||||||
|
provider => Err(crate::net::NetError::Parse(format!(
|
||||||
|
"Unsupported modpack provider '{provider}'"
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn download_provider_summary(
|
||||||
|
source: &crate::instance::ProviderProject,
|
||||||
|
version: &crate::net::modrinth::VersionInfo,
|
||||||
|
temporary_dir: &Path,
|
||||||
|
) -> Result<ImportSummary, crate::net::NetError> {
|
||||||
|
tokio::fs::create_dir_all(temporary_dir).await?;
|
||||||
|
let registry = crate::instance::content::provider::ProviderRegistry::configured(
|
||||||
|
crate::net::HttpClient::new(),
|
||||||
|
);
|
||||||
|
let provider = registry.get(&source.provider).ok_or_else(|| {
|
||||||
|
crate::net::NetError::Parse(format!(
|
||||||
|
"{} content provider is unavailable",
|
||||||
|
source.provider
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
let archive = match provider
|
||||||
|
.download_version(version, temporary_dir, None)
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
crate::net::modrinth::DownloadOutcome::Downloaded(path)
|
||||||
|
| crate::net::modrinth::DownloadOutcome::SkippedExisting(path) => path,
|
||||||
|
};
|
||||||
|
let mut summary = build_summary(&archive).map_err(crate::net::NetError::Parse)?;
|
||||||
|
summary.source = Some(crate::instance::ProviderProject {
|
||||||
|
provider: source.provider.clone(),
|
||||||
|
project_id: source.project_id.clone(),
|
||||||
|
version_id: version.id.clone(),
|
||||||
|
});
|
||||||
|
Ok(summary)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn owned_files(summary: &ImportSummary) -> Result<Vec<PathBuf>, String> {
|
||||||
|
match summary.format {
|
||||||
|
PackFormat::Mrpack => mrpack::owned_files(&summary.archive_path),
|
||||||
|
PackFormat::CurseForge => curseforge::owned_files(&summary.archive_path).await,
|
||||||
|
PackFormat::Mmc => Err("Managed updates are unavailable for MultiMC packs".to_owned()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cleanup_failed_import(manager: &InstanceManager, name: &str) {
|
||||||
|
crate::feedback::progress::clear();
|
||||||
|
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
|
||||||
|
{
|
||||||
|
tracing::warn!(
|
||||||
|
"Failed to clean up incomplete imported instance {}: {}",
|
||||||
|
instance_dir.display(),
|
||||||
|
error
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "../tests/import/format_detection.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn unique_name_no_collision() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let name = unique_instance_name("TestPack", tmp.path());
|
|
||||||
assert_eq!(name, "TestPack");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn unique_name_with_collision() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = tmp.path().join("TestPack");
|
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
|
||||||
std::fs::write(dir.join("instance.json"), "{}").unwrap();
|
|
||||||
let name = unique_instance_name("TestPack", tmp.path());
|
|
||||||
assert_eq!(name, "TestPack (2)");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn unique_name_multiple_collisions() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
for suffix in ["", " (2)", " (3)"] {
|
|
||||||
let dir = tmp.path().join(format!("TestPack{suffix}"));
|
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
|
||||||
std::fs::write(dir.join("instance.json"), "{}").unwrap();
|
|
||||||
}
|
|
||||||
let name = unique_instance_name("TestPack", tmp.path());
|
|
||||||
assert_eq!(name, "TestPack (4)");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parse_project_url() {
|
|
||||||
assert_eq!(
|
|
||||||
parse_import_input("https://modrinth.com/modpack/fabulously-optimized"),
|
|
||||||
ImportInput::ProjectSlug("fabulously-optimized".to_string())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parse_version_url() {
|
|
||||||
assert_eq!(
|
|
||||||
parse_import_input("https://modrinth.com/modpack/fabulously-optimized/version/abc123"),
|
|
||||||
ImportInput::VersionId {
|
|
||||||
slug: "fabulously-optimized".to_string(),
|
|
||||||
version_id: "abc123".to_string(),
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parse_local_mrpack() {
|
|
||||||
assert_eq!(
|
|
||||||
parse_import_input("/home/user/pack.mrpack"),
|
|
||||||
ImportInput::LocalFile("/home/user/pack.mrpack".to_string())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parse_local_zip() {
|
|
||||||
assert_eq!(
|
|
||||||
parse_import_input("GT_New_Horizons.zip"),
|
|
||||||
ImportInput::LocalFile("GT_New_Horizons.zip".to_string())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parse_tilde_path() {
|
|
||||||
assert_eq!(
|
|
||||||
parse_import_input("~/Downloads/pack.mrpack"),
|
|
||||||
ImportInput::LocalFile("~/Downloads/pack.mrpack".to_string())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parse_bare_slug() {
|
|
||||||
assert_eq!(
|
|
||||||
parse_import_input("fabulously-optimized"),
|
|
||||||
ImportInput::ProjectSlug("fabulously-optimized".to_string())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parse_input_trims_whitespace() {
|
|
||||||
assert_eq!(
|
|
||||||
parse_import_input(" fabulously-optimized "),
|
|
||||||
ImportInput::ProjectSlug("fabulously-optimized".to_string())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+332
-26
@@ -1,26 +1,119 @@
|
|||||||
// modrinth .mrpack import: parse the manifest, download all the mods,
|
// modrinth .mrpack import: parse the manifest, download all the mods,
|
||||||
// and extract config/resource overrides from the zip
|
// and extract config/resource overrides from the zip
|
||||||
|
|
||||||
use std::path::Path;
|
use std::collections::HashMap;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use crate::feedback::progress;
|
||||||
|
use crate::instance::content::manifest::{
|
||||||
|
ContentFileRecord, ContentKind, ContentManifest, ProviderProject, Resolution, fingerprint,
|
||||||
|
};
|
||||||
use crate::instance::manager::InstanceManager;
|
use crate::instance::manager::InstanceManager;
|
||||||
use crate::instance::models::ModLoader;
|
use crate::instance::models::ModLoader;
|
||||||
use crate::net::modrinth::MrpackIndex;
|
use crate::storage::InstancePaths;
|
||||||
use crate::tui::progress;
|
|
||||||
|
|
||||||
use super::{ImportSummary, PackFormat};
|
use super::{ImportSummary, PackFormat};
|
||||||
|
|
||||||
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
let index = crate::net::modrinth::parse_mrpack(path)?;
|
pub struct MrpackIndex {
|
||||||
|
#[serde(rename = "formatVersion")]
|
||||||
|
pub format_version: u32,
|
||||||
|
pub game: String,
|
||||||
|
#[serde(rename = "versionId")]
|
||||||
|
pub version_id: String,
|
||||||
|
pub name: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub dependencies: HashMap<String, String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub files: Vec<MrpackFile>,
|
||||||
|
}
|
||||||
|
|
||||||
let game_version = crate::net::modrinth::game_version_from_dependencies(&index.dependencies)
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct MrpackFile {
|
||||||
|
pub path: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub hashes: 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
|
||||||
|
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}"))?;
|
||||||
|
let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("Invalid ZIP: {e}"))?;
|
||||||
|
let entry = archive
|
||||||
|
.by_name("modrinth.index.json")
|
||||||
|
.map_err(|_| "Missing modrinth.index.json in .mrpack".to_string())?;
|
||||||
|
let index: MrpackIndex =
|
||||||
|
serde_json::from_reader(entry).map_err(|e| format!("Invalid manifest JSON: {e}"))?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Parsed .mrpack '{}' version_id={} files={} deps={}",
|
||||||
|
index.name,
|
||||||
|
index.version_id,
|
||||||
|
index.files.len(),
|
||||||
|
index.dependencies.len()
|
||||||
|
);
|
||||||
|
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>) {
|
||||||
|
let loaders = [
|
||||||
|
("fabric-loader", ModLoader::Fabric),
|
||||||
|
("forge", ModLoader::Forge),
|
||||||
|
("neoforge", ModLoader::NeoForge),
|
||||||
|
("quilt-loader", ModLoader::Quilt),
|
||||||
|
];
|
||||||
|
for (key, loader) in &loaders {
|
||||||
|
if let Some(version) = deps.get(*key) {
|
||||||
|
tracing::trace!(
|
||||||
|
"Resolved Modrinth loader dependency {}={} as {}",
|
||||||
|
key,
|
||||||
|
version,
|
||||||
|
loader
|
||||||
|
);
|
||||||
|
return (Some(*loader), Some(version.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tracing::trace!("No Modrinth loader dependency found; treating pack as vanilla");
|
||||||
|
(None, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn game_version_from_dependencies(deps: &HashMap<String, String>) -> Option<String> {
|
||||||
|
deps.get("minecraft").cloned()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||||
|
let index = parse_mrpack(path)?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Parsed .mrpack '{}' version_id={} files={} deps={}",
|
||||||
|
index.name,
|
||||||
|
index.version_id,
|
||||||
|
index.files.len(),
|
||||||
|
index.dependencies.len()
|
||||||
|
);
|
||||||
|
|
||||||
|
let game_version = game_version_from_dependencies(&index.dependencies)
|
||||||
.ok_or_else(|| "Manifest missing minecraft dependency".to_string())?;
|
.ok_or_else(|| "Manifest missing minecraft dependency".to_string())?;
|
||||||
|
|
||||||
let (loader_opt, loader_version) =
|
let (loader_opt, loader_version) = loader_from_dependencies(&index.dependencies);
|
||||||
crate::net::modrinth::loader_from_dependencies(&index.dependencies);
|
|
||||||
let loader = loader_opt.unwrap_or(ModLoader::Vanilla);
|
let loader = loader_opt.unwrap_or(ModLoader::Vanilla);
|
||||||
|
|
||||||
let override_count = count_overrides(path).unwrap_or(0);
|
let override_count = count_overrides(path).unwrap_or(0);
|
||||||
|
tracing::trace!(
|
||||||
|
".mrpack summary: game_version={} loader={:?} loader_version={:?} overrides={}",
|
||||||
|
game_version,
|
||||||
|
loader,
|
||||||
|
loader_version,
|
||||||
|
override_count
|
||||||
|
);
|
||||||
|
|
||||||
Ok(ImportSummary {
|
Ok(ImportSummary {
|
||||||
name: index.name.clone(),
|
name: index.name.clone(),
|
||||||
@@ -32,6 +125,7 @@ pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
|||||||
override_count,
|
override_count,
|
||||||
format: PackFormat::Mrpack,
|
format: PackFormat::Mrpack,
|
||||||
archive_path: path.to_path_buf(),
|
archive_path: path.to_path_buf(),
|
||||||
|
source: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,6 +148,11 @@ pub async fn execute_import(
|
|||||||
manager: &InstanceManager,
|
manager: &InstanceManager,
|
||||||
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
|
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
let name = super::unique_instance_name(&summary.name, &manager.instances_dir);
|
let name = super::unique_instance_name(&summary.name, &manager.instances_dir);
|
||||||
|
tracing::info!(
|
||||||
|
"Importing Modrinth pack '{}' as instance '{}'",
|
||||||
|
summary.name,
|
||||||
|
name
|
||||||
|
);
|
||||||
|
|
||||||
progress::set_action(format!("Importing '{name}'..."));
|
progress::set_action(format!("Importing '{name}'..."));
|
||||||
progress::set_sub_action(format!("{} {}", summary.game_version, summary.loader));
|
progress::set_sub_action(format!("{} {}", summary.game_version, summary.loader));
|
||||||
@@ -68,16 +167,30 @@ pub async fn execute_import(
|
|||||||
.await
|
.await
|
||||||
.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) })?;
|
||||||
|
|
||||||
let minecraft_dir = manager.instances_dir.join(&name).join(".minecraft");
|
let minecraft_dir = manager
|
||||||
|
.instances_dir
|
||||||
|
.join(&name)
|
||||||
|
.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||||
|
|
||||||
let index = crate::net::modrinth::parse_mrpack(&summary.archive_path)
|
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() })?;
|
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { e.into() })?;
|
||||||
|
|
||||||
download_mod_files(&index, &minecraft_dir).await?;
|
download_mod_files(&index, &minecraft_dir).await?;
|
||||||
|
|
||||||
extract_overrides(&summary.archive_path, &minecraft_dir)?;
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
progress::clear();
|
progress::clear();
|
||||||
|
tracing::info!("Imported Modrinth pack '{}' as '{}'", summary.name, name);
|
||||||
Ok(config)
|
Ok(config)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,6 +206,12 @@ async fn download_mod_files(
|
|||||||
let client = crate::net::HttpClient::new();
|
let client = crate::net::HttpClient::new();
|
||||||
let total = index.files.len();
|
let total = index.files.len();
|
||||||
let completed = Arc::new(AtomicUsize::new(0));
|
let completed = Arc::new(AtomicUsize::new(0));
|
||||||
|
tracing::debug!(
|
||||||
|
"Downloading {} file(s) from .mrpack '{}' into {}",
|
||||||
|
total,
|
||||||
|
index.name,
|
||||||
|
minecraft_dir.display()
|
||||||
|
);
|
||||||
|
|
||||||
progress::set_action(format!("Downloading mods... 0/{total}"));
|
progress::set_action(format!("Downloading mods... 0/{total}"));
|
||||||
|
|
||||||
@@ -105,21 +224,39 @@ async fn download_mod_files(
|
|||||||
for _ in 0..max_concurrent {
|
for _ in 0..max_concurrent {
|
||||||
if let Some(file) = file_iter.next() {
|
if let Some(file) = file_iter.next() {
|
||||||
let client = client.clone();
|
let client = client.clone();
|
||||||
let dest = minecraft_dir.join(&file.path);
|
let relative = safe_mrpack_path(&file.path)?;
|
||||||
let url = file.downloads.first().cloned().unwrap_or_default();
|
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
|
let filename = file
|
||||||
.path
|
.path
|
||||||
.rsplit('/')
|
.rsplit('/')
|
||||||
.next()
|
.next()
|
||||||
.unwrap_or(&file.path)
|
.unwrap_or(&file.path)
|
||||||
.to_string();
|
.to_string();
|
||||||
|
let hashes = file.hashes.clone();
|
||||||
|
let file_size = file.file_size;
|
||||||
let completed = completed.clone();
|
let completed = completed.clone();
|
||||||
tasks.spawn(async move {
|
tasks.spawn(async move {
|
||||||
if let Some(parent) = dest.parent() {
|
if let Some(parent) = dest.parent()
|
||||||
let _ = tokio::fs::create_dir_all(parent).await;
|
&& let Err(error) = tokio::fs::create_dir_all(parent).await
|
||||||
|
{
|
||||||
|
return Err(crate::net::NetError::from(error));
|
||||||
}
|
}
|
||||||
progress::set_sub_action(filename);
|
progress::set_sub_action(filename);
|
||||||
|
tracing::trace!("Downloading .mrpack file to {}", dest.display());
|
||||||
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
|
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;
|
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
|
||||||
progress::set_action(format!("Downloading mods... {done}/{total}"));
|
progress::set_action(format!("Downloading mods... {done}/{total}"));
|
||||||
Ok::<(), crate::net::NetError>(())
|
Ok::<(), crate::net::NetError>(())
|
||||||
@@ -134,21 +271,36 @@ async fn download_mod_files(
|
|||||||
.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) })?;
|
||||||
}
|
}
|
||||||
let client = client.clone();
|
let client = client.clone();
|
||||||
let dest = minecraft_dir.join(&file.path);
|
let relative = safe_mrpack_path(&file.path)?;
|
||||||
let url = file.downloads.first().cloned().unwrap_or_default();
|
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
|
let filename = file
|
||||||
.path
|
.path
|
||||||
.rsplit('/')
|
.rsplit('/')
|
||||||
.next()
|
.next()
|
||||||
.unwrap_or(&file.path)
|
.unwrap_or(&file.path)
|
||||||
.to_string();
|
.to_string();
|
||||||
|
let hashes = file.hashes.clone();
|
||||||
|
let file_size = file.file_size;
|
||||||
let completed = completed.clone();
|
let completed = completed.clone();
|
||||||
tasks.spawn(async move {
|
tasks.spawn(async move {
|
||||||
if let Some(parent) = dest.parent() {
|
if let Some(parent) = dest.parent()
|
||||||
let _ = tokio::fs::create_dir_all(parent).await;
|
&& let Err(error) = tokio::fs::create_dir_all(parent).await
|
||||||
|
{
|
||||||
|
return Err(crate::net::NetError::from(error));
|
||||||
}
|
}
|
||||||
progress::set_sub_action(filename);
|
progress::set_sub_action(filename);
|
||||||
|
tracing::trace!("Downloading .mrpack file to {}", dest.display());
|
||||||
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
|
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;
|
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
|
||||||
progress::set_action(format!("Downloading mods... {done}/{total}"));
|
progress::set_action(format!("Downloading mods... {done}/{total}"));
|
||||||
Ok::<(), crate::net::NetError>(())
|
Ok::<(), crate::net::NetError>(())
|
||||||
@@ -164,6 +316,128 @@ async fn download_mod_files(
|
|||||||
Ok(())
|
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())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn owned_files(path: &Path) -> Result<Vec<PathBuf>, String> {
|
||||||
|
parse_mrpack(path)?
|
||||||
|
.files
|
||||||
|
.into_iter()
|
||||||
|
.map(|file| safe_mrpack_path(&file.path).map_err(|error| error.to_string()))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_mrpack_file(
|
||||||
|
path: &Path,
|
||||||
|
expected_size: u64,
|
||||||
|
expected_hashes: &HashMap<String, String>,
|
||||||
|
) -> Result<bool, crate::net::NetError> {
|
||||||
|
let fingerprint = fingerprint(path)?;
|
||||||
|
if fingerprint.size != expected_size {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
Ok(["sha512", "sha1"].into_iter().all(|algorithm| {
|
||||||
|
expected_hashes.get(algorithm).is_none_or(|expected| {
|
||||||
|
fingerprint
|
||||||
|
.hash(algorithm)
|
||||||
|
.is_some_and(|actual| actual.eq_ignore_ascii_case(expected))
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn seed_content_manifest(
|
||||||
|
index: &MrpackIndex,
|
||||||
|
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 {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some((project_id, version_id)) = file.downloads.iter().find_map(|url| {
|
||||||
|
let path = url.strip_prefix("https://cdn.modrinth.com/data/")?;
|
||||||
|
let (project_id, path) = path.split_once("/versions/")?;
|
||||||
|
let version_id = path.split('/').next()?;
|
||||||
|
(!project_id.is_empty() && !version_id.is_empty())
|
||||||
|
.then_some((project_id.to_owned(), version_id.to_owned()))
|
||||||
|
}) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(expected_sha512) = file.hashes.get("sha512") else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
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))
|
||||||
|
{
|
||||||
|
tracing::warn!(
|
||||||
|
"Skipping stale Modrinth identity for '{}' because its downloaded hash changed",
|
||||||
|
file.path
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
manifest.upsert(ContentFileRecord {
|
||||||
|
relative_path: relative_path.to_owned(),
|
||||||
|
kind,
|
||||||
|
enabled: true,
|
||||||
|
fingerprint: file_fingerprint,
|
||||||
|
resolution: Resolution::Resolved {
|
||||||
|
project: ProviderProject {
|
||||||
|
provider: "modrinth".to_owned(),
|
||||||
|
project_id,
|
||||||
|
version_id,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
provider_aliases: Vec::new(),
|
||||||
|
provider_checks: vec!["modrinth".to_owned()],
|
||||||
|
required_dependencies: Vec::new(),
|
||||||
|
automatic_dependency: false,
|
||||||
|
cleanup_eligible: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let seeded = manifest.files.len();
|
||||||
|
manifest.save(&paths.content_manifest())?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Seeded {} exact Modrinth content record(s) from .mrpack '{}'",
|
||||||
|
seeded,
|
||||||
|
index.name
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mrpack_content_kind(path: &Path) -> Option<ContentKind> {
|
||||||
|
use std::path::Component;
|
||||||
|
|
||||||
|
if path
|
||||||
|
.components()
|
||||||
|
.any(|component| !matches!(component, Component::Normal(_)))
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let directory = path.components().next()?.as_os_str().to_str()?;
|
||||||
|
let name = path.file_name()?.to_str()?.to_ascii_lowercase();
|
||||||
|
match (directory, name.as_str()) {
|
||||||
|
("mods", name) if name.ends_with(".jar") => Some(ContentKind::Mod),
|
||||||
|
("resourcepacks", name) if name.ends_with(".zip") => Some(ContentKind::ResourcePack),
|
||||||
|
("shaderpacks", name) if name.ends_with(".zip") => Some(ContentKind::Shader),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn extract_overrides(
|
fn extract_overrides(
|
||||||
mrpack_path: &Path,
|
mrpack_path: &Path,
|
||||||
minecraft_dir: &Path,
|
minecraft_dir: &Path,
|
||||||
@@ -175,22 +449,37 @@ fn extract_overrides(
|
|||||||
|
|
||||||
let file = std::fs::File::open(mrpack_path)?;
|
let file = std::fs::File::open(mrpack_path)?;
|
||||||
let mut archive = zip::ZipArchive::new(file)?;
|
let mut archive = zip::ZipArchive::new(file)?;
|
||||||
|
let mut extracted = 0usize;
|
||||||
|
let mut dirs = 0usize;
|
||||||
|
|
||||||
for i in 0..archive.len() {
|
for i in 0..archive.len() {
|
||||||
let mut entry = archive.by_index(i)?;
|
let mut entry = archive.by_index(i)?;
|
||||||
let entry_name = entry.name().to_string();
|
let entry_name = entry.name().to_string();
|
||||||
|
|
||||||
let relative = entry_name
|
let root = if entry_name.starts_with("overrides/") {
|
||||||
.strip_prefix("overrides/")
|
"overrides"
|
||||||
.or_else(|| entry_name.strip_prefix("client-overrides/"));
|
} else if entry_name.starts_with("client-overrides/") {
|
||||||
|
"client-overrides"
|
||||||
let Some(relative) = relative else {
|
} else {
|
||||||
continue;
|
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.is_empty() || entry_name.ends_with('/') {
|
if relative.as_os_str().is_empty() || entry_name.ends_with('/') {
|
||||||
let dir = minecraft_dir.join(relative);
|
let dir = minecraft_dir.join(relative);
|
||||||
std::fs::create_dir_all(dir)?;
|
std::fs::create_dir_all(dir)?;
|
||||||
|
dirs += 1;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -201,8 +490,25 @@ fn extract_overrides(
|
|||||||
|
|
||||||
let mut buf = Vec::new();
|
let mut buf = Vec::new();
|
||||||
entry.read_to_end(&mut buf)?;
|
entry.read_to_end(&mut buf)?;
|
||||||
|
tracing::trace!(
|
||||||
|
"Extracting .mrpack override {} to {} ({} bytes)",
|
||||||
|
entry_name,
|
||||||
|
dest.display(),
|
||||||
|
buf.len()
|
||||||
|
);
|
||||||
std::fs::write(&dest, &buf)?;
|
std::fs::write(&dest, &buf)?;
|
||||||
|
extracted += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tracing::debug!(
|
||||||
|
"Extracted {} override files and {} directories from {}",
|
||||||
|
extracted,
|
||||||
|
dirs,
|
||||||
|
mrpack_path.display()
|
||||||
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/import/mrpack.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,393 @@
|
|||||||
|
use std::collections::HashSet;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::instance::{InstanceConfig, InstanceManager, ProviderProject};
|
||||||
|
use crate::net::modrinth::VersionInfo;
|
||||||
|
use crate::storage::InstancePaths;
|
||||||
|
|
||||||
|
use super::ImportSummary;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct PackState {
|
||||||
|
pub source: ProviderProject,
|
||||||
|
pub files: Vec<PathBuf>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PackState {
|
||||||
|
pub fn load(paths: &InstancePaths) -> Option<Self> {
|
||||||
|
std::fs::read(paths.modpack_state())
|
||||||
|
.ok()
|
||||||
|
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save(&self, paths: &InstancePaths) -> Result<(), String> {
|
||||||
|
let bytes = serde_json::to_vec_pretty(self).map_err(|error| error.to_string())?;
|
||||||
|
crate::storage::write_atomic(&paths.modpack_state(), &bytes)
|
||||||
|
.map_err(|error| error.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct RefreshPlan {
|
||||||
|
pub instance: InstanceConfig,
|
||||||
|
pub summary: ImportSummary,
|
||||||
|
pub current_version: String,
|
||||||
|
pub target_version: String,
|
||||||
|
pub conflicts: Vec<PathBuf>,
|
||||||
|
stage_root: PathBuf,
|
||||||
|
staged_instance: PathBuf,
|
||||||
|
old_owned: HashSet<PathBuf>,
|
||||||
|
new_owned: HashSet<PathBuf>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for RefreshPlan {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = std::fs::remove_dir_all(&self.stage_root);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn prepare(
|
||||||
|
manager: &InstanceManager,
|
||||||
|
instance: &InstanceConfig,
|
||||||
|
target: VersionInfo,
|
||||||
|
) -> Result<RefreshPlan, String> {
|
||||||
|
if crate::instance::runtime::get(&instance.name)
|
||||||
|
.is_some_and(|state| !matches!(state, crate::instance::runtime::RunState::Crashed(_)))
|
||||||
|
{
|
||||||
|
return Err("Stop the instance before changing its modpack".to_owned());
|
||||||
|
}
|
||||||
|
let source = instance
|
||||||
|
.modpack_source
|
||||||
|
.clone()
|
||||||
|
.ok_or_else(|| "This instance is not linked to a modpack provider".to_owned())?;
|
||||||
|
let registry = crate::instance::content::provider::ProviderRegistry::configured(
|
||||||
|
crate::net::HttpClient::new(),
|
||||||
|
);
|
||||||
|
let provider = registry
|
||||||
|
.get(&source.provider)
|
||||||
|
.ok_or_else(|| format!("{} content provider is unavailable", source.provider))?;
|
||||||
|
let current = provider
|
||||||
|
.version(&source.version_id)
|
||||||
|
.await
|
||||||
|
.map_err(|error| error.to_string())?;
|
||||||
|
let live = manager.instances_dir.join(&instance.name);
|
||||||
|
let needed = directory_size(&live)
|
||||||
|
.saturating_add(target.files.iter().map(|file| file.size).sum::<u64>())
|
||||||
|
.saturating_add(64 * 1024 * 1024);
|
||||||
|
let available = fs2::available_space(&manager.instances_dir).map_err(|e| e.to_string())?;
|
||||||
|
if available < needed {
|
||||||
|
return Err(format!(
|
||||||
|
"Not enough free space to stage this modpack change (need about {}, available {})",
|
||||||
|
format_bytes(needed),
|
||||||
|
format_bytes(available)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let nonce = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.map_err(|error| error.to_string())?
|
||||||
|
.as_nanos();
|
||||||
|
let stage_root = manager.instances_dir.join(format!(".rmcl-refresh-{nonce}"));
|
||||||
|
let archives = stage_root.join("archives");
|
||||||
|
let result = async {
|
||||||
|
let summary = super::download_provider_summary(&source, &target, &archives.join("target"))
|
||||||
|
.await
|
||||||
|
.map_err(|error| error.to_string())?;
|
||||||
|
let old_owned = match PackState::load(&InstancePaths::new(&live))
|
||||||
|
.filter(|state| state.source == source)
|
||||||
|
{
|
||||||
|
Some(state) => state.files.into_iter().collect(),
|
||||||
|
None => reconstruct_owned_files(&source, ¤t, &archives.join("current")).await?,
|
||||||
|
};
|
||||||
|
|
||||||
|
let staging_manager = InstanceManager::new(&stage_root, &manager.meta_dir);
|
||||||
|
let staged_config = super::execute_import(&summary, &staging_manager)
|
||||||
|
.await
|
||||||
|
.map_err(|error| error.to_string())?;
|
||||||
|
let imported = stage_root.join(&staged_config.name);
|
||||||
|
let new_owned = PackState::load(&InstancePaths::new(&imported))
|
||||||
|
.ok_or_else(|| "The staged pack did not record its owned files".to_owned())?
|
||||||
|
.files
|
||||||
|
.into_iter()
|
||||||
|
.collect::<HashSet<_>>();
|
||||||
|
let staged_instance = stage_root.join(&instance.name);
|
||||||
|
if imported != staged_instance {
|
||||||
|
std::fs::rename(&imported, &staged_instance).map_err(|error| error.to_string())?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut config = instance.clone();
|
||||||
|
config.game_version = summary.game_version.clone();
|
||||||
|
config.loader = summary.loader;
|
||||||
|
config.loader_version = summary.loader_version.clone();
|
||||||
|
config.modpack_source = summary.source.clone();
|
||||||
|
let staged_manager = InstanceManager::new(&stage_root, &manager.meta_dir);
|
||||||
|
staged_manager
|
||||||
|
.save(&config)
|
||||||
|
.map_err(|error| error.to_string())?;
|
||||||
|
|
||||||
|
let conflicts = user_file_collisions(
|
||||||
|
&InstancePaths::new(&live).minecraft(),
|
||||||
|
&old_owned,
|
||||||
|
&new_owned,
|
||||||
|
)?;
|
||||||
|
Ok::<_, String>(RefreshPlan {
|
||||||
|
instance: config,
|
||||||
|
current_version: current.version_number,
|
||||||
|
target_version: target.version_number.clone(),
|
||||||
|
summary,
|
||||||
|
conflicts,
|
||||||
|
stage_root: stage_root.clone(),
|
||||||
|
staged_instance,
|
||||||
|
old_owned,
|
||||||
|
new_owned,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
if result.is_err() {
|
||||||
|
let _ = std::fs::remove_dir_all(&stage_root);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn apply(
|
||||||
|
plan: RefreshPlan,
|
||||||
|
replace_conflicts: &HashSet<PathBuf>,
|
||||||
|
) -> Result<InstanceConfig, String> {
|
||||||
|
let live = plan
|
||||||
|
.stage_root
|
||||||
|
.parent()
|
||||||
|
.ok_or_else(|| "Invalid refresh staging path".to_owned())?
|
||||||
|
.join(&plan.instance.name);
|
||||||
|
let old_minecraft = InstancePaths::new(&live).minecraft();
|
||||||
|
let staged_minecraft = InstancePaths::new(&plan.staged_instance).minecraft();
|
||||||
|
preserve_user_files(
|
||||||
|
&old_minecraft,
|
||||||
|
&staged_minecraft,
|
||||||
|
&old_minecraft,
|
||||||
|
&plan.old_owned,
|
||||||
|
&plan.new_owned,
|
||||||
|
replace_conflicts,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
let backup = live.with_file_name(format!(".{}.rmcl-backup", plan.instance.name));
|
||||||
|
if backup.exists() {
|
||||||
|
return Err(format!(
|
||||||
|
"A previous update backup still exists at '{}'",
|
||||||
|
backup.display()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
std::fs::rename(&live, &backup).map_err(|error| error.to_string())?;
|
||||||
|
if let Err(error) = std::fs::rename(&plan.staged_instance, &live) {
|
||||||
|
let _ = std::fs::rename(&backup, &live);
|
||||||
|
return Err(format!("Could not activate the staged update: {error}"));
|
||||||
|
}
|
||||||
|
if let Err(error) = std::fs::remove_dir_all(&backup) {
|
||||||
|
tracing::warn!("Could not remove successful modpack update backup: {error}");
|
||||||
|
}
|
||||||
|
Ok(plan.instance.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn reconstruct_owned_files(
|
||||||
|
source: &ProviderProject,
|
||||||
|
version: &VersionInfo,
|
||||||
|
temporary_dir: &Path,
|
||||||
|
) -> Result<HashSet<PathBuf>, String> {
|
||||||
|
let summary = super::download_provider_summary(source, version, temporary_dir)
|
||||||
|
.await
|
||||||
|
.map_err(|error| error.to_string())?;
|
||||||
|
Ok(super::owned_files(&summary).await?.into_iter().collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn recover_interrupted(instances_dir: &Path) {
|
||||||
|
let Ok(entries) = std::fs::read_dir(instances_dir) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let path = entry.path();
|
||||||
|
let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if name.starts_with(".rmcl-refresh-") {
|
||||||
|
let _ = std::fs::remove_dir_all(path);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(instance_name) = name
|
||||||
|
.strip_prefix('.')
|
||||||
|
.and_then(|name| name.strip_suffix(".rmcl-backup"))
|
||||||
|
else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let live = instances_dir.join(instance_name);
|
||||||
|
if live.join("instance.json").is_file() {
|
||||||
|
let _ = std::fs::remove_dir_all(path);
|
||||||
|
} else if let Err(error) = std::fs::rename(&path, &live) {
|
||||||
|
tracing::warn!(
|
||||||
|
"Could not restore interrupted modpack update backup '{}': {error}",
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn user_file_collisions(
|
||||||
|
minecraft: &Path,
|
||||||
|
old_owned: &HashSet<PathBuf>,
|
||||||
|
new_owned: &HashSet<PathBuf>,
|
||||||
|
) -> Result<Vec<PathBuf>, String> {
|
||||||
|
let mut collisions = Vec::new();
|
||||||
|
collect_files(minecraft, minecraft, &mut |relative, _| {
|
||||||
|
if !old_owned.contains(relative) && new_owned.contains(relative) {
|
||||||
|
collisions.push(relative.to_owned());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})?;
|
||||||
|
collisions.sort();
|
||||||
|
Ok(collisions)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn preserve_user_files(
|
||||||
|
source: &Path,
|
||||||
|
destination: &Path,
|
||||||
|
root: &Path,
|
||||||
|
old_owned: &HashSet<PathBuf>,
|
||||||
|
new_owned: &HashSet<PathBuf>,
|
||||||
|
replace_conflicts: &HashSet<PathBuf>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
for entry in std::fs::read_dir(source).map_err(|error| error.to_string())? {
|
||||||
|
let entry = entry.map_err(|error| error.to_string())?;
|
||||||
|
let path = entry.path();
|
||||||
|
let relative = path.strip_prefix(root).map_err(|error| error.to_string())?;
|
||||||
|
let metadata = std::fs::symlink_metadata(&path).map_err(|error| error.to_string())?;
|
||||||
|
if metadata.file_type().is_symlink() {
|
||||||
|
return Err(format!(
|
||||||
|
"Cannot safely preserve symbolic link '{}'",
|
||||||
|
path.display()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if metadata.is_dir() {
|
||||||
|
let target = destination.join(entry.file_name());
|
||||||
|
std::fs::create_dir_all(&target).map_err(|error| error.to_string())?;
|
||||||
|
preserve_user_files(
|
||||||
|
&path,
|
||||||
|
&target,
|
||||||
|
root,
|
||||||
|
old_owned,
|
||||||
|
new_owned,
|
||||||
|
replace_conflicts,
|
||||||
|
)?;
|
||||||
|
} else if !(old_owned.contains(relative)
|
||||||
|
|| new_owned.contains(relative) && replace_conflicts.contains(relative))
|
||||||
|
{
|
||||||
|
let target = destination.join(entry.file_name());
|
||||||
|
std::fs::copy(&path, target).map_err(|error| error.to_string())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collect_files(
|
||||||
|
directory: &Path,
|
||||||
|
root: &Path,
|
||||||
|
visit: &mut impl FnMut(&Path, &Path) -> Result<(), String>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
if !directory.exists() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
for entry in std::fs::read_dir(directory).map_err(|error| error.to_string())? {
|
||||||
|
let entry = entry.map_err(|error| error.to_string())?;
|
||||||
|
let path = entry.path();
|
||||||
|
let metadata = std::fs::symlink_metadata(&path).map_err(|error| error.to_string())?;
|
||||||
|
if metadata.is_dir() {
|
||||||
|
collect_files(&path, root, visit)?;
|
||||||
|
} else if metadata.is_file() {
|
||||||
|
visit(
|
||||||
|
path.strip_prefix(root).map_err(|error| error.to_string())?,
|
||||||
|
&path,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn directory_size(path: &Path) -> u64 {
|
||||||
|
let mut size = 0;
|
||||||
|
let _ = collect_files(path, path, &mut |_, file| {
|
||||||
|
size += file.metadata().map(|metadata| metadata.len()).unwrap_or(0);
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
size
|
||||||
|
}
|
||||||
|
|
||||||
|
fn format_bytes(bytes: u64) -> String {
|
||||||
|
if bytes >= 1024 * 1024 * 1024 {
|
||||||
|
format!("{:.1} GB", bytes as f64 / (1024 * 1024 * 1024) as f64)
|
||||||
|
} else {
|
||||||
|
format!("{:.1} MB", bytes as f64 / (1024 * 1024) as f64)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn preservation_replaces_pack_files_and_keeps_user_files() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let old = temp.path().join("old");
|
||||||
|
let new = temp.path().join("new");
|
||||||
|
std::fs::create_dir_all(old.join("mods")).unwrap();
|
||||||
|
std::fs::create_dir_all(new.join("mods")).unwrap();
|
||||||
|
std::fs::write(old.join("mods/pack.jar"), "old").unwrap();
|
||||||
|
std::fs::write(old.join("mods/user.jar"), "user").unwrap();
|
||||||
|
std::fs::write(new.join("mods/pack.jar"), "new").unwrap();
|
||||||
|
std::fs::write(new.join("mods/user.jar"), "pack collision").unwrap();
|
||||||
|
let owned = HashSet::from([PathBuf::from("mods/pack.jar")]);
|
||||||
|
let target_owned = HashSet::from([
|
||||||
|
PathBuf::from("mods/pack.jar"),
|
||||||
|
PathBuf::from("mods/user.jar"),
|
||||||
|
]);
|
||||||
|
|
||||||
|
preserve_user_files(&old, &new, &old, &owned, &target_owned, &HashSet::new()).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(new.join("mods/pack.jar")).unwrap(),
|
||||||
|
"new"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(new.join("mods/user.jar")).unwrap(),
|
||||||
|
"user"
|
||||||
|
);
|
||||||
|
|
||||||
|
std::fs::write(new.join("mods/user.jar"), "pack collision").unwrap();
|
||||||
|
preserve_user_files(
|
||||||
|
&old,
|
||||||
|
&new,
|
||||||
|
&old,
|
||||||
|
&owned,
|
||||||
|
&target_owned,
|
||||||
|
&HashSet::from([PathBuf::from("mods/user.jar")]),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(new.join("mods/user.jar")).unwrap(),
|
||||||
|
"pack collision"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn interrupted_swap_restores_the_backup_and_removes_staging() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let backup = temp.path().join(".Pack.rmcl-backup");
|
||||||
|
let staging = temp.path().join(".rmcl-refresh-1");
|
||||||
|
std::fs::create_dir_all(&backup).unwrap();
|
||||||
|
std::fs::write(backup.join("instance.json"), "{}").unwrap();
|
||||||
|
std::fs::create_dir_all(&staging).unwrap();
|
||||||
|
|
||||||
|
recover_interrupted(temp.path());
|
||||||
|
|
||||||
|
assert!(temp.path().join("Pack/instance.json").is_file());
|
||||||
|
assert!(!backup.exists());
|
||||||
|
assert!(!staging.exists());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
// java runtime discovery shared by launching, loader installation, and settings.
|
||||||
|
|
||||||
|
#[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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+689
-322
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,323 @@
|
|||||||
|
// 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.
|
||||||
|
|
||||||
|
use libcasr::exception::Exception;
|
||||||
|
use libcasr::java::{JavaException, JavaStacktrace};
|
||||||
|
use libcasr::stacktrace::ParseStacktrace;
|
||||||
|
use regex::Regex;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum LogStream {
|
||||||
|
Stdout,
|
||||||
|
Stderr,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum LogLevel {
|
||||||
|
Trace,
|
||||||
|
Debug,
|
||||||
|
Info,
|
||||||
|
Warn,
|
||||||
|
Error,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||||
|
pub struct JavaParse {
|
||||||
|
pub has_exception: bool,
|
||||||
|
pub has_stacktrace: bool,
|
||||||
|
pub stacktrace_frames: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct ParsedLogEvent {
|
||||||
|
pub level: LogLevel,
|
||||||
|
pub primary_stream: LogStream,
|
||||||
|
pub lines: Vec<String>,
|
||||||
|
pub java: Option<JavaParse>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
struct PendingEvent {
|
||||||
|
level: LogLevel,
|
||||||
|
primary_stream: LogStream,
|
||||||
|
lines: Vec<String>,
|
||||||
|
normalized_lines: Vec<String>,
|
||||||
|
kind: EventKind,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum EventKind {
|
||||||
|
Header,
|
||||||
|
Java,
|
||||||
|
JvmBurst,
|
||||||
|
Native,
|
||||||
|
Plain,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct MinecraftLogParser {
|
||||||
|
current: Option<PendingEvent>,
|
||||||
|
minecraft_header_re: Regex,
|
||||||
|
plain_level_re: Regex,
|
||||||
|
java_exception_re: Regex,
|
||||||
|
java_continuation_re: Regex,
|
||||||
|
jvm_burst_re: Regex,
|
||||||
|
native_header_re: Regex,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for MinecraftLogParser {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MinecraftLogParser {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
// header matching stays local because this parser is in the live
|
||||||
|
// path; pulling in heavier pattern machinery would not help with
|
||||||
|
// the multiline framing problem.
|
||||||
|
minecraft_header_re: Regex::new(
|
||||||
|
r"(?i)^\s*(?:\[[^\]]+\]\s*)*\[[^/\]]+/(?P<level>TRACE|DEBUG|INFO|WARN|ERROR|FATAL)\]\s*:",
|
||||||
|
)
|
||||||
|
.expect("valid minecraft header regex"),
|
||||||
|
plain_level_re: Regex::new(
|
||||||
|
r"(?i)^\s*(?:\[[^\]]+\]\s*)*(?P<level>TRACE|DEBUG|INFO|WARN|ERROR|FATAL)\b\s*(?:[:\]\-])?",
|
||||||
|
)
|
||||||
|
.expect("valid plain level regex"),
|
||||||
|
java_exception_re: Regex::new(
|
||||||
|
r"(?i)^\s*(?:Exception in thread .+|Caused by: |Suppressed: )?(?:[a-z_$][\w$]*\.)+(?:[A-Z][\w$]*(?:Exception|Error)|Throwable)(?::|\b)",
|
||||||
|
)
|
||||||
|
.expect("valid java exception regex"),
|
||||||
|
java_continuation_re: Regex::new(
|
||||||
|
r"^(?:\s+at\s+.+|\s*\.\.\.\s+\d+\s+more|Caused by:\s+.+|Suppressed:\s+.+)$",
|
||||||
|
)
|
||||||
|
.expect("valid java continuation regex"),
|
||||||
|
jvm_burst_re: Regex::new(
|
||||||
|
r"(?i)^\s*(?:Error:\s+.+|Unrecognized option:\s+.+|Could not create the Java Virtual Machine\.|A fatal exception has occurred\. Program will exit\.|Invalid maximum heap size:.+)$",
|
||||||
|
)
|
||||||
|
.expect("valid jvm burst regex"),
|
||||||
|
native_header_re: Regex::new(r"^\[[A-Z]\]\s+\[[0-9:.]+\]\s+[^:]+:")
|
||||||
|
.expect("valid native header regex"),
|
||||||
|
current: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn push_line(&mut self, stream: LogStream, line: impl Into<String>) -> Vec<ParsedLogEvent> {
|
||||||
|
let line = line.into();
|
||||||
|
// classify against ansi-stripped text, but keep the original line for
|
||||||
|
// display so the live log remains faithful to the child process.
|
||||||
|
let normalized = fast_strip_ansi::strip_ansi_string(&line).into_owned();
|
||||||
|
let analysis = self.analyze_line(stream, &normalized);
|
||||||
|
|
||||||
|
let Some(current) = &mut self.current else {
|
||||||
|
self.current = Some(PendingEvent::new(stream, line, normalized, analysis));
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
|
||||||
|
// 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) {
|
||||||
|
let finished = self.current.take().map(finish_event);
|
||||||
|
self.current = Some(PendingEvent::new(stream, line, normalized, analysis));
|
||||||
|
finished.into_iter().collect()
|
||||||
|
} else {
|
||||||
|
if analysis.level_priority() > current.level_priority() {
|
||||||
|
current.level = analysis.level;
|
||||||
|
}
|
||||||
|
if matches!(current.kind, EventKind::Plain)
|
||||||
|
&& !matches!(analysis.kind, EventKind::Plain)
|
||||||
|
{
|
||||||
|
current.kind = analysis.kind;
|
||||||
|
}
|
||||||
|
current.lines.push(line);
|
||||||
|
current.normalized_lines.push(normalized);
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn flush(&mut self) -> Option<ParsedLogEvent> {
|
||||||
|
self.current.take().map(finish_event)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn has_pending(&self) -> bool {
|
||||||
|
self.current.is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn analyze_line(&self, stream: LogStream, normalized: &str) -> LineAnalysis {
|
||||||
|
if let Some(level) = self.header_level(normalized) {
|
||||||
|
return LineAnalysis {
|
||||||
|
level,
|
||||||
|
kind: EventKind::Header,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.java_exception_re.is_match(normalized) {
|
||||||
|
return LineAnalysis {
|
||||||
|
level: LogLevel::Error,
|
||||||
|
kind: EventKind::Java,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.java_continuation_re.is_match(normalized) {
|
||||||
|
return LineAnalysis {
|
||||||
|
level: LogLevel::Error,
|
||||||
|
kind: EventKind::Java,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.jvm_burst_re.is_match(normalized) {
|
||||||
|
return LineAnalysis {
|
||||||
|
level: LogLevel::Error,
|
||||||
|
kind: EventKind::JvmBurst,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.native_header_re.is_match(normalized) {
|
||||||
|
return LineAnalysis {
|
||||||
|
level: native_level(normalized).unwrap_or(LogLevel::Warn),
|
||||||
|
kind: EventKind::Native,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
LineAnalysis {
|
||||||
|
level: match stream {
|
||||||
|
LogStream::Stdout => LogLevel::Info,
|
||||||
|
LogStream::Stderr => LogLevel::Error,
|
||||||
|
},
|
||||||
|
kind: EventKind::Plain,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn header_level(&self, normalized: &str) -> Option<LogLevel> {
|
||||||
|
self.minecraft_header_re
|
||||||
|
.captures(normalized)
|
||||||
|
.and_then(|caps| caps.name("level"))
|
||||||
|
.or_else(|| {
|
||||||
|
self.plain_level_re
|
||||||
|
.captures(normalized)
|
||||||
|
.and_then(|caps| caps.name("level"))
|
||||||
|
})
|
||||||
|
.and_then(|m| parse_level(m.as_str()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
struct LineAnalysis {
|
||||||
|
level: LogLevel,
|
||||||
|
kind: EventKind,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LineAnalysis {
|
||||||
|
fn level_priority(self) -> u8 {
|
||||||
|
level_priority(self.level)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PendingEvent {
|
||||||
|
fn new(stream: LogStream, line: String, normalized: String, analysis: LineAnalysis) -> Self {
|
||||||
|
Self {
|
||||||
|
level: analysis.level,
|
||||||
|
primary_stream: stream,
|
||||||
|
lines: vec![line],
|
||||||
|
normalized_lines: vec![normalized],
|
||||||
|
kind: analysis.kind,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn level_priority(&self) -> u8 {
|
||||||
|
level_priority(self.level)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn should_split(current: EventKind, next: EventKind) -> bool {
|
||||||
|
match next {
|
||||||
|
EventKind::Header => true,
|
||||||
|
EventKind::Native => !matches!(current, EventKind::Native),
|
||||||
|
EventKind::JvmBurst => !matches!(current, EventKind::JvmBurst),
|
||||||
|
EventKind::Java => !matches!(current, EventKind::Java | EventKind::Header),
|
||||||
|
EventKind::Plain => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish_event(mut event: PendingEvent) -> ParsedLogEvent {
|
||||||
|
let normalized_body = event.normalized_lines.join("\n");
|
||||||
|
// libcasr is intentionally second-stage here: first frame the multiline
|
||||||
|
// event ourselves, then ask libcasr whether the block is a java failure.
|
||||||
|
let java = parse_java(&normalized_body);
|
||||||
|
|
||||||
|
if java
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|java| java.has_exception || java.has_stacktrace)
|
||||||
|
{
|
||||||
|
event.level = LogLevel::Error;
|
||||||
|
}
|
||||||
|
|
||||||
|
ParsedLogEvent {
|
||||||
|
level: event.level,
|
||||||
|
primary_stream: event.primary_stream,
|
||||||
|
lines: event.lines,
|
||||||
|
java,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_java(body: &str) -> Option<JavaParse> {
|
||||||
|
let stacktrace_entries = JavaStacktrace::extract_stacktrace(body).unwrap_or_default();
|
||||||
|
let parsed_stacktrace = if stacktrace_entries.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
JavaStacktrace::parse_stacktrace(&stacktrace_entries).ok()
|
||||||
|
};
|
||||||
|
let has_exception = JavaException::parse_exception(body).is_some();
|
||||||
|
let has_stacktrace = parsed_stacktrace
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|stacktrace| !stacktrace.is_empty());
|
||||||
|
|
||||||
|
if has_exception || has_stacktrace {
|
||||||
|
Some(JavaParse {
|
||||||
|
has_exception,
|
||||||
|
has_stacktrace,
|
||||||
|
stacktrace_frames: parsed_stacktrace.map_or(0, |stacktrace| stacktrace.len()),
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_level(level: &str) -> Option<LogLevel> {
|
||||||
|
match level.to_ascii_uppercase().as_str() {
|
||||||
|
"TRACE" => Some(LogLevel::Trace),
|
||||||
|
"DEBUG" => Some(LogLevel::Debug),
|
||||||
|
"INFO" => Some(LogLevel::Info),
|
||||||
|
"WARN" => Some(LogLevel::Warn),
|
||||||
|
"ERROR" | "FATAL" => Some(LogLevel::Error),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn native_level(line: &str) -> Option<LogLevel> {
|
||||||
|
match line.chars().nth(1)? {
|
||||||
|
'E' | 'F' => Some(LogLevel::Error),
|
||||||
|
'W' => Some(LogLevel::Warn),
|
||||||
|
'I' => Some(LogLevel::Info),
|
||||||
|
'D' => Some(LogLevel::Debug),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn level_priority(level: LogLevel) -> u8 {
|
||||||
|
match level {
|
||||||
|
LogLevel::Trace => 0,
|
||||||
|
LogLevel::Debug => 1,
|
||||||
|
LogLevel::Info => 2,
|
||||||
|
LogLevel::Warn => 3,
|
||||||
|
LogLevel::Error => 4,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/launch/parser.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -324,3 +324,7 @@ async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/launch/patches.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -5,7 +5,7 @@ use std::path::Path;
|
|||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
|
|
||||||
use super::{GameVersion, ModLoaderInstaller};
|
use super::{GameVersion, InstallError, InstallerError, ModLoaderInstaller};
|
||||||
use crate::instance::models::ModLoader;
|
use crate::instance::models::ModLoader;
|
||||||
use crate::net::{HttpClient, NetError, fabric as fabric_api};
|
use crate::net::{HttpClient, NetError, fabric as fabric_api};
|
||||||
|
|
||||||
@@ -26,7 +26,16 @@ impl ModLoaderInstaller for FabricInstaller {
|
|||||||
client: &HttpClient,
|
client: &HttpClient,
|
||||||
game_version: &str,
|
game_version: &str,
|
||||||
) -> Result<Vec<String>, NetError> {
|
) -> Result<Vec<String>, NetError> {
|
||||||
|
tracing::debug!(
|
||||||
|
"Fetching Fabric loader versions for Minecraft {}",
|
||||||
|
game_version
|
||||||
|
);
|
||||||
let loader_versions = fabric_api::fetch_fabric_versions(client, game_version).await?;
|
let loader_versions = fabric_api::fetch_fabric_versions(client, game_version).await?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Fetched {} Fabric loader version(s) for Minecraft {}",
|
||||||
|
loader_versions.len(),
|
||||||
|
game_version
|
||||||
|
);
|
||||||
Ok(loader_versions
|
Ok(loader_versions
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|lv| lv.loader.version)
|
.map(|lv| lv.loader.version)
|
||||||
@@ -40,17 +49,31 @@ impl ModLoaderInstaller for FabricInstaller {
|
|||||||
loader_version: &str,
|
loader_version: &str,
|
||||||
_instance_dir: &Path,
|
_instance_dir: &Path,
|
||||||
meta_dir: &Path,
|
meta_dir: &Path,
|
||||||
) -> Result<(), NetError> {
|
) -> Result<(), InstallError> {
|
||||||
let profile =
|
tracing::info!(
|
||||||
fabric_api::fetch_fabric_profile(client, game_version, loader_version).await?;
|
"Installing Fabric {} for Minecraft {}",
|
||||||
|
loader_version,
|
||||||
|
game_version
|
||||||
|
);
|
||||||
|
let (profile, raw_bytes) =
|
||||||
|
fabric_api::fetch_fabric_profile_with_raw(client, game_version, loader_version).await?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Fetched Fabric profile {} with {} libraries",
|
||||||
|
profile.id,
|
||||||
|
profile.libraries.len()
|
||||||
|
);
|
||||||
fabric_api::download_fabric_libraries(client, &profile, meta_dir).await?;
|
fabric_api::download_fabric_libraries(client, &profile, meta_dir).await?;
|
||||||
|
super::save_profile_bytes(
|
||||||
super::save_profile_json(
|
|
||||||
meta_dir,
|
meta_dir,
|
||||||
&format!("fabric-{game_version}-{loader_version}.json"),
|
&format!("fabric-{game_version}-{loader_version}.json"),
|
||||||
&profile,
|
&raw_bytes,
|
||||||
)?;
|
)
|
||||||
|
.map_err(InstallerError::from)?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Saved Fabric profile for Minecraft {} loader {}",
|
||||||
|
game_version,
|
||||||
|
loader_version
|
||||||
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+281
-19
@@ -6,9 +6,10 @@ use std::path::Path;
|
|||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
|
|
||||||
use super::{GameVersion, ModLoaderInstaller};
|
use super::{GameVersion, InstallError, InstallerError, ModLoaderInstaller};
|
||||||
|
use crate::feedback::progress::{set_action, set_sub_action};
|
||||||
use crate::instance::models::ModLoader;
|
use crate::instance::models::ModLoader;
|
||||||
use crate::net::{HttpClient, NetError, forge as forge_api};
|
use crate::net::{HttpClient, NetError, download_file, forge as forge_api};
|
||||||
|
|
||||||
pub struct ForgeInstaller;
|
pub struct ForgeInstaller;
|
||||||
|
|
||||||
@@ -27,7 +28,14 @@ impl ModLoaderInstaller for ForgeInstaller {
|
|||||||
client: &HttpClient,
|
client: &HttpClient,
|
||||||
game_version: &str,
|
game_version: &str,
|
||||||
) -> Result<Vec<String>, NetError> {
|
) -> Result<Vec<String>, NetError> {
|
||||||
forge_api::fetch_forge_versions(client, game_version).await
|
tracing::debug!("Fetching Forge versions for Minecraft {}", game_version);
|
||||||
|
let versions = forge_api::fetch_forge_versions(client, game_version).await?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Fetched {} Forge version(s) for Minecraft {}",
|
||||||
|
versions.len(),
|
||||||
|
game_version
|
||||||
|
);
|
||||||
|
Ok(versions)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn install(
|
async fn install(
|
||||||
@@ -37,22 +45,27 @@ impl ModLoaderInstaller for ForgeInstaller {
|
|||||||
loader_version: &str,
|
loader_version: &str,
|
||||||
instance_dir: &Path,
|
instance_dir: &Path,
|
||||||
meta_dir: &Path,
|
meta_dir: &Path,
|
||||||
) -> Result<(), NetError> {
|
) -> Result<(), InstallError> {
|
||||||
let installer_jar = instance_dir.join(".minecraft").join("forge-installer.jar");
|
let installer_jar = instance_dir
|
||||||
|
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||||
|
.join("forge-installer.jar");
|
||||||
|
tracing::info!(
|
||||||
|
"Installing Forge {} for Minecraft {}",
|
||||||
|
loader_version,
|
||||||
|
game_version
|
||||||
|
);
|
||||||
|
tracing::debug!("Forge installer path: {}", installer_jar.display());
|
||||||
|
|
||||||
forge_api::download_forge_installer(client, game_version, loader_version, &installer_jar)
|
forge_api::download_forge_installer(client, game_version, loader_version, &installer_jar)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let profile_filename = format!("forge-{game_version}-{loader_version}.json");
|
let profile_filename = format!("forge-{game_version}-{loader_version}.json");
|
||||||
|
|
||||||
if forge_api::has_legacy_install_profile(&installer_jar) {
|
if has_legacy_install_profile(&installer_jar) {
|
||||||
// old forge: no --installClient support, extract directly from jar
|
// old forge: no --installClient support, extract directly from jar
|
||||||
if let Err(e) = forge_api::install_forge_from_profile(
|
tracing::debug!("Forge installer uses legacy install_profile.json path");
|
||||||
client,
|
if let Err(e) =
|
||||||
&installer_jar,
|
install_forge_from_profile(client, &installer_jar, meta_dir, &profile_filename)
|
||||||
meta_dir,
|
|
||||||
&profile_filename,
|
|
||||||
)
|
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
let _ = tokio::fs::remove_file(&installer_jar).await;
|
let _ = tokio::fs::remove_file(&installer_jar).await;
|
||||||
@@ -64,33 +77,282 @@ impl ModLoaderInstaller for ForgeInstaller {
|
|||||||
.paths
|
.paths
|
||||||
.effective_java_path()
|
.effective_java_path()
|
||||||
.map(str::to_owned)
|
.map(str::to_owned)
|
||||||
.unwrap_or_else(crate::net::detect_java_path);
|
.unwrap_or_else(crate::instance::java::detect_java_path);
|
||||||
if let Err(e) =
|
tracing::debug!("Running Forge installer with Java {}", java_path);
|
||||||
forge_api::run_forge_installer(&installer_jar, instance_dir, &java_path).await
|
if let Err(e) = run_forge_installer(&installer_jar, instance_dir, &java_path).await {
|
||||||
{
|
|
||||||
let _ = tokio::fs::remove_file(&installer_jar).await;
|
let _ = tokio::fs::remove_file(&installer_jar).await;
|
||||||
return Err(e);
|
return Err(InstallError::Installer(e));
|
||||||
}
|
}
|
||||||
|
|
||||||
// extract the profile from what the installer just wrote to disk
|
// extract the profile from what the installer just wrote to disk
|
||||||
save_forge_profile(instance_dir, meta_dir, game_version, loader_version)?;
|
save_forge_profile(instance_dir, meta_dir, game_version, loader_version)
|
||||||
|
.map_err(InstallError::Installer)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Err(e) = tokio::fs::remove_file(&installer_jar).await {
|
if let Err(e) = tokio::fs::remove_file(&installer_jar).await {
|
||||||
tracing::warn!("Failed to remove Forge installer JAR: {}", e);
|
tracing::warn!("Failed to remove Forge installer JAR: {}", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tracing::debug!(
|
||||||
|
"Installed Forge {} for Minecraft {}",
|
||||||
|
loader_version,
|
||||||
|
game_version
|
||||||
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn run_forge_installer(
|
||||||
|
installer_path: &Path,
|
||||||
|
instance_dir: &Path,
|
||||||
|
java_path: &str,
|
||||||
|
) -> Result<(), InstallerError> {
|
||||||
|
use tokio::process::Command;
|
||||||
|
|
||||||
|
set_action("Running Forge installer...");
|
||||||
|
|
||||||
|
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
|
||||||
|
{
|
||||||
|
Ok(o) => o,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::debug!(
|
||||||
|
"Failed to spawn Forge installer {} with Java {}: {}",
|
||||||
|
installer_path.display(),
|
||||||
|
java_path,
|
||||||
|
e
|
||||||
|
);
|
||||||
|
return Err(InstallerError::Io(e));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if !output.status.success() {
|
||||||
|
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||||
|
let detail = if stderr.trim().is_empty() {
|
||||||
|
format!("exit code {:?}", output.status.code())
|
||||||
|
} else {
|
||||||
|
stderr.lines().last().unwrap_or("unknown error").to_string()
|
||||||
|
};
|
||||||
|
tracing::debug!(
|
||||||
|
"Forge installer {} failed with status {:?}: {}",
|
||||||
|
installer_path.display(),
|
||||||
|
output.status.code(),
|
||||||
|
detail
|
||||||
|
);
|
||||||
|
return Err(InstallerError::ProcessFailed(detail));
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::debug!("Forge installer completed successfully");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// old forge installers have an install_profile.json with a "versionInfo" key
|
||||||
|
// containing everything needed. modern ones don't have this structure.
|
||||||
|
pub(crate) fn has_legacy_install_profile(installer_path: &Path) -> bool {
|
||||||
|
let file = match std::fs::File::open(installer_path) {
|
||||||
|
Ok(f) => f,
|
||||||
|
Err(_) => return false,
|
||||||
|
};
|
||||||
|
let mut archive = match zip::ZipArchive::new(file) {
|
||||||
|
Ok(a) => a,
|
||||||
|
Err(_) => return false,
|
||||||
|
};
|
||||||
|
let entry = match archive.by_name("install_profile.json") {
|
||||||
|
Ok(e) => e,
|
||||||
|
Err(_) => return false,
|
||||||
|
};
|
||||||
|
let value: serde_json::Value = match serde_json::from_reader(entry) {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(_) => return false,
|
||||||
|
};
|
||||||
|
value.get("versionInfo").is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
// handles old-style forge installation by extracting the universal jar and
|
||||||
|
// library info directly from the installer, bypassing the GUI-only installer
|
||||||
|
pub(crate) async fn install_forge_from_profile(
|
||||||
|
client: &HttpClient,
|
||||||
|
installer_path: &Path,
|
||||||
|
meta_dir: &Path,
|
||||||
|
profile_filename: &str,
|
||||||
|
) -> Result<(), InstallError> {
|
||||||
|
use std::io::Read;
|
||||||
|
|
||||||
|
set_action("Installing legacy Forge from profile...");
|
||||||
|
tracing::debug!(
|
||||||
|
"Installing legacy Forge from {} into {}",
|
||||||
|
installer_path.display(),
|
||||||
|
meta_dir.display()
|
||||||
|
);
|
||||||
|
|
||||||
|
let file = std::fs::File::open(installer_path)
|
||||||
|
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
|
||||||
|
let mut archive = zip::ZipArchive::new(file).map_err(|e| {
|
||||||
|
InstallError::Installer(InstallerError::Profile(format!(
|
||||||
|
"Failed to open installer as ZIP: {e}"
|
||||||
|
)))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let profile_data: serde_json::Value = {
|
||||||
|
let entry = archive.by_name("install_profile.json").map_err(|e| {
|
||||||
|
InstallError::Installer(InstallerError::Profile(format!(
|
||||||
|
"install_profile.json not found in installer: {e}"
|
||||||
|
)))
|
||||||
|
})?;
|
||||||
|
serde_json::from_reader(entry).map_err(|e| {
|
||||||
|
InstallError::Installer(InstallerError::Profile(format!(
|
||||||
|
"Failed to parse install_profile.json: {e}"
|
||||||
|
)))
|
||||||
|
})?
|
||||||
|
};
|
||||||
|
|
||||||
|
let version_info = profile_data.get("versionInfo").ok_or_else(|| {
|
||||||
|
InstallError::Installer(InstallerError::Profile(
|
||||||
|
"install_profile.json missing versionInfo".into(),
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
let install_info = profile_data.get("install").ok_or_else(|| {
|
||||||
|
InstallError::Installer(InstallerError::Profile(
|
||||||
|
"install_profile.json missing install section".into(),
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let libraries = version_info
|
||||||
|
.get("libraries")
|
||||||
|
.and_then(|v| v.as_array())
|
||||||
|
.ok_or_else(|| {
|
||||||
|
InstallError::Installer(InstallerError::Profile(
|
||||||
|
"missing versionInfo.libraries".into(),
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let file_path = install_info
|
||||||
|
.get("filePath")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.ok_or_else(|| {
|
||||||
|
InstallError::Installer(InstallerError::Profile("missing install.filePath".into()))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let install_path_coord = install_info
|
||||||
|
.get("path")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.ok_or_else(|| {
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
.ok_or_else(|| {
|
||||||
|
InstallError::Installer(InstallerError::Profile(format!(
|
||||||
|
"Invalid maven coord in install.path: {install_path_coord}"
|
||||||
|
)))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
set_sub_action("Extracting universal JAR...");
|
||||||
|
let universal_dest = crate::storage::MetadataPaths::new(meta_dir)
|
||||||
|
.libraries()
|
||||||
|
.join(&universal_maven_path);
|
||||||
|
if let Some(parent) = universal_dest.parent() {
|
||||||
|
std::fs::create_dir_all(parent)
|
||||||
|
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut entry = archive.by_name(file_path).map_err(|e| {
|
||||||
|
InstallError::Installer(InstallerError::Profile(format!(
|
||||||
|
"Universal JAR '{file_path}' not found in installer: {e}"
|
||||||
|
)))
|
||||||
|
})?;
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
entry
|
||||||
|
.read_to_end(&mut buf)
|
||||||
|
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
|
||||||
|
std::fs::write(&universal_dest, &buf)
|
||||||
|
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Extracted legacy Forge universal JAR to {} ({} bytes)",
|
||||||
|
universal_dest.display(),
|
||||||
|
buf.len()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// download libraries needed by this forge version. libs with a url field
|
||||||
|
// are forge-hosted, libs without one are typically from mojang's library
|
||||||
|
// server. old forge versions reference libs like launchwrapper that aren't
|
||||||
|
// in mojang's modern version metadata, so we fetch those too.
|
||||||
|
let libraries_dir = crate::storage::MetadataPaths::new(meta_dir).libraries();
|
||||||
|
for lib in libraries {
|
||||||
|
let name = lib.get("name").and_then(|v| v.as_str()).unwrap_or_default();
|
||||||
|
|
||||||
|
let maven_path = match crate::instance::loader::maven::maven_coord_to_path(name) {
|
||||||
|
Some(p) => p,
|
||||||
|
None => {
|
||||||
|
return Err(InstallError::Installer(InstallerError::Profile(format!(
|
||||||
|
"Invalid Maven coordinate: {name}"
|
||||||
|
))));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let dest = libraries_dir.join(&maven_path);
|
||||||
|
if dest.exists() {
|
||||||
|
tracing::trace!("Legacy Forge library already cached: {}", name);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let base_url = lib
|
||||||
|
.get("url")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or("https://libraries.minecraft.net/")
|
||||||
|
.trim_end_matches('/');
|
||||||
|
let download_url = format!("{base_url}/{maven_path}");
|
||||||
|
|
||||||
|
set_sub_action(name);
|
||||||
|
tracing::debug!("Downloading legacy Forge library {}", name);
|
||||||
|
download_file(client, &download_url, &dest, |_, _| {}).await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
set_action("Saving Forge profile...");
|
||||||
|
// write the installer's versionInfo as compact JSON. it already has the
|
||||||
|
// mainClass, the full library list (with name + url for forge-hosted
|
||||||
|
// libs), and minecraftArguments (the legacy --tweakClass etc). the
|
||||||
|
// launch flow parses this as a LaunchProfile and - if there's no
|
||||||
|
// 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.
|
||||||
|
let serialized = serde_json::to_vec(version_info).map_err(|e| {
|
||||||
|
InstallError::Installer(InstallerError::Profile(format!(
|
||||||
|
"Failed to serialize Forge profile: {e}"
|
||||||
|
)))
|
||||||
|
})?;
|
||||||
|
crate::instance::loader::save_profile_bytes(meta_dir, profile_filename, &serialized)
|
||||||
|
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn save_forge_profile(
|
fn save_forge_profile(
|
||||||
instance_dir: &Path,
|
instance_dir: &Path,
|
||||||
meta_dir: &Path,
|
meta_dir: &Path,
|
||||||
game_version: &str,
|
game_version: &str,
|
||||||
loader_version: &str,
|
loader_version: &str,
|
||||||
) -> Result<(), NetError> {
|
) -> Result<(), super::InstallerError> {
|
||||||
let version_dir_name = format!("{game_version}-forge-{loader_version}");
|
let version_dir_name = format!("{game_version}-forge-{loader_version}");
|
||||||
let profile_filename = format!("forge-{game_version}-{loader_version}.json");
|
let profile_filename = format!("forge-{game_version}-{loader_version}.json");
|
||||||
super::save_installer_profile(instance_dir, meta_dir, &version_dir_name, &profile_filename)
|
super::save_installer_profile(instance_dir, meta_dir, &version_dir_name, &profile_filename)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/loader/forge.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
// 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() {
|
||||||
|
[group, artifact, version] => {
|
||||||
|
let group_path = group.replace('.', "/");
|
||||||
|
Some(format!(
|
||||||
|
"{}/{}/{}/{}-{}.jar",
|
||||||
|
group_path, artifact, version, artifact, version
|
||||||
|
))
|
||||||
|
}
|
||||||
|
[group, artifact, version, classifier] => {
|
||||||
|
let group_path = group.replace('.', "/");
|
||||||
|
Some(format!(
|
||||||
|
"{}/{}/{}/{}-{}-{}.jar",
|
||||||
|
group_path, artifact, version, artifact, version, classifier
|
||||||
|
))
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/loader/maven.rs"]
|
||||||
|
mod tests;
|
||||||
+61
-86
@@ -4,18 +4,38 @@
|
|||||||
// though (fabric/quilt just download jars, forge/neoforge run a whole java installer).
|
// though (fabric/quilt just download jars, forge/neoforge run a whole java installer).
|
||||||
|
|
||||||
mod fabric;
|
mod fabric;
|
||||||
mod forge;
|
pub mod forge;
|
||||||
mod neoforge;
|
pub mod maven;
|
||||||
|
pub mod neoforge;
|
||||||
mod quilt;
|
mod quilt;
|
||||||
mod vanilla;
|
mod vanilla;
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
|
use thiserror::Error;
|
||||||
|
|
||||||
use crate::instance::models::ModLoader;
|
use crate::instance::models::ModLoader;
|
||||||
use crate::net::{HttpClient, NetError};
|
use crate::net::{HttpClient, NetError};
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum InstallerError {
|
||||||
|
#[error("IO error: {0}")]
|
||||||
|
Io(#[from] std::io::Error),
|
||||||
|
#[error("Process failed: {0}")]
|
||||||
|
ProcessFailed(String),
|
||||||
|
#[error("Profile error: {0}")]
|
||||||
|
Profile(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum InstallError {
|
||||||
|
#[error("Download error: {0}")]
|
||||||
|
Download(#[from] NetError),
|
||||||
|
#[error("Installer error: {0}")]
|
||||||
|
Installer(#[from] InstallerError),
|
||||||
|
}
|
||||||
|
|
||||||
pub use vanilla::VanillaInstaller;
|
pub use vanilla::VanillaInstaller;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -43,76 +63,69 @@ pub trait ModLoaderInstaller: Send + Sync {
|
|||||||
loader_version: &str,
|
loader_version: &str,
|
||||||
instance_dir: &Path,
|
instance_dir: &Path,
|
||||||
meta_dir: &Path,
|
meta_dir: &Path,
|
||||||
) -> Result<(), NetError>;
|
) -> Result<(), InstallError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn save_profile_json(
|
// writes raw profile JSON bytes to meta_dir/loader-profiles/<filename>.
|
||||||
|
// 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(
|
||||||
meta_dir: &Path,
|
meta_dir: &Path,
|
||||||
filename: &str,
|
filename: &str,
|
||||||
profile: &impl serde::Serialize,
|
bytes: &[u8],
|
||||||
) -> Result<(), NetError> {
|
) -> std::io::Result<()> {
|
||||||
let profiles_dir = meta_dir.join("loader-profiles");
|
let profiles_dir = crate::storage::MetadataPaths::new(meta_dir).loader_profiles();
|
||||||
std::fs::create_dir_all(&profiles_dir)?;
|
std::fs::create_dir_all(&profiles_dir)?;
|
||||||
let profile_path = profiles_dir.join(filename);
|
std::fs::write(profiles_dir.join(filename), bytes)
|
||||||
let json = serde_json::to_string_pretty(profile)
|
|
||||||
.map_err(|e| NetError::Parse(format!("Failed to serialize profile {filename}: {e}")))?;
|
|
||||||
std::fs::write(&profile_path, &json)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// used by forge/neoforge. their java installer drops a version json into
|
// used by forge/neoforge. their java installer drops a version json into
|
||||||
// .minecraft/versions/. parses that to extract the main class and library
|
// .minecraft/versions/. we copy that file byte-for-byte to our loader
|
||||||
// list, then saves a stripped-down profile for use at launch time.
|
// profile cache so launch-time code sees the full upstream JSON -
|
||||||
|
// inheritsFrom, arguments.jvm, library rules, all of it - instead of a
|
||||||
|
// stripped-down version that would silently drop modern features (e.g.
|
||||||
|
// the --add-opens flags forge 1.17+ ships for java 17+ support).
|
||||||
pub(crate) fn save_installer_profile(
|
pub(crate) fn save_installer_profile(
|
||||||
instance_dir: &Path,
|
instance_dir: &Path,
|
||||||
meta_dir: &Path,
|
meta_dir: &Path,
|
||||||
version_dir_name: &str,
|
version_dir_name: &str,
|
||||||
profile_filename: &str,
|
profile_filename: &str,
|
||||||
) -> Result<(), NetError> {
|
) -> Result<(), InstallerError> {
|
||||||
let ver_json_path = instance_dir
|
let ver_json_path = instance_dir
|
||||||
.join(".minecraft")
|
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||||
.join("versions")
|
.join("versions")
|
||||||
.join(version_dir_name)
|
.join(version_dir_name)
|
||||||
.join(format!("{version_dir_name}.json"));
|
.join(format!("{version_dir_name}.json"));
|
||||||
|
|
||||||
if !ver_json_path.exists() {
|
if !ver_json_path.exists() {
|
||||||
return Err(NetError::Parse(format!(
|
tracing::debug!(
|
||||||
|
"Installer profile JSON missing: {}",
|
||||||
|
ver_json_path.display()
|
||||||
|
);
|
||||||
|
return Err(InstallerError::Profile(format!(
|
||||||
"Version JSON not found at {}",
|
"Version JSON not found at {}",
|
||||||
ver_json_path.display()
|
ver_json_path.display()
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
tracing::debug!(
|
||||||
#[serde(rename_all = "camelCase")]
|
"Saving installer profile {} from {}",
|
||||||
struct InstallerVersionJson {
|
profile_filename,
|
||||||
main_class: String,
|
|
||||||
#[serde(default)]
|
|
||||||
libraries: Vec<InstallerLib>,
|
|
||||||
}
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
struct InstallerLib {
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
let raw = std::fs::read(&ver_json_path)?;
|
|
||||||
let ver: InstallerVersionJson = serde_json::from_slice(&raw).map_err(|e| {
|
|
||||||
NetError::Parse(format!(
|
|
||||||
"Invalid version JSON at {}: {e}",
|
|
||||||
ver_json_path.display()
|
ver_json_path.display()
|
||||||
))
|
);
|
||||||
})?;
|
let raw = std::fs::read(&ver_json_path)?;
|
||||||
|
|
||||||
let libs: Vec<serde_json::Value> = ver
|
let profiles_dir = crate::storage::MetadataPaths::new(meta_dir).loader_profiles();
|
||||||
.libraries
|
std::fs::create_dir_all(&profiles_dir)?;
|
||||||
.iter()
|
let profile_path = profiles_dir.join(profile_filename);
|
||||||
.map(|l| serde_json::json!({"name": l.name}))
|
std::fs::write(&profile_path, &raw)?;
|
||||||
.collect();
|
tracing::debug!(
|
||||||
let json_val = serde_json::json!({
|
"Saved installer profile to {} ({} bytes)",
|
||||||
"mainClass": ver.main_class,
|
profile_path.display(),
|
||||||
"libraries": libs
|
raw.len()
|
||||||
});
|
);
|
||||||
|
Ok(())
|
||||||
save_profile_json(meta_dir, profile_filename, &json_val)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_installer(loader: ModLoader) -> Box<dyn ModLoaderInstaller + Send + Sync> {
|
pub fn get_installer(loader: ModLoader) -> Box<dyn ModLoaderInstaller + Send + Sync> {
|
||||||
@@ -126,43 +139,5 @@ pub fn get_installer(loader: ModLoader) -> Box<dyn ModLoaderInstaller + Send + S
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "../tests/loader/installers.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_vanilla_factory() {
|
|
||||||
let installer = get_installer(ModLoader::Vanilla);
|
|
||||||
assert_eq!(installer.loader_type(), ModLoader::Vanilla);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn test_vanilla_get_versions() {
|
|
||||||
let client = HttpClient::new();
|
|
||||||
let installer = VanillaInstaller;
|
|
||||||
let versions = installer.get_versions(&client, "1.20.1").await.unwrap();
|
|
||||||
assert!(!versions.is_empty());
|
|
||||||
assert_eq!(versions[0], "vanilla");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn test_vanilla_install_noop() {
|
|
||||||
let client = HttpClient::new();
|
|
||||||
let installer = VanillaInstaller;
|
|
||||||
let tmp = std::env::temp_dir().join("rmcl_test_vanilla_install");
|
|
||||||
let meta = std::env::temp_dir().join("rmcl_test_meta");
|
|
||||||
installer
|
|
||||||
.install(&client, "1.20.1", "vanilla", &tmp, &meta)
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
#[ignore = "hits live Mojang API"]
|
|
||||||
async fn test_vanilla_get_game_versions() {
|
|
||||||
let client = HttpClient::new();
|
|
||||||
let installer = VanillaInstaller;
|
|
||||||
let versions = installer.get_game_versions(&client).await.unwrap();
|
|
||||||
assert!(!versions.is_empty());
|
|
||||||
assert!(versions.iter().any(|v| v.id == "1.20.1"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,7 +5,8 @@ use std::path::Path;
|
|||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
|
|
||||||
use super::{GameVersion, ModLoaderInstaller};
|
use super::{GameVersion, InstallError, InstallerError, ModLoaderInstaller};
|
||||||
|
use crate::feedback::progress::set_action;
|
||||||
use crate::instance::models::ModLoader;
|
use crate::instance::models::ModLoader;
|
||||||
use crate::net::{HttpClient, NetError, neoforge as neoforge_api};
|
use crate::net::{HttpClient, NetError, neoforge as neoforge_api};
|
||||||
|
|
||||||
@@ -26,7 +27,14 @@ impl ModLoaderInstaller for NeoForgeInstaller {
|
|||||||
client: &HttpClient,
|
client: &HttpClient,
|
||||||
game_version: &str,
|
game_version: &str,
|
||||||
) -> Result<Vec<String>, NetError> {
|
) -> Result<Vec<String>, NetError> {
|
||||||
neoforge_api::fetch_neoforge_versions(client, game_version).await
|
tracing::debug!("Fetching NeoForge versions for Minecraft {}", game_version);
|
||||||
|
let versions = neoforge_api::fetch_neoforge_versions(client, game_version).await?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Fetched {} NeoForge version(s) for Minecraft {}",
|
||||||
|
versions.len(),
|
||||||
|
game_version
|
||||||
|
);
|
||||||
|
Ok(versions)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn install(
|
async fn install(
|
||||||
@@ -36,10 +44,12 @@ impl ModLoaderInstaller for NeoForgeInstaller {
|
|||||||
loader_version: &str,
|
loader_version: &str,
|
||||||
instance_dir: &Path,
|
instance_dir: &Path,
|
||||||
meta_dir: &Path,
|
meta_dir: &Path,
|
||||||
) -> Result<(), NetError> {
|
) -> Result<(), InstallError> {
|
||||||
let installer_jar = instance_dir
|
let installer_jar = instance_dir
|
||||||
.join(".minecraft")
|
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||||
.join("neoforge-installer.jar");
|
.join("neoforge-installer.jar");
|
||||||
|
tracing::info!("Installing NeoForge {}", loader_version);
|
||||||
|
tracing::debug!("NeoForge installer path: {}", installer_jar.display());
|
||||||
|
|
||||||
neoforge_api::download_neoforge_installer(client, loader_version, &installer_jar).await?;
|
neoforge_api::download_neoforge_installer(client, loader_version, &installer_jar).await?;
|
||||||
|
|
||||||
@@ -47,29 +57,79 @@ impl ModLoaderInstaller for NeoForgeInstaller {
|
|||||||
.paths
|
.paths
|
||||||
.effective_java_path()
|
.effective_java_path()
|
||||||
.map(str::to_owned)
|
.map(str::to_owned)
|
||||||
.unwrap_or_else(crate::net::detect_java_path);
|
.unwrap_or_else(crate::instance::java::detect_java_path);
|
||||||
if let Err(e) =
|
tracing::debug!("Running NeoForge installer with Java {}", java_path);
|
||||||
neoforge_api::run_neoforge_installer(&installer_jar, instance_dir, &java_path).await
|
if let Err(e) = run_neoforge_installer(&installer_jar, instance_dir, &java_path).await {
|
||||||
{
|
|
||||||
let _ = tokio::fs::remove_file(&installer_jar).await;
|
let _ = tokio::fs::remove_file(&installer_jar).await;
|
||||||
return Err(e);
|
return Err(InstallError::Installer(e));
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Err(e) = tokio::fs::remove_file(&installer_jar).await {
|
if let Err(e) = tokio::fs::remove_file(&installer_jar).await {
|
||||||
tracing::warn!("Failed to remove NeoForge installer JAR: {}", e);
|
tracing::warn!("Failed to remove NeoForge installer JAR: {}", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
save_neoforge_profile(instance_dir, meta_dir, loader_version)?;
|
save_neoforge_profile(instance_dir, meta_dir, loader_version)
|
||||||
|
.map_err(InstallError::Installer)?;
|
||||||
|
|
||||||
|
tracing::debug!("Installed NeoForge {}", loader_version);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn run_neoforge_installer(
|
||||||
|
installer_path: &Path,
|
||||||
|
instance_dir: &Path,
|
||||||
|
java_path: &str,
|
||||||
|
) -> Result<(), InstallerError> {
|
||||||
|
use tokio::process::Command;
|
||||||
|
|
||||||
|
set_action("Running NeoForge installer...");
|
||||||
|
|
||||||
|
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
|
||||||
|
{
|
||||||
|
Ok(o) => o,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::debug!(
|
||||||
|
"Failed to spawn NeoForge installer {} with Java {}: {}",
|
||||||
|
installer_path.display(),
|
||||||
|
java_path,
|
||||||
|
e
|
||||||
|
);
|
||||||
|
return Err(InstallerError::Io(e));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if !output.status.success() {
|
||||||
|
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||||
|
let detail = stderr.lines().last().unwrap_or("").trim();
|
||||||
|
tracing::debug!(
|
||||||
|
"NeoForge installer {} failed with status {:?}: {}",
|
||||||
|
installer_path.display(),
|
||||||
|
output.status.code(),
|
||||||
|
detail
|
||||||
|
);
|
||||||
|
return Err(InstallerError::ProcessFailed(format!(
|
||||||
|
"NeoForge installer exited with {:?}",
|
||||||
|
output.status.code()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::debug!("NeoForge installer completed successfully");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn save_neoforge_profile(
|
fn save_neoforge_profile(
|
||||||
instance_dir: &Path,
|
instance_dir: &Path,
|
||||||
meta_dir: &Path,
|
meta_dir: &Path,
|
||||||
loader_version: &str,
|
loader_version: &str,
|
||||||
) -> Result<(), NetError> {
|
) -> Result<(), super::InstallerError> {
|
||||||
let version_dir_name = format!("neoforge-{loader_version}");
|
let version_dir_name = format!("neoforge-{loader_version}");
|
||||||
let profile_filename = format!("neoforge-{loader_version}.json");
|
let profile_filename = format!("neoforge-{loader_version}.json");
|
||||||
super::save_installer_profile(instance_dir, meta_dir, &version_dir_name, &profile_filename)
|
super::save_installer_profile(instance_dir, meta_dir, &version_dir_name, &profile_filename)
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use std::path::Path;
|
|||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
|
|
||||||
use super::{GameVersion, ModLoaderInstaller};
|
use super::{GameVersion, InstallError, InstallerError, ModLoaderInstaller};
|
||||||
use crate::instance::models::ModLoader;
|
use crate::instance::models::ModLoader;
|
||||||
use crate::net::{HttpClient, NetError, quilt as quilt_api};
|
use crate::net::{HttpClient, NetError, quilt as quilt_api};
|
||||||
|
|
||||||
@@ -26,7 +26,16 @@ impl ModLoaderInstaller for QuiltInstaller {
|
|||||||
client: &HttpClient,
|
client: &HttpClient,
|
||||||
game_version: &str,
|
game_version: &str,
|
||||||
) -> Result<Vec<String>, NetError> {
|
) -> Result<Vec<String>, NetError> {
|
||||||
|
tracing::debug!(
|
||||||
|
"Fetching Quilt loader versions for Minecraft {}",
|
||||||
|
game_version
|
||||||
|
);
|
||||||
let loader_versions = quilt_api::fetch_quilt_versions(client, game_version).await?;
|
let loader_versions = quilt_api::fetch_quilt_versions(client, game_version).await?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Fetched {} Quilt loader version(s) for Minecraft {}",
|
||||||
|
loader_versions.len(),
|
||||||
|
game_version
|
||||||
|
);
|
||||||
Ok(loader_versions
|
Ok(loader_versions
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|lv| lv.loader.version)
|
.map(|lv| lv.loader.version)
|
||||||
@@ -40,16 +49,31 @@ impl ModLoaderInstaller for QuiltInstaller {
|
|||||||
loader_version: &str,
|
loader_version: &str,
|
||||||
_instance_dir: &Path,
|
_instance_dir: &Path,
|
||||||
meta_dir: &Path,
|
meta_dir: &Path,
|
||||||
) -> Result<(), NetError> {
|
) -> Result<(), InstallError> {
|
||||||
let profile = quilt_api::fetch_quilt_profile(client, game_version, loader_version).await?;
|
tracing::info!(
|
||||||
|
"Installing Quilt {} for Minecraft {}",
|
||||||
|
loader_version,
|
||||||
|
game_version
|
||||||
|
);
|
||||||
|
let (profile, raw_bytes) =
|
||||||
|
quilt_api::fetch_quilt_profile_with_raw(client, game_version, loader_version).await?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Fetched Quilt profile {} with {} libraries",
|
||||||
|
profile.id,
|
||||||
|
profile.libraries.len()
|
||||||
|
);
|
||||||
quilt_api::download_quilt_libraries(client, &profile, meta_dir).await?;
|
quilt_api::download_quilt_libraries(client, &profile, meta_dir).await?;
|
||||||
|
super::save_profile_bytes(
|
||||||
super::save_profile_json(
|
|
||||||
meta_dir,
|
meta_dir,
|
||||||
&format!("quilt-{game_version}-{loader_version}.json"),
|
&format!("quilt-{game_version}-{loader_version}.json"),
|
||||||
&profile,
|
&raw_bytes,
|
||||||
)?;
|
)
|
||||||
|
.map_err(InstallerError::from)?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Saved Quilt profile for Minecraft {} loader {}",
|
||||||
|
game_version,
|
||||||
|
loader_version
|
||||||
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -6,7 +6,7 @@ use std::path::Path;
|
|||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
|
|
||||||
use super::{GameVersion, ModLoaderInstaller};
|
use super::{GameVersion, InstallError, ModLoaderInstaller};
|
||||||
use crate::instance::models::ModLoader;
|
use crate::instance::models::ModLoader;
|
||||||
use crate::net::{HttpClient, NetError, mojang};
|
use crate::net::{HttpClient, NetError, mojang};
|
||||||
|
|
||||||
@@ -20,14 +20,7 @@ impl ModLoaderInstaller for VanillaInstaller {
|
|||||||
|
|
||||||
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
|
async fn get_game_versions(&self, client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
|
||||||
let manifest = mojang::fetch_version_manifest(client).await?;
|
let manifest = mojang::fetch_version_manifest(client).await?;
|
||||||
Ok(manifest
|
Ok(game_versions_from_manifest(manifest))
|
||||||
.versions
|
|
||||||
.into_iter()
|
|
||||||
.map(|v| GameVersion {
|
|
||||||
id: v.id,
|
|
||||||
stable: v.version_type == "release",
|
|
||||||
})
|
|
||||||
.collect())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_versions(
|
async fn get_versions(
|
||||||
@@ -45,7 +38,22 @@ impl ModLoaderInstaller for VanillaInstaller {
|
|||||||
_loader_version: &str,
|
_loader_version: &str,
|
||||||
_instance_dir: &Path,
|
_instance_dir: &Path,
|
||||||
_meta_dir: &Path,
|
_meta_dir: &Path,
|
||||||
) -> Result<(), NetError> {
|
) -> Result<(), InstallError> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn game_versions_from_manifest(manifest: mojang::VersionManifest) -> Vec<GameVersion> {
|
||||||
|
manifest
|
||||||
|
.versions
|
||||||
|
.into_iter()
|
||||||
|
.map(|version| GameVersion {
|
||||||
|
id: version.id,
|
||||||
|
stable: version.version_type == "release",
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/loader/vanilla.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -1,141 +0,0 @@
|
|||||||
// 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)]
|
|
||||||
pub struct LogFileEntry {
|
|
||||||
pub name: String,
|
|
||||||
pub path: PathBuf,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn log_dir(instances_dir: &Path, instance_name: &str) -> PathBuf {
|
|
||||||
instances_dir
|
|
||||||
.join(instance_name)
|
|
||||||
.join(".minecraft")
|
|
||||||
.join("logs")
|
|
||||||
.join("launches")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn create_log_file(instances_dir: &Path, instance_name: &str) -> Option<PathBuf> {
|
|
||||||
let dir = log_dir(instances_dir, instance_name);
|
|
||||||
std::fs::create_dir_all(&dir).ok()?;
|
|
||||||
let now = chrono::Local::now().format("%Y-%m-%d_%H-%M-%S");
|
|
||||||
Some(dir.join(format!("{now}.log")))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn scan_log_files(instances_dir: &Path, instance_name: &str) -> Vec<LogFileEntry> {
|
|
||||||
let dir = log_dir(instances_dir, instance_name);
|
|
||||||
|
|
||||||
let read_dir = match std::fs::read_dir(&dir) {
|
|
||||||
Ok(rd) => rd,
|
|
||||||
Err(_) => return Vec::new(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut entries: Vec<LogFileEntry> = read_dir
|
|
||||||
.flatten()
|
|
||||||
.filter_map(|entry| {
|
|
||||||
let path = entry.path();
|
|
||||||
let name = path.file_name()?.to_str()?.to_string();
|
|
||||||
if name.ends_with(".log") {
|
|
||||||
Some(LogFileEntry { name, path })
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
entries.sort_by(|a, b| b.name.cmp(&a.name));
|
|
||||||
entries
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn read_log_file(path: &Path) -> Vec<String> {
|
|
||||||
match std::fs::read_to_string(path) {
|
|
||||||
Ok(content) => content.lines().map(|l| l.to_string()).collect(),
|
|
||||||
Err(_) => Vec::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn setup_log_dir(tmp: &Path, instance: &str) -> PathBuf {
|
|
||||||
let dir = log_dir(tmp, instance);
|
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
|
||||||
dir
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn log_dir_builds_correct_path() {
|
|
||||||
let p = log_dir(Path::new("/instances"), "my-world");
|
|
||||||
assert_eq!(
|
|
||||||
p,
|
|
||||||
PathBuf::from("/instances/my-world/.minecraft/logs/launches")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_log_files_empty_dir() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
setup_log_dir(tmp.path(), "inst");
|
|
||||||
let entries = scan_log_files(tmp.path(), "inst");
|
|
||||||
assert!(entries.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_log_files_finds_logs() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_log_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("2024-01-01_12-00-00.log"), "line1\nline2").unwrap();
|
|
||||||
std::fs::write(dir.join("2024-01-02_12-00-00.log"), "line3").unwrap();
|
|
||||||
let entries = scan_log_files(tmp.path(), "inst");
|
|
||||||
assert_eq!(entries.len(), 2);
|
|
||||||
assert_eq!(entries[0].name, "2024-01-02_12-00-00.log");
|
|
||||||
assert_eq!(entries[1].name, "2024-01-01_12-00-00.log");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_log_files_ignores_non_log() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_log_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("notes.txt"), "not a log").unwrap();
|
|
||||||
std::fs::write(dir.join("real.log"), "log line").unwrap();
|
|
||||||
let entries = scan_log_files(tmp.path(), "inst");
|
|
||||||
assert_eq!(entries.len(), 1);
|
|
||||||
assert_eq!(entries[0].name, "real.log");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_log_files_missing_dir_returns_empty() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let entries = scan_log_files(tmp.path(), "ghost");
|
|
||||||
assert!(entries.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn read_log_file_returns_lines() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let path = tmp.path().join("test.log");
|
|
||||||
std::fs::write(&path, "alpha\nbeta\ngamma").unwrap();
|
|
||||||
let lines = read_log_file(&path);
|
|
||||||
assert_eq!(lines, vec!["alpha", "beta", "gamma"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn read_log_file_missing_returns_empty() {
|
|
||||||
let lines = read_log_file(Path::new("/nonexistent/test.log"));
|
|
||||||
assert!(lines.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn create_log_file_creates_path() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let path = create_log_file(tmp.path(), "inst");
|
|
||||||
assert!(path.is_some());
|
|
||||||
let path = path.unwrap();
|
|
||||||
assert!(path.to_string_lossy().ends_with(".log"));
|
|
||||||
assert!(path.parent().unwrap().exists());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
// 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)]
|
||||||
|
pub struct LogFileEntry {
|
||||||
|
pub name: String,
|
||||||
|
pub path: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn log_dir(instances_dir: &Path, instance_name: &str) -> PathBuf {
|
||||||
|
instances_dir
|
||||||
|
.join(instance_name)
|
||||||
|
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||||
|
.join("logs")
|
||||||
|
.join("launches")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_log_file(instances_dir: &Path, instance_name: &str) -> Option<PathBuf> {
|
||||||
|
let dir = log_dir(instances_dir, instance_name);
|
||||||
|
std::fs::create_dir_all(&dir).ok()?;
|
||||||
|
let now = chrono::Local::now().format("%Y-%m-%d_%H-%M-%S");
|
||||||
|
Some(dir.join(format!("{now}.log")))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn scan_log_files(instances_dir: &Path, instance_name: &str) -> Vec<LogFileEntry> {
|
||||||
|
let dir = log_dir(instances_dir, instance_name);
|
||||||
|
|
||||||
|
let read_dir = match std::fs::read_dir(&dir) {
|
||||||
|
Ok(rd) => rd,
|
||||||
|
Err(_) => return Vec::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut entries: Vec<LogFileEntry> = read_dir
|
||||||
|
.flatten()
|
||||||
|
.filter_map(|entry| {
|
||||||
|
let path = entry.path();
|
||||||
|
let name = path.file_name()?.to_str()?.to_string();
|
||||||
|
if name.ends_with(".log") {
|
||||||
|
Some(LogFileEntry { name, path })
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
entries.sort_by(|a, b| b.name.cmp(&a.name));
|
||||||
|
entries
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn read_log_file(path: &Path) -> Vec<String> {
|
||||||
|
match std::fs::read_to_string(path) {
|
||||||
|
Ok(content) => content.lines().map(|l| l.to_string()).collect(),
|
||||||
|
Err(_) => Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/logs/files.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
// 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};
|
||||||
|
|
||||||
|
use crate::instance::launch::parser::{LogLevel, LogStream, ParsedLogEvent};
|
||||||
|
|
||||||
|
const MAX_LINES: usize = 2000;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct LiveLogLine {
|
||||||
|
pub level: LogLevel,
|
||||||
|
pub stream: LogStream,
|
||||||
|
pub text: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
type LogsMap = Arc<Mutex<HashMap<String, VecDeque<LiveLogLine>>>>;
|
||||||
|
pub static LOGS: LazyLock<LogsMap> = LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
|
||||||
|
|
||||||
|
pub fn push(name: &str, line: impl Into<String>) {
|
||||||
|
push_line(name, LogLevel::Info, LogStream::Stdout, line);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn push_event(name: &str, event: ParsedLogEvent) {
|
||||||
|
for line in event.lines {
|
||||||
|
push_line(name, event.level, event.primary_stream, line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn push_line(name: &str, level: LogLevel, stream: LogStream, line: impl Into<String>) {
|
||||||
|
if let Ok(mut logs) = LOGS.lock() {
|
||||||
|
let buf = logs.entry(name.to_string()).or_insert_with(VecDeque::new);
|
||||||
|
buf.push_back(LiveLogLine {
|
||||||
|
level,
|
||||||
|
stream,
|
||||||
|
text: line.into(),
|
||||||
|
});
|
||||||
|
while buf.len() > MAX_LINES {
|
||||||
|
buf.pop_front();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_entries(name: &str) -> Vec<LiveLogLine> {
|
||||||
|
LOGS.lock()
|
||||||
|
.ok()
|
||||||
|
.and_then(|logs| logs.get(name).map(|buf| buf.iter().cloned().collect()))
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_all(name: &str) -> Vec<String> {
|
||||||
|
LOGS.lock()
|
||||||
|
.ok()
|
||||||
|
.and_then(|logs| {
|
||||||
|
logs.get(name)
|
||||||
|
.map(|buf| buf.iter().map(|line| line.text.clone()).collect())
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear(name: &str) {
|
||||||
|
if let Ok(mut logs) = LOGS.lock() {
|
||||||
|
logs.remove(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/logs/live.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
pub mod files;
|
||||||
|
pub mod live;
|
||||||
+311
-141
@@ -6,6 +6,8 @@ use std::path::PathBuf;
|
|||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
|
use crate::instance::loader::InstallError;
|
||||||
|
use crate::instance::loader::InstallerError;
|
||||||
use crate::instance::models::{InstanceConfig, ModLoader};
|
use crate::instance::models::{InstanceConfig, ModLoader};
|
||||||
|
|
||||||
#[derive(Debug, Error)]
|
#[derive(Debug, Error)]
|
||||||
@@ -20,6 +22,8 @@ pub enum InstanceError {
|
|||||||
Json(#[from] serde_json::Error),
|
Json(#[from] serde_json::Error),
|
||||||
#[error("Download error: {0}")]
|
#[error("Download error: {0}")]
|
||||||
Download(#[from] crate::net::NetError),
|
Download(#[from] crate::net::NetError),
|
||||||
|
#[error("Installer error: {0}")]
|
||||||
|
InstallerError(#[from] InstallerError),
|
||||||
#[error("Invalid instance name: {0}")]
|
#[error("Invalid instance name: {0}")]
|
||||||
InvalidName(String),
|
InvalidName(String),
|
||||||
}
|
}
|
||||||
@@ -33,11 +37,17 @@ pub struct InstanceManager {
|
|||||||
|
|
||||||
impl InstanceManager {
|
impl InstanceManager {
|
||||||
pub fn new(instances_dir: impl Into<PathBuf>, meta_dir: impl Into<PathBuf>) -> Self {
|
pub fn new(instances_dir: impl Into<PathBuf>, meta_dir: impl Into<PathBuf>) -> Self {
|
||||||
InstanceManager {
|
let manager = InstanceManager {
|
||||||
instances_dir: instances_dir.into(),
|
instances_dir: instances_dir.into(),
|
||||||
meta_dir: meta_dir.into(),
|
meta_dir: meta_dir.into(),
|
||||||
client: crate::net::HttpClient::new(),
|
client: crate::net::HttpClient::new(),
|
||||||
}
|
};
|
||||||
|
tracing::trace!(
|
||||||
|
"Created InstanceManager with instances_dir={} meta_dir={}",
|
||||||
|
manager.instances_dir.display(),
|
||||||
|
manager.meta_dir.display()
|
||||||
|
);
|
||||||
|
manager
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn create(
|
pub async fn create(
|
||||||
@@ -51,13 +61,31 @@ impl InstanceManager {
|
|||||||
|
|
||||||
let instance_dir = self.instances_dir.join(name);
|
let instance_dir = self.instances_dir.join(name);
|
||||||
let instance_json = instance_dir.join("instance.json");
|
let instance_json = instance_dir.join("instance.json");
|
||||||
|
tracing::info!(
|
||||||
|
"Creating instance '{}' (Minecraft {}, loader {}, loader_version={})",
|
||||||
|
name,
|
||||||
|
game_version,
|
||||||
|
loader,
|
||||||
|
loader_version.unwrap_or("<none>")
|
||||||
|
);
|
||||||
|
tracing::debug!("Instance directory: {}", instance_dir.display());
|
||||||
|
|
||||||
if instance_json.exists() {
|
if instance_json.exists() {
|
||||||
|
tracing::warn!(
|
||||||
|
"Cannot create instance '{}': {} already exists",
|
||||||
|
name,
|
||||||
|
instance_json.display()
|
||||||
|
);
|
||||||
return Err(InstanceError::AlreadyExists(name.to_string()));
|
return Err(InstanceError::AlreadyExists(name.to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// leftover directory without config = botched previous creation, nuke it
|
// leftover directory without config = botched previous creation, nuke it
|
||||||
if instance_dir.exists() && !instance_json.exists() {
|
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::remove_dir_all(&instance_dir)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,7 +97,22 @@ impl InstanceManager {
|
|||||||
|
|
||||||
// clean up on failure so there's no half-baked instance left around
|
// clean up on failure so there's no half-baked instance left around
|
||||||
if result.is_err() {
|
if result.is_err() {
|
||||||
let _ = std::fs::remove_dir_all(&instance_dir);
|
tracing::debug!(
|
||||||
|
"Cleaning up incomplete instance '{}' after creation failed",
|
||||||
|
name
|
||||||
|
);
|
||||||
|
if let Err(cleanup_error) = std::fs::remove_dir_all(&instance_dir) {
|
||||||
|
tracing::warn!(
|
||||||
|
"Failed to clean up incomplete instance directory {}: {}",
|
||||||
|
instance_dir.display(),
|
||||||
|
cleanup_error
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
tracing::debug!(
|
||||||
|
"Cleaned up incomplete instance directory {}",
|
||||||
|
instance_dir.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
result
|
result
|
||||||
@@ -83,58 +126,100 @@ impl InstanceManager {
|
|||||||
loader_version: Option<&str>,
|
loader_version: Option<&str>,
|
||||||
instance_dir: &std::path::Path,
|
instance_dir: &std::path::Path,
|
||||||
) -> Result<InstanceConfig, InstanceError> {
|
) -> Result<InstanceConfig, InstanceError> {
|
||||||
let minecraft_dir = instance_dir.join(".minecraft");
|
let minecraft_dir = instance_dir.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||||
|
tracing::debug!(
|
||||||
|
"Preparing Minecraft directory for '{}': {}",
|
||||||
|
name,
|
||||||
|
minecraft_dir.display()
|
||||||
|
);
|
||||||
for subdir in &["mods", "config", "resourcepacks", "shaderpacks", "saves"] {
|
for subdir in &["mods", "config", "resourcepacks", "shaderpacks", "saves"] {
|
||||||
std::fs::create_dir_all(minecraft_dir.join(subdir))?;
|
let path = minecraft_dir.join(subdir);
|
||||||
|
std::fs::create_dir_all(&path)?;
|
||||||
|
tracing::trace!("Ensured instance subdirectory {}", path.display());
|
||||||
}
|
}
|
||||||
|
|
||||||
// forge insists on this file existing, even if it's empty json. thanks forge.
|
// forge insists on this file existing, even if it's empty json. thanks forge.
|
||||||
let launcher_profiles_path = minecraft_dir.join("launcher_profiles.json");
|
let launcher_profiles_path = minecraft_dir.join("launcher_profiles.json");
|
||||||
if !launcher_profiles_path.exists() {
|
if !launcher_profiles_path.exists() {
|
||||||
std::fs::write(&launcher_profiles_path, "{}")?;
|
std::fs::write(&launcher_profiles_path, "{}")?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Created launcher_profiles.json for '{}': {}",
|
||||||
|
name,
|
||||||
|
launcher_profiles_path.display()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let metadata_paths = crate::storage::MetadataPaths::new(&self.meta_dir);
|
||||||
for meta_subdir in &[
|
for meta_subdir in &[
|
||||||
self.meta_dir.join("versions"),
|
metadata_paths.versions(),
|
||||||
self.meta_dir.join("libraries"),
|
metadata_paths.libraries(),
|
||||||
self.meta_dir.join("assets").join("objects"),
|
metadata_paths.assets().join("objects"),
|
||||||
self.meta_dir.join("assets").join("indexes"),
|
metadata_paths.assets().join("indexes"),
|
||||||
] {
|
] {
|
||||||
std::fs::create_dir_all(meta_subdir)?;
|
std::fs::create_dir_all(meta_subdir)?;
|
||||||
|
tracing::trace!("Ensured metadata directory {}", meta_subdir.display());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
tracing::debug!("Fetching Mojang version manifest for '{}'", name);
|
||||||
let manifest = crate::net::mojang::fetch_version_manifest(&self.client).await?;
|
let manifest = crate::net::mojang::fetch_version_manifest(&self.client).await?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Loaded Mojang manifest with {} version(s); latest release={} snapshot={}",
|
||||||
|
manifest.versions.len(),
|
||||||
|
manifest.latest.release,
|
||||||
|
manifest.latest.snapshot
|
||||||
|
);
|
||||||
|
|
||||||
let version_entry = match manifest.versions.iter().find(|v| v.id == game_version) {
|
let version_entry = match manifest.versions.iter().find(|v| v.id == game_version) {
|
||||||
Some(v) => v,
|
Some(v) => {
|
||||||
|
tracing::debug!(
|
||||||
|
"Resolved Minecraft version '{}' as {} entry",
|
||||||
|
game_version,
|
||||||
|
v.version_type
|
||||||
|
);
|
||||||
|
v
|
||||||
|
}
|
||||||
None => {
|
None => {
|
||||||
return Err(InstanceError::InvalidName(format!(
|
return Err(InstanceError::InvalidName(format!(
|
||||||
"Minecraft version '{}' not found in manifest",
|
"Minecraft version '{}' not found in manifest with {} entries",
|
||||||
game_version
|
game_version,
|
||||||
|
manifest.versions.len()
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let version_meta =
|
let (version_meta, raw_meta_bytes) =
|
||||||
crate::net::mojang::fetch_version_meta(&self.client, version_entry).await?;
|
crate::net::mojang::fetch_version_meta_with_raw(&self.client, version_entry).await?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Fetched version meta '{}' with {} libraries and asset index {}",
|
||||||
|
version_meta.id,
|
||||||
|
version_meta.libraries.len(),
|
||||||
|
version_meta.asset_index.id
|
||||||
|
);
|
||||||
|
|
||||||
crate::net::mojang::download_client_jar(&self.client, &version_meta, &self.meta_dir)
|
crate::net::mojang::download_client_jar(&self.client, &version_meta, &self.meta_dir)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
let meta_json_path = self
|
let meta_json_path = metadata_paths
|
||||||
.meta_dir
|
.versions()
|
||||||
.join("versions")
|
|
||||||
.join(game_version)
|
.join(game_version)
|
||||||
.join("meta.json");
|
.join("meta.json");
|
||||||
match serde_json::to_string_pretty(&version_meta) {
|
if let Some(parent) = meta_json_path.parent()
|
||||||
Ok(json) => {
|
&& let Err(e) = std::fs::create_dir_all(parent)
|
||||||
if let Err(e) = std::fs::write(&meta_json_path, &json) {
|
{
|
||||||
tracing::warn!("Failed to save version meta: {}", e);
|
tracing::warn!(
|
||||||
}
|
"Failed to ensure meta dir {} exists: {}",
|
||||||
}
|
parent.display(),
|
||||||
Err(e) => {
|
e
|
||||||
tracing::warn!("Failed to serialize version meta: {}", e);
|
);
|
||||||
}
|
}
|
||||||
|
if let Err(e) = std::fs::write(&meta_json_path, &raw_meta_bytes) {
|
||||||
|
tracing::warn!(
|
||||||
|
"Failed to save version meta {}: {}",
|
||||||
|
meta_json_path.display(),
|
||||||
|
e
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
tracing::debug!("Saved version meta to {}", meta_json_path.display());
|
||||||
}
|
}
|
||||||
|
|
||||||
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?;
|
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?;
|
||||||
@@ -152,6 +237,12 @@ impl InstanceManager {
|
|||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
tracing::debug!(
|
||||||
|
"Installing loader {} {} for instance '{}'",
|
||||||
|
loader,
|
||||||
|
effective_loader_version,
|
||||||
|
name
|
||||||
|
);
|
||||||
installer
|
installer
|
||||||
.install(
|
.install(
|
||||||
&self.client,
|
&self.client,
|
||||||
@@ -160,7 +251,13 @@ impl InstanceManager {
|
|||||||
instance_dir,
|
instance_dir,
|
||||||
&self.meta_dir,
|
&self.meta_dir,
|
||||||
)
|
)
|
||||||
.await?;
|
.await
|
||||||
|
.map_err(|e| match e {
|
||||||
|
InstallError::Download(net_error) => InstanceError::Download(net_error),
|
||||||
|
InstallError::Installer(installer_error) => {
|
||||||
|
InstanceError::InstallerError(installer_error)
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
|
||||||
let config = InstanceConfig {
|
let config = InstanceConfig {
|
||||||
name: name.to_string(),
|
name: name.to_string(),
|
||||||
@@ -174,20 +271,132 @@ impl InstanceManager {
|
|||||||
memory_min: None,
|
memory_min: None,
|
||||||
jvm_args: vec![],
|
jvm_args: vec![],
|
||||||
resolution: None,
|
resolution: None,
|
||||||
|
config_sync_profile: None,
|
||||||
|
modpack_source: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
self.save(&config)?;
|
self.save(&config)?;
|
||||||
|
tracing::info!("Created instance '{}'", name);
|
||||||
|
|
||||||
crate::tui::progress::clear();
|
crate::feedback::progress::clear();
|
||||||
Ok(config)
|
Ok(config)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn repair_runtime_cache(&self, config: &InstanceConfig) -> Result<(), InstanceError> {
|
||||||
|
let task = crate::feedback::progress::ProgressTask::start(format!(
|
||||||
|
"Rebuilding runtime for '{}'",
|
||||||
|
config.name
|
||||||
|
));
|
||||||
|
task.set_sub_action(format!("Minecraft {}", config.game_version));
|
||||||
|
let metadata_paths = crate::storage::MetadataPaths::new(&self.meta_dir);
|
||||||
|
for directory in [
|
||||||
|
metadata_paths.versions(),
|
||||||
|
metadata_paths.libraries(),
|
||||||
|
metadata_paths.assets().join("objects"),
|
||||||
|
metadata_paths.assets().join("indexes"),
|
||||||
|
metadata_paths.loader_profiles(),
|
||||||
|
] {
|
||||||
|
std::fs::create_dir_all(directory)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let meta_path = metadata_paths
|
||||||
|
.versions()
|
||||||
|
.join(&config.game_version)
|
||||||
|
.join("meta.json");
|
||||||
|
let (version_meta, raw_meta) = if meta_path.exists() {
|
||||||
|
let raw = std::fs::read(&meta_path)?;
|
||||||
|
let parsed = serde_json::from_slice(&raw).map_err(|error| {
|
||||||
|
InstanceError::InvalidName(format!(
|
||||||
|
"Cached metadata for Minecraft {} is invalid: {error}",
|
||||||
|
config.game_version
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
(parsed, raw)
|
||||||
|
} else {
|
||||||
|
let manifest = crate::net::mojang::fetch_version_manifest(&self.client).await?;
|
||||||
|
let version_entry = manifest
|
||||||
|
.versions
|
||||||
|
.iter()
|
||||||
|
.find(|version| version.id == config.game_version)
|
||||||
|
.ok_or_else(|| {
|
||||||
|
InstanceError::InvalidName(format!(
|
||||||
|
"Minecraft version '{}' is no longer present in Mojang's manifest",
|
||||||
|
config.game_version
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
crate::net::mojang::fetch_version_meta_with_raw(&self.client, version_entry).await?
|
||||||
|
};
|
||||||
|
crate::net::mojang::download_client_jar(&self.client, &version_meta, &self.meta_dir)
|
||||||
|
.await?;
|
||||||
|
if let Some(parent) = meta_path.parent() {
|
||||||
|
std::fs::create_dir_all(parent)?;
|
||||||
|
}
|
||||||
|
if !meta_path.exists() {
|
||||||
|
crate::storage::write_atomic(&meta_path, &raw_meta)?;
|
||||||
|
}
|
||||||
|
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?;
|
||||||
|
crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await?;
|
||||||
|
|
||||||
|
if config.loader != ModLoader::Vanilla {
|
||||||
|
let loader_version = config.loader_version.as_deref().ok_or_else(|| {
|
||||||
|
InstanceError::InvalidName(format!(
|
||||||
|
"Instance '{}' has no {} loader version",
|
||||||
|
config.name, config.loader
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
let profile_name = match config.loader {
|
||||||
|
ModLoader::Fabric => {
|
||||||
|
format!("fabric-{}-{loader_version}.json", config.game_version)
|
||||||
|
}
|
||||||
|
ModLoader::Quilt => {
|
||||||
|
format!("quilt-{}-{loader_version}.json", config.game_version)
|
||||||
|
}
|
||||||
|
ModLoader::Forge => {
|
||||||
|
format!("forge-{}-{loader_version}.json", config.game_version)
|
||||||
|
}
|
||||||
|
ModLoader::NeoForge => format!("neoforge-{loader_version}.json"),
|
||||||
|
ModLoader::Vanilla => unreachable!(),
|
||||||
|
};
|
||||||
|
if !metadata_paths.loader_profiles().join(profile_name).exists() {
|
||||||
|
task.set_sub_action(format!("{} {}", config.loader, loader_version));
|
||||||
|
crate::instance::loader::get_installer(config.loader)
|
||||||
|
.install(
|
||||||
|
&self.client,
|
||||||
|
&config.game_version,
|
||||||
|
loader_version,
|
||||||
|
&self.instances_dir.join(&config.name),
|
||||||
|
&self.meta_dir,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|error| match error {
|
||||||
|
InstallError::Download(error) => InstanceError::Download(error),
|
||||||
|
InstallError::Installer(error) => InstanceError::InstallerError(error),
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
task.finish();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn delete(&self, name: &str) -> Result<(), InstanceError> {
|
pub fn delete(&self, name: &str) -> Result<(), InstanceError> {
|
||||||
let instance_dir = self.instances_dir.join(name);
|
let instance_dir = self.instances_dir.join(name);
|
||||||
if !instance_dir.exists() {
|
if !instance_dir.exists() {
|
||||||
|
tracing::warn!(
|
||||||
|
"Cannot delete missing instance '{}': {}",
|
||||||
|
name,
|
||||||
|
instance_dir.display()
|
||||||
|
);
|
||||||
return Err(InstanceError::NotFound(name.to_string()));
|
return Err(InstanceError::NotFound(name.to_string()));
|
||||||
}
|
}
|
||||||
std::fs::remove_dir_all(&instance_dir)?;
|
tracing::info!("Deleting instance '{}' at {}", name, instance_dir.display());
|
||||||
|
if let Err(e) = std::fs::remove_dir_all(&instance_dir) {
|
||||||
|
tracing::error!(
|
||||||
|
"Failed to delete instance directory {}: {}",
|
||||||
|
instance_dir.display(),
|
||||||
|
e
|
||||||
|
);
|
||||||
|
return Err(e.into());
|
||||||
|
}
|
||||||
if let Err(e) = crate::instance::desktop::remove(name) {
|
if let Err(e) = crate::instance::desktop::remove(name) {
|
||||||
tracing::warn!("Failed to remove desktop shortcut for '{}': {}", name, e);
|
tracing::warn!("Failed to remove desktop shortcut for '{}': {}", name, e);
|
||||||
}
|
}
|
||||||
@@ -197,22 +406,44 @@ impl InstanceManager {
|
|||||||
pub fn rename(&self, old_name: &str, new_name: &str) -> Result<(), InstanceError> {
|
pub fn rename(&self, old_name: &str, new_name: &str) -> Result<(), InstanceError> {
|
||||||
let new_name = new_name.trim();
|
let new_name = new_name.trim();
|
||||||
if new_name.is_empty() {
|
if new_name.is_empty() {
|
||||||
|
tracing::warn!("Cannot rename instance '{}': new name is empty", old_name);
|
||||||
return Err(InstanceError::InvalidName(
|
return Err(InstanceError::InvalidName(
|
||||||
"Name cannot be empty".to_string(),
|
"Name cannot be empty".to_string(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
if old_name == new_name {
|
if old_name == new_name {
|
||||||
|
tracing::debug!("Ignoring no-op instance rename '{}'", old_name);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let old_dir = self.instances_dir.join(old_name);
|
let old_dir = self.instances_dir.join(old_name);
|
||||||
let new_dir = self.instances_dir.join(new_name);
|
let new_dir = self.instances_dir.join(new_name);
|
||||||
if !old_dir.exists() {
|
if !old_dir.exists() {
|
||||||
|
tracing::warn!(
|
||||||
|
"Cannot rename missing instance '{}': {}",
|
||||||
|
old_name,
|
||||||
|
old_dir.display()
|
||||||
|
);
|
||||||
return Err(InstanceError::NotFound(old_name.to_string()));
|
return Err(InstanceError::NotFound(old_name.to_string()));
|
||||||
}
|
}
|
||||||
if new_dir.exists() {
|
if new_dir.exists() {
|
||||||
|
tracing::warn!(
|
||||||
|
"Cannot rename instance '{}' to '{}': destination exists at {}",
|
||||||
|
old_name,
|
||||||
|
new_name,
|
||||||
|
new_dir.display()
|
||||||
|
);
|
||||||
return Err(InstanceError::AlreadyExists(new_name.to_string()));
|
return Err(InstanceError::AlreadyExists(new_name.to_string()));
|
||||||
}
|
}
|
||||||
std::fs::rename(&old_dir, &new_dir)?;
|
tracing::info!("Renaming instance '{}' to '{}'", old_name, new_name);
|
||||||
|
if let Err(e) = std::fs::rename(&old_dir, &new_dir) {
|
||||||
|
tracing::error!(
|
||||||
|
"Failed to rename instance directory {} to {}: {}",
|
||||||
|
old_dir.display(),
|
||||||
|
new_dir.display(),
|
||||||
|
e
|
||||||
|
);
|
||||||
|
return Err(e.into());
|
||||||
|
}
|
||||||
|
|
||||||
let config_path = new_dir.join("instance.json");
|
let config_path = new_dir.join("instance.json");
|
||||||
if let Ok(data) = std::fs::read_to_string(&config_path)
|
if let Ok(data) = std::fs::read_to_string(&config_path)
|
||||||
@@ -225,6 +456,11 @@ impl InstanceManager {
|
|||||||
if let Err(e) = crate::instance::desktop::rename(old_name, &config) {
|
if let Err(e) = crate::instance::desktop::rename(old_name, &config) {
|
||||||
tracing::warn!("Failed to rename desktop shortcut: {}", e);
|
tracing::warn!("Failed to rename desktop shortcut: {}", e);
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
tracing::warn!(
|
||||||
|
"Renamed instance directory but could not update config at {}",
|
||||||
|
config_path.display()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -232,10 +468,15 @@ impl InstanceManager {
|
|||||||
|
|
||||||
pub fn load_all(&self) -> Vec<InstanceConfig> {
|
pub fn load_all(&self) -> Vec<InstanceConfig> {
|
||||||
let mut instances = vec![];
|
let mut instances = vec![];
|
||||||
|
tracing::debug!("Loading instances from {}", self.instances_dir.display());
|
||||||
let read_dir = match std::fs::read_dir(&self.instances_dir) {
|
let read_dir = match std::fs::read_dir(&self.instances_dir) {
|
||||||
Ok(rd) => rd,
|
Ok(rd) => rd,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::error!("Failed to read instances directory: {}", e);
|
tracing::error!(
|
||||||
|
"Failed to read instances directory {}: {}",
|
||||||
|
self.instances_dir.display(),
|
||||||
|
e
|
||||||
|
);
|
||||||
return instances;
|
return instances;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -249,6 +490,7 @@ impl InstanceManager {
|
|||||||
};
|
};
|
||||||
let config_path = entry.path().join("instance.json");
|
let config_path = entry.path().join("instance.json");
|
||||||
if !config_path.exists() {
|
if !config_path.exists() {
|
||||||
|
tracing::trace!("Skipping non-instance directory {}", entry.path().display());
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let contents = match std::fs::read_to_string(&config_path) {
|
let contents = match std::fs::read_to_string(&config_path) {
|
||||||
@@ -265,6 +507,7 @@ impl InstanceManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
tracing::debug!("Loaded {} instance(s)", instances.len());
|
||||||
instances
|
instances
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -273,11 +516,39 @@ impl InstanceManager {
|
|||||||
|
|
||||||
let config_path = self.instances_dir.join(name).join("instance.json");
|
let config_path = self.instances_dir.join(name).join("instance.json");
|
||||||
if !config_path.exists() {
|
if !config_path.exists() {
|
||||||
|
tracing::warn!(
|
||||||
|
"Instance '{}' config is missing at {}",
|
||||||
|
name,
|
||||||
|
config_path.display()
|
||||||
|
);
|
||||||
return Err(InstanceError::NotFound(name.to_string()));
|
return Err(InstanceError::NotFound(name.to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
let contents = std::fs::read_to_string(&config_path)?;
|
tracing::debug!("Loading instance '{}' from {}", name, config_path.display());
|
||||||
Ok(serde_json::from_str::<InstanceConfig>(&contents)?)
|
let contents = match std::fs::read_to_string(&config_path) {
|
||||||
|
Ok(contents) => contents,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(
|
||||||
|
"Failed to read instance '{}' config {}: {}",
|
||||||
|
name,
|
||||||
|
config_path.display(),
|
||||||
|
e
|
||||||
|
);
|
||||||
|
return Err(e.into());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match serde_json::from_str::<InstanceConfig>(&contents) {
|
||||||
|
Ok(config) => Ok(config),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!(
|
||||||
|
"Failed to parse instance '{}' config {}: {}",
|
||||||
|
name,
|
||||||
|
config_path.display(),
|
||||||
|
e
|
||||||
|
);
|
||||||
|
Err(e.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn save(&self, instance: &InstanceConfig) -> Result<(), InstanceError> {
|
pub fn save(&self, instance: &InstanceConfig) -> Result<(), InstanceError> {
|
||||||
@@ -285,12 +556,18 @@ impl InstanceManager {
|
|||||||
let config_path = instance_dir.join("instance.json");
|
let config_path = instance_dir.join("instance.json");
|
||||||
let json = serde_json::to_string_pretty(instance)?;
|
let json = serde_json::to_string_pretty(instance)?;
|
||||||
std::fs::write(&config_path, &json)?;
|
std::fs::write(&config_path, &json)?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Saved instance '{}' config to {}",
|
||||||
|
instance.name,
|
||||||
|
config_path.display()
|
||||||
|
);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn touch_last_played(&self, name: &str) -> Result<(), InstanceError> {
|
pub fn touch_last_played(&self, name: &str) -> Result<(), InstanceError> {
|
||||||
let mut config = self.load_one(name)?;
|
let mut config = self.load_one(name)?;
|
||||||
config.last_played = Some(chrono::Utc::now());
|
config.last_played = Some(chrono::Utc::now());
|
||||||
|
tracing::debug!("Updating last_played for '{}'", name);
|
||||||
self.save(&config)
|
self.save(&config)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -313,112 +590,5 @@ fn validate_name(name: &str) -> Result<(), InstanceError> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/manager.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
use crate::instance::models::ModLoader;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
fn test_manager() -> (InstanceManager, PathBuf) {
|
|
||||||
let tmp = std::env::temp_dir().join(format!("rmcl_test_{}", uuid_like()));
|
|
||||||
let meta = std::env::temp_dir().join(format!("rmcl_meta_test_{}", uuid_like()));
|
|
||||||
std::fs::create_dir_all(&tmp).ok();
|
|
||||||
std::fs::create_dir_all(&meta).ok();
|
|
||||||
(InstanceManager::new(tmp.clone(), meta), tmp)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn uuid_like() -> String {
|
|
||||||
format!(
|
|
||||||
"{:x}",
|
|
||||||
std::time::SystemTime::now()
|
|
||||||
.duration_since(std::time::UNIX_EPOCH)
|
|
||||||
.map(|d| d.as_nanos())
|
|
||||||
.unwrap_or(0)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_validate_name_valid() {
|
|
||||||
assert!(validate_name("my-instance").is_ok());
|
|
||||||
assert!(validate_name("test_world").is_ok());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_validate_name_invalid() {
|
|
||||||
assert!(validate_name("").is_err());
|
|
||||||
assert!(validate_name("path/traversal").is_err());
|
|
||||||
assert!(validate_name(".hidden").is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_delete_nonexistent() {
|
|
||||||
let (manager, tmp) = test_manager();
|
|
||||||
let result = manager.delete("ghost-instance");
|
|
||||||
assert!(matches!(result, Err(InstanceError::NotFound(_))));
|
|
||||||
std::fs::remove_dir_all(&tmp).ok();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_save_and_load_all() {
|
|
||||||
let (manager, tmp) = test_manager();
|
|
||||||
let instance_dir = tmp.join("test-save");
|
|
||||||
std::fs::create_dir_all(&instance_dir).ok();
|
|
||||||
|
|
||||||
let config = InstanceConfig {
|
|
||||||
name: "test-save".to_string(),
|
|
||||||
game_version: "1.20.1".to_string(),
|
|
||||||
loader: ModLoader::Vanilla,
|
|
||||||
loader_version: None,
|
|
||||||
created: chrono::Utc::now(),
|
|
||||||
last_played: None,
|
|
||||||
java_path: None,
|
|
||||||
memory_max: None,
|
|
||||||
memory_min: None,
|
|
||||||
jvm_args: vec![],
|
|
||||||
resolution: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
manager.save(&config).expect("save failed");
|
|
||||||
|
|
||||||
let all = manager.load_all();
|
|
||||||
assert_eq!(all.len(), 1);
|
|
||||||
assert_eq!(all[0].name, "test-save");
|
|
||||||
assert_eq!(all[0].game_version, "1.20.1");
|
|
||||||
|
|
||||||
std::fs::remove_dir_all(&tmp).ok();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_load_all_accepts_numeric_memory() {
|
|
||||||
let (manager, tmp) = test_manager();
|
|
||||||
let instance_dir = tmp.join("test-memory");
|
|
||||||
std::fs::create_dir_all(&instance_dir).ok();
|
|
||||||
std::fs::write(
|
|
||||||
instance_dir.join("instance.json"),
|
|
||||||
r#"{
|
|
||||||
"name": "test-memory",
|
|
||||||
"game_version": "1.7.10",
|
|
||||||
"loader": "forge",
|
|
||||||
"loader_version": "10.13.4.1614",
|
|
||||||
"created": "2026-04-20T18:04:25.567993893Z",
|
|
||||||
"memory_max": 8,
|
|
||||||
"memory_min": 512
|
|
||||||
}"#,
|
|
||||||
)
|
|
||||||
.expect("write config");
|
|
||||||
|
|
||||||
let all = manager.load_all();
|
|
||||||
assert_eq!(all.len(), 1);
|
|
||||||
assert_eq!(all[0].memory_max.as_deref(), Some("8G"));
|
|
||||||
assert_eq!(all[0].memory_min.as_deref(), Some("512M"));
|
|
||||||
|
|
||||||
std::fs::remove_dir_all(&tmp).ok();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_load_one_not_found() {
|
|
||||||
let (manager, tmp) = test_manager();
|
|
||||||
let result = manager.load_one("ghost-instance");
|
|
||||||
assert!(matches!(result, Err(InstanceError::NotFound(_))));
|
|
||||||
std::fs::remove_dir_all(&tmp).ok();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+10
-6
@@ -1,21 +1,25 @@
|
|||||||
// instance management: creation, launching, importing modpacks, and all the
|
// instance management: creation, launching, importing modpacks, and all the
|
||||||
// bookkeeping that comes with pretending to be a real launcher
|
// bookkeeping that comes with pretending to be a real launcher
|
||||||
|
|
||||||
|
pub mod config_sync;
|
||||||
pub mod content;
|
pub mod content;
|
||||||
pub mod desktop;
|
pub mod desktop;
|
||||||
pub mod import;
|
pub mod import;
|
||||||
|
pub mod java;
|
||||||
pub mod launch;
|
pub mod launch;
|
||||||
pub mod loader;
|
pub mod loader;
|
||||||
pub mod log_files;
|
pub mod logs;
|
||||||
pub mod manager;
|
pub mod manager;
|
||||||
pub mod models;
|
pub mod models;
|
||||||
|
pub mod runtime;
|
||||||
pub mod screenshots;
|
pub mod screenshots;
|
||||||
|
|
||||||
|
pub use content::manifest::{
|
||||||
|
ContentFileRecord, ContentKind, ContentManifest, FileFingerprint, ProviderProject, Resolution,
|
||||||
|
};
|
||||||
pub use content::{
|
pub use content::{
|
||||||
ContentEntry, toggle_entry,
|
scan_mods, scan_one_datapack, scan_one_mod, scan_one_resource_pack, scan_one_shader,
|
||||||
scan_mods, scan_one_mod,
|
scan_one_world, scan_resource_packs, scan_shaders, scan_worlds,
|
||||||
scan_resource_packs, scan_one_resource_pack,
|
|
||||||
scan_shaders, scan_one_shader,
|
|
||||||
scan_worlds, scan_one_world,
|
|
||||||
};
|
};
|
||||||
pub use launch::LaunchError;
|
pub use launch::LaunchError;
|
||||||
pub use loader::{GameVersion, ModLoaderInstaller, VanillaInstaller, get_installer};
|
pub use loader::{GameVersion, ModLoaderInstaller, VanillaInstaller, get_installer};
|
||||||
|
|||||||
+6
-80
@@ -47,6 +47,10 @@ pub struct InstanceConfig {
|
|||||||
pub jvm_args: Vec<String>,
|
pub jvm_args: Vec<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub resolution: Option<(u32, u32)>,
|
pub resolution: Option<(u32, u32)>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub config_sync_profile: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub modpack_source: Option<crate::instance::ProviderProject>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn normalize_memory_value(raw: &str) -> Option<String> {
|
pub fn normalize_memory_value(raw: &str) -> Option<String> {
|
||||||
@@ -120,83 +124,5 @@ fn memory_number_to_string(value: u64) -> Option<String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/models.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_instance_config_roundtrip() {
|
|
||||||
let config = InstanceConfig {
|
|
||||||
name: "test".to_string(),
|
|
||||||
game_version: "1.20.1".to_string(),
|
|
||||||
loader: ModLoader::Fabric,
|
|
||||||
loader_version: Some("0.15.0".to_string()),
|
|
||||||
created: Utc::now(),
|
|
||||||
last_played: None,
|
|
||||||
java_path: None,
|
|
||||||
memory_max: Some("4G".to_string()),
|
|
||||||
memory_min: Some("512M".to_string()),
|
|
||||||
jvm_args: vec![],
|
|
||||||
resolution: Some((1920, 1080)),
|
|
||||||
};
|
|
||||||
let json = serde_json::to_string_pretty(&config).expect("serialize");
|
|
||||||
let parsed: InstanceConfig = serde_json::from_str(&json).expect("deserialize");
|
|
||||||
assert_eq!(parsed.name, config.name);
|
|
||||||
assert_eq!(parsed.game_version, config.game_version);
|
|
||||||
assert_eq!(parsed.loader, config.loader);
|
|
||||||
assert_eq!(parsed.resolution, config.resolution);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn instance_config_accepts_numeric_memory() {
|
|
||||||
let json = r#"
|
|
||||||
{
|
|
||||||
"name": "test",
|
|
||||||
"game_version": "1.7.10",
|
|
||||||
"loader": "forge",
|
|
||||||
"loader_version": "10.13.4.1614",
|
|
||||||
"created": "2026-04-20T18:04:25.567993893Z",
|
|
||||||
"memory_max": 8,
|
|
||||||
"memory_min": 512
|
|
||||||
}
|
|
||||||
"#;
|
|
||||||
let parsed: InstanceConfig = serde_json::from_str(json).expect("deserialize");
|
|
||||||
assert_eq!(parsed.memory_max.as_deref(), Some("8G"));
|
|
||||||
assert_eq!(parsed.memory_min.as_deref(), Some("512M"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn normalize_memory_value_handles_bare_numbers() {
|
|
||||||
assert_eq!(normalize_memory_value("8").as_deref(), Some("8G"));
|
|
||||||
assert_eq!(normalize_memory_value("4096").as_deref(), Some("4096M"));
|
|
||||||
assert_eq!(normalize_memory_value("8G").as_deref(), Some("8G"));
|
|
||||||
assert_eq!(normalize_memory_value("2048m").as_deref(), Some("2048M"));
|
|
||||||
assert_eq!(normalize_memory_value(""), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn instance_config_ignores_invalid_memory_values() {
|
|
||||||
let json = r#"
|
|
||||||
{
|
|
||||||
"name": "test",
|
|
||||||
"game_version": "1.7.10",
|
|
||||||
"loader": "forge",
|
|
||||||
"loader_version": "10.13.4.1614",
|
|
||||||
"created": "2026-04-20T18:04:25.567993893Z",
|
|
||||||
"memory_max": ["8G"],
|
|
||||||
"memory_min": "8GB"
|
|
||||||
}
|
|
||||||
"#;
|
|
||||||
let parsed: InstanceConfig = serde_json::from_str(json).expect("deserialize");
|
|
||||||
assert_eq!(parsed.memory_max, None);
|
|
||||||
assert_eq!(parsed.memory_min, None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn normalize_memory_value_rejects_invalid_values() {
|
|
||||||
assert_eq!(normalize_memory_value("0"), None);
|
|
||||||
assert_eq!(normalize_memory_value("-1"), None);
|
|
||||||
assert_eq!(normalize_memory_value("1.5G"), None);
|
|
||||||
assert_eq!(normalize_memory_value("8GB"), None);
|
|
||||||
assert_eq!(normalize_memory_value("banana"), None);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -33,12 +33,14 @@ pub static KILL_SENDERS: LazyLock<KillSenders> =
|
|||||||
pub fn set_state(name: &str, state: RunState) {
|
pub fn set_state(name: &str, state: RunState) {
|
||||||
if let Ok(mut map) = RUNNING.lock() {
|
if let Ok(mut map) = RUNNING.lock() {
|
||||||
map.insert(name.to_string(), state);
|
map.insert(name.to_string(), state);
|
||||||
|
crate::feedback::request_redraw();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn remove(name: &str) {
|
pub fn remove(name: &str) {
|
||||||
if let Ok(mut map) = RUNNING.lock() {
|
if let Ok(mut map) = RUNNING.lock() {
|
||||||
map.remove(name);
|
map.remove(name);
|
||||||
|
crate::feedback::request_redraw();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,9 +58,22 @@ pub fn all() -> Vec<(String, RunState)> {
|
|||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn has_active() -> bool {
|
||||||
|
RUNNING.lock().is_ok_and(|map| {
|
||||||
|
map.values().any(|state| {
|
||||||
|
matches!(
|
||||||
|
state,
|
||||||
|
RunState::Authenticating | RunState::Starting | RunState::Running
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
pub fn push_last_played(name: &str, time: DateTime<Utc>) {
|
pub fn push_last_played(name: &str, time: DateTime<Utc>) {
|
||||||
if let Ok(mut q) = PENDING_LAST_PLAYED.lock() {
|
if let Ok(mut q) = PENDING_LAST_PLAYED.lock() {
|
||||||
q.push((name.to_string(), time));
|
q.push((name.to_string(), time));
|
||||||
|
crate::feedback::request_redraw();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,80 +108,5 @@ pub fn cleanup_kill_sender(name: &str) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/runtime.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn set_and_get_state() {
|
|
||||||
set_state("run_test_1", RunState::Starting);
|
|
||||||
assert_eq!(get("run_test_1"), Some(RunState::Starting));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn get_missing_returns_none() {
|
|
||||||
assert_eq!(get("run_never_set_xyz"), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn remove_clears_state() {
|
|
||||||
set_state("run_test_2", RunState::Running);
|
|
||||||
remove("run_test_2");
|
|
||||||
assert_eq!(get("run_test_2"), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn set_state_overwrites() {
|
|
||||||
set_state("run_test_3", RunState::Starting);
|
|
||||||
set_state("run_test_3", RunState::Running);
|
|
||||||
assert_eq!(get("run_test_3"), Some(RunState::Running));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn all_returns_entries() {
|
|
||||||
set_state("run_test_all_a", RunState::Running);
|
|
||||||
let entries = all();
|
|
||||||
assert!(entries.iter().any(|(k, _)| k == "run_test_all_a"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn crashed_state_stores_exit_code() {
|
|
||||||
set_state("run_test_crash", RunState::Crashed(Some(1)));
|
|
||||||
assert_eq!(get("run_test_crash"), Some(RunState::Crashed(Some(1))));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn push_and_drain_last_played() {
|
|
||||||
let time = Utc::now();
|
|
||||||
push_last_played("run_test_lp", time);
|
|
||||||
let drained = drain_last_played();
|
|
||||||
assert!(drained.iter().any(|(k, _)| k == "run_test_lp"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn drain_empty_returns_empty() {
|
|
||||||
let _ = drain_last_played();
|
|
||||||
let drained = drain_last_played();
|
|
||||||
assert!(drained.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn send_kill_returns_false_for_missing() {
|
|
||||||
assert!(!send_kill("run_never_registered_xyz"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn register_and_send_kill() {
|
|
||||||
let (tx, mut rx) = tokio::sync::oneshot::channel::<()>();
|
|
||||||
register_kill("run_test_kill", tx);
|
|
||||||
assert!(send_kill("run_test_kill"));
|
|
||||||
let _ = rx.try_recv();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn cleanup_kill_sender_removes() {
|
|
||||||
let (tx, _rx) = tokio::sync::oneshot::channel::<()>();
|
|
||||||
register_kill("run_test_cleanup", tx);
|
|
||||||
cleanup_kill_sender("run_test_cleanup");
|
|
||||||
assert!(!send_kill("run_test_cleanup"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -14,7 +14,7 @@ pub struct ScreenshotEntry {
|
|||||||
pub fn scan_screenshots(instances_dir: &Path, instance_name: &str) -> Vec<ScreenshotEntry> {
|
pub fn scan_screenshots(instances_dir: &Path, instance_name: &str) -> Vec<ScreenshotEntry> {
|
||||||
let dir = instances_dir
|
let dir = instances_dir
|
||||||
.join(instance_name)
|
.join(instance_name)
|
||||||
.join(".minecraft")
|
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||||
.join("screenshots");
|
.join("screenshots");
|
||||||
|
|
||||||
let read_dir = match std::fs::read_dir(&dir) {
|
let read_dir = match std::fs::read_dir(&dir) {
|
||||||
@@ -45,88 +45,3 @@ pub fn scan_screenshots(instances_dir: &Path, instance_name: &str) -> Vec<Screen
|
|||||||
entries.sort_by(|a, b| b.name.cmp(&a.name));
|
entries.sort_by(|a, b| b.name.cmp(&a.name));
|
||||||
entries
|
entries
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn setup_screenshots_dir(tmp: &Path, instance: &str) -> PathBuf {
|
|
||||||
let dir = tmp.join(instance).join(".minecraft").join("screenshots");
|
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
|
||||||
dir
|
|
||||||
}
|
|
||||||
|
|
||||||
fn tiny_png() -> Vec<u8> {
|
|
||||||
let img = image::RgbImage::from_pixel(1, 1, image::Rgb([255, 255, 255]));
|
|
||||||
let mut buf = std::io::Cursor::new(Vec::new());
|
|
||||||
img.write_to(&mut buf, image::ImageFormat::Png).unwrap();
|
|
||||||
buf.into_inner()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_screenshots_empty_dir() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
setup_screenshots_dir(tmp.path(), "inst");
|
|
||||||
let screenshots = scan_screenshots(tmp.path(), "inst");
|
|
||||||
assert!(screenshots.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_screenshots_missing_dir_returns_empty() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let screenshots = scan_screenshots(tmp.path(), "ghost");
|
|
||||||
assert!(screenshots.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_screenshots_finds_images() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_screenshots_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("2024-01-01.png"), tiny_png()).unwrap();
|
|
||||||
std::fs::write(dir.join("2024-01-02.png"), tiny_png()).unwrap();
|
|
||||||
let screenshots = scan_screenshots(tmp.path(), "inst");
|
|
||||||
assert_eq!(screenshots.len(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_screenshots_ignores_non_images() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_screenshots_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("pic.png"), tiny_png()).unwrap();
|
|
||||||
std::fs::write(dir.join("notes.txt"), "not an image").unwrap();
|
|
||||||
let screenshots = scan_screenshots(tmp.path(), "inst");
|
|
||||||
assert_eq!(screenshots.len(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_screenshots_sorted_newest_first() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_screenshots_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("aaa.png"), tiny_png()).unwrap();
|
|
||||||
std::fs::write(dir.join("zzz.png"), tiny_png()).unwrap();
|
|
||||||
let screenshots = scan_screenshots(tmp.path(), "inst");
|
|
||||||
assert_eq!(screenshots[0].name, "zzz.png");
|
|
||||||
assert_eq!(screenshots[1].name, "aaa.png");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_screenshots_reads_dimensions() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_screenshots_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("shot.png"), tiny_png()).unwrap();
|
|
||||||
let screenshots = scan_screenshots(tmp.path(), "inst");
|
|
||||||
assert_eq!(screenshots[0].width, 1);
|
|
||||||
assert_eq!(screenshots[0].height, 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_screenshots_bad_image_uses_default_dimensions() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_screenshots_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("corrupt.png"), b"not a real png").unwrap();
|
|
||||||
let screenshots = scan_screenshots(tmp.path(), "inst");
|
|
||||||
assert_eq!(screenshots.len(), 1);
|
|
||||||
assert_eq!(screenshots[0].width, 1920);
|
|
||||||
assert_eq!(screenshots[0].height, 1080);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,309 @@
|
|||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn first_prepare_seeds_shared_config() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let meta = tmp.path().join("meta");
|
||||||
|
let minecraft = tmp.path().join("instance/minecraft");
|
||||||
|
create_profile(&meta, "main").unwrap();
|
||||||
|
std::fs::create_dir_all(minecraft.join("config/nested")).unwrap();
|
||||||
|
std::fs::write(minecraft.join("options.txt"), "local-options").unwrap();
|
||||||
|
std::fs::write(minecraft.join("optionsshaders.txt"), "shader-options").unwrap();
|
||||||
|
std::fs::write(minecraft.join("config/options.txt"), "local-config").unwrap();
|
||||||
|
std::fs::write(minecraft.join("config/nested/mod.toml"), "nested").unwrap();
|
||||||
|
|
||||||
|
assert!(prepare(Some("main"), &meta, &minecraft).unwrap());
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(meta.join("state/profiles/main/options.txt")).unwrap(),
|
||||||
|
"local-options"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(meta.join("state/profiles/main/optionsshaders.txt")).unwrap(),
|
||||||
|
"shader-options"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(meta.join("state/profiles/main/config/options.txt")).unwrap(),
|
||||||
|
"local-config"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(meta.join("state/profiles/main/config/nested/mod.toml")).unwrap(),
|
||||||
|
"nested"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prepare_mirrors_shared_config_into_instance() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let meta = tmp.path().join("meta");
|
||||||
|
let minecraft = tmp.path().join("instance/minecraft");
|
||||||
|
std::fs::create_dir_all(meta.join("state/profiles/main/config")).unwrap();
|
||||||
|
std::fs::create_dir_all(minecraft.join("config")).unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
meta.join("state/profiles/main/options.txt"),
|
||||||
|
"shared-options",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
meta.join("state/profiles/main/config/shared.toml"),
|
||||||
|
"shared",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
std::fs::write(minecraft.join("options.txt"), "stale-options").unwrap();
|
||||||
|
std::fs::write(minecraft.join("config/local.toml"), "stale").unwrap();
|
||||||
|
|
||||||
|
assert!(prepare(Some("main"), &meta, &minecraft).unwrap());
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
|
||||||
|
"shared-options"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(minecraft.join("config/shared.toml")).unwrap(),
|
||||||
|
"shared"
|
||||||
|
);
|
||||||
|
assert!(!minecraft.join("config/local.toml").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn finish_mirrors_instance_config_back_to_shared() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let meta = tmp.path().join("meta");
|
||||||
|
let minecraft = tmp.path().join("instance/minecraft");
|
||||||
|
std::fs::create_dir_all(meta.join("state/profiles/main/config")).unwrap();
|
||||||
|
std::fs::write(meta.join("state/profiles/main/config/old.toml"), "old").unwrap();
|
||||||
|
std::fs::create_dir_all(minecraft.join("config")).unwrap();
|
||||||
|
std::fs::write(minecraft.join("options.txt"), "new-options").unwrap();
|
||||||
|
std::fs::write(minecraft.join("config/new.toml"), "new").unwrap();
|
||||||
|
|
||||||
|
finish(Some("main"), &meta, &minecraft).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(meta.join("state/profiles/main/options.txt")).unwrap(),
|
||||||
|
"new-options"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(meta.join("state/profiles/main/config/new.toml")).unwrap(),
|
||||||
|
"new"
|
||||||
|
);
|
||||||
|
assert!(!meta.join("state/profiles/main/config/old.toml").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prepare_releases_lock_for_another_instance() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let meta = tmp.path().join("meta");
|
||||||
|
let minecraft = tmp.path().join("instance/minecraft");
|
||||||
|
create_profile(&meta, "main").unwrap();
|
||||||
|
std::fs::create_dir_all(minecraft.join("config")).unwrap();
|
||||||
|
|
||||||
|
assert!(prepare(Some("main"), &meta, &minecraft).unwrap());
|
||||||
|
let second = tmp.path().join("second/minecraft");
|
||||||
|
std::fs::create_dir_all(second.join("config")).unwrap();
|
||||||
|
|
||||||
|
assert!(prepare(Some("main"), &meta, &second).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn profile_rejects_path_traversal() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let err = prepare(Some("../bad"), tmp.path(), tmp.path()).unwrap_err();
|
||||||
|
|
||||||
|
assert!(matches!(err, ConfigSyncError::InvalidProfile(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn profile_rejects_builtin_names() {
|
||||||
|
for profile in [
|
||||||
|
"none",
|
||||||
|
"default",
|
||||||
|
"local",
|
||||||
|
"instance default",
|
||||||
|
"local default",
|
||||||
|
] {
|
||||||
|
let err = validate_profile(profile).unwrap_err();
|
||||||
|
assert!(matches!(err, ConfigSyncError::InvalidProfile(_)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prepare_ignores_deleted_profile() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let meta = tmp.path().join("meta");
|
||||||
|
let minecraft = tmp.path().join("instance/minecraft");
|
||||||
|
std::fs::create_dir_all(minecraft.join("config")).unwrap();
|
||||||
|
|
||||||
|
let lock = prepare(Some("deleted"), &meta, &minecraft).unwrap();
|
||||||
|
|
||||||
|
assert!(!lock);
|
||||||
|
assert!(!meta.join("state/profiles/deleted").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn create_profile_trims_and_lists_profiles() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
|
||||||
|
let profile = create_profile(tmp.path(), " main ").unwrap();
|
||||||
|
let profiles = list_profiles(tmp.path()).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(profile, "main");
|
||||||
|
assert_eq!(profiles, vec!["main"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn delete_profile_removes_profile_dir() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
create_profile(tmp.path(), "main").unwrap();
|
||||||
|
|
||||||
|
delete_profile(tmp.path(), "main").unwrap();
|
||||||
|
|
||||||
|
assert!(list_profiles(tmp.path()).unwrap().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn switch_to_profile_backs_up_local_config_and_restores_none() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let meta = tmp.path().join("meta");
|
||||||
|
let instance = tmp.path().join("instance");
|
||||||
|
let minecraft = instance.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||||
|
std::fs::create_dir_all(minecraft.join("config")).unwrap();
|
||||||
|
std::fs::write(minecraft.join("options.txt"), "local-options").unwrap();
|
||||||
|
std::fs::write(minecraft.join("config/local.txt"), "local").unwrap();
|
||||||
|
|
||||||
|
let selected = switch_profile("inst", None, Some("main"), &meta, &instance).unwrap();
|
||||||
|
assert_eq!(selected.as_deref(), Some("main"));
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(instance.join("rmcl/content/config/options.txt")).unwrap(),
|
||||||
|
"local-options"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(instance.join("rmcl/content/config/config/local.txt")).unwrap(),
|
||||||
|
"local"
|
||||||
|
);
|
||||||
|
|
||||||
|
std::fs::write(minecraft.join("options.txt"), "shared-options").unwrap();
|
||||||
|
std::fs::write(minecraft.join("config/shared.txt"), "shared").unwrap();
|
||||||
|
let selected = switch_profile("inst", Some("main"), None, &meta, &instance).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(selected, None);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(meta.join("state/profiles/main/options.txt")).unwrap(),
|
||||||
|
"shared-options"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(meta.join("state/profiles/main/config/shared.txt")).unwrap(),
|
||||||
|
"shared"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
|
||||||
|
"local-options"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(minecraft.join("config/local.txt")).unwrap(),
|
||||||
|
"local"
|
||||||
|
);
|
||||||
|
assert!(!minecraft.join("config/shared.txt").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn switch_from_deleted_profile_restores_local_without_recreating_profile() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let meta = tmp.path().join("meta");
|
||||||
|
let instance = tmp.path().join("instance");
|
||||||
|
let minecraft = instance.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||||
|
std::fs::create_dir_all(minecraft.join("config")).unwrap();
|
||||||
|
std::fs::create_dir_all(instance.join("rmcl/content/config/config")).unwrap();
|
||||||
|
std::fs::write(minecraft.join("options.txt"), "deleted-profile-options").unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
instance.join("rmcl/content/config/options.txt"),
|
||||||
|
"local-options",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
instance.join("rmcl/content/config/config/local.txt"),
|
||||||
|
"local",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let selected = switch_profile("inst", Some("deleted"), None, &meta, &instance).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(selected, None);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
|
||||||
|
"local-options"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(minecraft.join("config/local.txt")).unwrap(),
|
||||||
|
"local"
|
||||||
|
);
|
||||||
|
assert!(!meta.join("state/profiles/deleted").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn switch_between_profiles_saves_old_and_loads_new() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let meta = tmp.path().join("meta");
|
||||||
|
let instance = tmp.path().join("instance");
|
||||||
|
let minecraft = instance.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||||
|
std::fs::create_dir_all(minecraft.join("config")).unwrap();
|
||||||
|
std::fs::write(minecraft.join("options.txt"), "changed-a-options").unwrap();
|
||||||
|
std::fs::write(minecraft.join("config/a.txt"), "changed-a").unwrap();
|
||||||
|
create_profile(&meta, "a").unwrap();
|
||||||
|
std::fs::create_dir_all(meta.join("state/profiles/b/config")).unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
meta.join("state/profiles/b/options.txt"),
|
||||||
|
"profile-b-options",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
std::fs::write(meta.join("state/profiles/b/config/b.txt"), "profile-b").unwrap();
|
||||||
|
|
||||||
|
let selected = switch_profile("inst", Some("a"), Some("b"), &meta, &instance).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(selected.as_deref(), Some("b"));
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(meta.join("state/profiles/a/options.txt")).unwrap(),
|
||||||
|
"changed-a-options"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(meta.join("state/profiles/a/config/a.txt")).unwrap(),
|
||||||
|
"changed-a"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(minecraft.join("options.txt")).unwrap(),
|
||||||
|
"profile-b-options"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(minecraft.join("config/b.txt")).unwrap(),
|
||||||
|
"profile-b"
|
||||||
|
);
|
||||||
|
assert!(!minecraft.join("config/a.txt").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn second_instance_uses_profile_options_saved_by_first_instance() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let meta = tmp.path().join("meta");
|
||||||
|
let first = tmp.path().join("first/minecraft");
|
||||||
|
let second_instance = tmp.path().join("second");
|
||||||
|
let second = second_instance.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||||
|
std::fs::create_dir_all(first.join("config")).unwrap();
|
||||||
|
std::fs::create_dir_all(second.join("config")).unwrap();
|
||||||
|
std::fs::write(first.join("options.txt"), "first-default").unwrap();
|
||||||
|
std::fs::write(second.join("options.txt"), "second-local").unwrap();
|
||||||
|
create_profile(&meta, "main").unwrap();
|
||||||
|
|
||||||
|
assert!(prepare(Some("main"), &meta, &first).unwrap());
|
||||||
|
std::fs::write(first.join("options.txt"), "changed-in-main").unwrap();
|
||||||
|
finish(Some("main"), &meta, &first).unwrap();
|
||||||
|
|
||||||
|
switch_profile("second", None, Some("main"), &meta, &second_instance).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(second.join("options.txt")).unwrap(),
|
||||||
|
"changed-in-main"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(second_instance.join("rmcl/content/config/options.txt")).unwrap(),
|
||||||
|
"second-local"
|
||||||
|
);
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,23 @@
|
|||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn quadrant_raster_has_requested_dimensions() {
|
||||||
|
let image =
|
||||||
|
image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(2, 2, image::Rgb([12, 34, 56])));
|
||||||
|
let rows = make_icon_quadrants_from_image(&image, 7, 3);
|
||||||
|
|
||||||
|
assert_eq!(rows.len(), 3);
|
||||||
|
assert!(rows.iter().all(|row| row.len() == 7));
|
||||||
|
assert!(rows.iter().flatten().all(|cell| cell.symbol == '\u{2588}'));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fallback_icon_is_square_and_contains_a_separate_question_mark_dot() {
|
||||||
|
let icon = fallback_icon();
|
||||||
|
|
||||||
|
assert_eq!(icon.len(), 3);
|
||||||
|
assert!(icon.iter().all(|row| row.len() == 6));
|
||||||
|
assert_eq!(icon[2][2].bg_r, 45);
|
||||||
|
assert_eq!(icon[2][2].fg_r, 150);
|
||||||
|
assert_eq!(icon[2][3].fg_r, 150);
|
||||||
|
}
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn curseforge_fingerprint_ignores_whitespace() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let compact = temp.path().join("compact.jar");
|
||||||
|
let spaced = temp.path().join("spaced.jar");
|
||||||
|
std::fs::write(&compact, b"abc").unwrap();
|
||||||
|
std::fs::write(&spaced, b"a b\nc\r\t").unwrap();
|
||||||
|
let compact = fingerprint(&compact).unwrap();
|
||||||
|
assert_eq!(compact.hash("curseforge"), Some("1621425345"));
|
||||||
|
assert_eq!(
|
||||||
|
compact.hash("curseforge"),
|
||||||
|
fingerprint(&spaced).unwrap().hash("curseforge")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn manifest_round_trip_and_lookup_are_exact() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let path = temp.path().join("rmcl/content/manifest.json");
|
||||||
|
let record = ContentFileRecord {
|
||||||
|
relative_path: PathBuf::from("mods/fabric-api.jar"),
|
||||||
|
kind: ContentKind::Mod,
|
||||||
|
enabled: true,
|
||||||
|
fingerprint: FileFingerprint {
|
||||||
|
size: 3,
|
||||||
|
modified_ns: 4,
|
||||||
|
hashes: BTreeMap::from([("sha1".to_owned(), "abc".to_owned())]),
|
||||||
|
},
|
||||||
|
resolution: Resolution::Resolved {
|
||||||
|
project: ProviderProject {
|
||||||
|
provider: "modrinth".to_owned(),
|
||||||
|
project_id: "P7dR8mSH".to_owned(),
|
||||||
|
version_id: "version".to_owned(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
provider_aliases: Vec::new(),
|
||||||
|
provider_checks: Vec::new(),
|
||||||
|
required_dependencies: Vec::new(),
|
||||||
|
automatic_dependency: false,
|
||||||
|
cleanup_eligible: false,
|
||||||
|
};
|
||||||
|
let mut manifest = ContentManifest::default();
|
||||||
|
manifest.upsert(record);
|
||||||
|
manifest.save(&path).unwrap();
|
||||||
|
|
||||||
|
let loaded = ContentManifest::load(&path).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
loaded.resolved_project_path("modrinth", "P7dR8mSH", Path::new("/instance/minecraft")),
|
||||||
|
Some(PathBuf::from("/instance/minecraft/mods/fabric-api.jar"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
loaded
|
||||||
|
.resolved_project_path("modrinth", "fabric-api", Path::new("/minecraft"))
|
||||||
|
.is_none()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fingerprint_contains_both_modrinth_hashes() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let path = temp.path().join("example.jar");
|
||||||
|
std::fs::write(&path, b"abc").unwrap();
|
||||||
|
let fingerprint = fingerprint(&path).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
fingerprint.hash("sha1"),
|
||||||
|
Some("a9993e364706816aba3e25717850c26c9cd0d89d")
|
||||||
|
);
|
||||||
|
assert_eq!(fingerprint.hash("sha512").unwrap().len(), 128);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn renaming_a_record_preserves_its_resolution() {
|
||||||
|
let mut manifest = ContentManifest::default();
|
||||||
|
manifest.upsert(ContentFileRecord {
|
||||||
|
relative_path: PathBuf::from("mods/example.jar"),
|
||||||
|
kind: ContentKind::Mod,
|
||||||
|
enabled: true,
|
||||||
|
fingerprint: FileFingerprint {
|
||||||
|
size: 3,
|
||||||
|
modified_ns: 4,
|
||||||
|
hashes: BTreeMap::new(),
|
||||||
|
},
|
||||||
|
resolution: Resolution::Resolved {
|
||||||
|
project: ProviderProject {
|
||||||
|
provider: "modrinth".to_owned(),
|
||||||
|
project_id: "project".to_owned(),
|
||||||
|
version_id: "version".to_owned(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
provider_aliases: Vec::new(),
|
||||||
|
provider_checks: Vec::new(),
|
||||||
|
required_dependencies: Vec::new(),
|
||||||
|
automatic_dependency: false,
|
||||||
|
cleanup_eligible: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert!(manifest.rename_record(
|
||||||
|
Path::new("mods/example.jar"),
|
||||||
|
Path::new("mods/example.jar.disabled"),
|
||||||
|
false,
|
||||||
|
));
|
||||||
|
let record = manifest
|
||||||
|
.record(Path::new("mods/example.jar.disabled"))
|
||||||
|
.unwrap();
|
||||||
|
assert!(!record.enabled);
|
||||||
|
assert!(matches!(record.resolution, Resolution::Resolved { .. }));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn managed_record(
|
||||||
|
path: &str,
|
||||||
|
project_id: &str,
|
||||||
|
automatic_dependency: bool,
|
||||||
|
required_dependencies: Vec<ProviderProject>,
|
||||||
|
) -> ContentFileRecord {
|
||||||
|
ContentFileRecord {
|
||||||
|
relative_path: PathBuf::from(path),
|
||||||
|
kind: ContentKind::Mod,
|
||||||
|
enabled: true,
|
||||||
|
fingerprint: FileFingerprint {
|
||||||
|
size: 1,
|
||||||
|
modified_ns: 1,
|
||||||
|
hashes: BTreeMap::new(),
|
||||||
|
},
|
||||||
|
resolution: Resolution::Resolved {
|
||||||
|
project: ProviderProject {
|
||||||
|
provider: "modrinth".to_owned(),
|
||||||
|
project_id: project_id.to_owned(),
|
||||||
|
version_id: format!("{project_id}-version"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
provider_aliases: Vec::new(),
|
||||||
|
provider_checks: Vec::new(),
|
||||||
|
required_dependencies,
|
||||||
|
automatic_dependency,
|
||||||
|
cleanup_eligible: automatic_dependency,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dependency(project_id: &str) -> ProviderProject {
|
||||||
|
ProviderProject {
|
||||||
|
provider: "modrinth".to_owned(),
|
||||||
|
project_id: project_id.to_owned(),
|
||||||
|
version_id: format!("{project_id}-version"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn provider_aliases_match_the_same_installed_record() {
|
||||||
|
let mut record = managed_record("mods/library.jar", "curseforge-library", false, Vec::new());
|
||||||
|
record.provider_aliases.push(ProviderProject {
|
||||||
|
provider: "modrinth".to_owned(),
|
||||||
|
project_id: "modrinth-library".to_owned(),
|
||||||
|
version_id: "modrinth-version".to_owned(),
|
||||||
|
});
|
||||||
|
let manifest = ContentManifest {
|
||||||
|
version: 1,
|
||||||
|
files: vec![record],
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
manifest
|
||||||
|
.resolved_project_record("modrinth", "modrinth-library")
|
||||||
|
.is_some()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn orphan_cleanup_keeps_shared_and_user_managed_libraries() {
|
||||||
|
let manifest = ContentManifest {
|
||||||
|
version: 1,
|
||||||
|
files: vec![
|
||||||
|
managed_record("mods/first.jar", "first", false, vec![dependency("shared")]),
|
||||||
|
managed_record(
|
||||||
|
"mods/second.jar",
|
||||||
|
"second",
|
||||||
|
false,
|
||||||
|
vec![dependency("shared"), dependency("explicit")],
|
||||||
|
),
|
||||||
|
managed_record("mods/shared.jar", "shared", true, Vec::new()),
|
||||||
|
managed_record("mods/explicit.jar", "explicit", false, Vec::new()),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
manifest.orphaned_dependencies_after_removing(Path::new("mods/first.jar")),
|
||||||
|
Vec::<PathBuf>::new()
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
manifest.orphaned_dependencies_after_removing(Path::new("mods/second.jar")),
|
||||||
|
Vec::<PathBuf>::new()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn orphan_cleanup_follows_automatic_dependency_chains() {
|
||||||
|
let manifest = ContentManifest {
|
||||||
|
version: 1,
|
||||||
|
files: vec![
|
||||||
|
managed_record("mods/root.jar", "root", false, vec![dependency("library")]),
|
||||||
|
managed_record(
|
||||||
|
"mods/library.jar",
|
||||||
|
"library",
|
||||||
|
true,
|
||||||
|
vec![dependency("nested")],
|
||||||
|
),
|
||||||
|
managed_record("mods/nested.jar", "nested", true, Vec::new()),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
manifest.orphaned_dependencies_after_removing(Path::new("mods/root.jar")),
|
||||||
|
vec![
|
||||||
|
PathBuf::from("mods/library.jar"),
|
||||||
|
PathBuf::from("mods/nested.jar")
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn orphan_cleanup_keeps_automatic_non_library_dependencies() {
|
||||||
|
let mut dependency_record = managed_record("mods/sodium.jar", "sodium", true, Vec::new());
|
||||||
|
dependency_record.cleanup_eligible = false;
|
||||||
|
let manifest = ContentManifest {
|
||||||
|
version: 1,
|
||||||
|
files: vec![
|
||||||
|
managed_record("mods/root.jar", "root", false, vec![dependency("sodium")]),
|
||||||
|
dependency_record,
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
manifest
|
||||||
|
.orphaned_dependencies_after_removing(Path::new("mods/root.jar"))
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn datapack_dependencies_are_scoped_to_their_world() {
|
||||||
|
let mut first_root = managed_record(
|
||||||
|
"saves/first/datapacks/root.zip",
|
||||||
|
"root",
|
||||||
|
false,
|
||||||
|
vec![dependency("library")],
|
||||||
|
);
|
||||||
|
first_root.kind = ContentKind::DataPack;
|
||||||
|
let mut second_root = managed_record(
|
||||||
|
"saves/second/datapacks/root.zip",
|
||||||
|
"root",
|
||||||
|
false,
|
||||||
|
vec![dependency("library")],
|
||||||
|
);
|
||||||
|
second_root.kind = ContentKind::DataPack;
|
||||||
|
let mut first_library = managed_record(
|
||||||
|
"saves/first/datapacks/library.zip",
|
||||||
|
"library",
|
||||||
|
true,
|
||||||
|
Vec::new(),
|
||||||
|
);
|
||||||
|
first_library.kind = ContentKind::DataPack;
|
||||||
|
let mut second_library = managed_record(
|
||||||
|
"saves/second/datapacks/library.zip",
|
||||||
|
"library",
|
||||||
|
true,
|
||||||
|
Vec::new(),
|
||||||
|
);
|
||||||
|
second_library.kind = ContentKind::DataPack;
|
||||||
|
let manifest = ContentManifest {
|
||||||
|
version: 1,
|
||||||
|
files: vec![first_root, second_root, first_library, second_library],
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
manifest.orphaned_dependencies_after_removing(Path::new("saves/first/datapacks/root.zip")),
|
||||||
|
vec![PathBuf::from("saves/first/datapacks/library.zip")]
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,374 @@
|
|||||||
|
use super::*;
|
||||||
|
use crate::instance::content::entry::{ContentEntry, toggle_entry};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
fn setup_mods_dir(tmp: &Path, instance: &str) -> PathBuf {
|
||||||
|
let dir = tmp
|
||||||
|
.join(instance)
|
||||||
|
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||||
|
.join("mods");
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
dir
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scan_mods_empty_dir() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
setup_mods_dir(tmp.path(), "inst");
|
||||||
|
let mods = scan_mods(tmp.path(), "inst");
|
||||||
|
assert!(mods.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scan_mods_missing_dir_returns_empty() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let mods = scan_mods(tmp.path(), "ghost");
|
||||||
|
assert!(mods.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scan_mods_enabled_disabled_flags() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||||
|
std::fs::write(dir.join("active.jar"), b"PK\x03\x04").unwrap();
|
||||||
|
std::fs::write(dir.join("inactive.jar.disabled"), b"PK\x03\x04").unwrap();
|
||||||
|
let mods = scan_mods(tmp.path(), "inst");
|
||||||
|
let active = mods.iter().find(|m| m.file_stem == "active").unwrap();
|
||||||
|
let inactive = mods.iter().find(|m| m.file_stem == "inactive").unwrap();
|
||||||
|
assert!(active.enabled);
|
||||||
|
assert!(!inactive.enabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scan_mods_ignores_non_jar() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||||
|
std::fs::write(dir.join("readme.txt"), "not a mod").unwrap();
|
||||||
|
std::fs::write(dir.join("config.json"), "{}").unwrap();
|
||||||
|
std::fs::write(dir.join("real.jar"), b"PK\x03\x04").unwrap();
|
||||||
|
let mods = scan_mods(tmp.path(), "inst");
|
||||||
|
assert_eq!(mods.len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scan_mods_sorted_case_insensitive() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||||
|
std::fs::write(dir.join("Zebra.jar"), b"PK\x03\x04").unwrap();
|
||||||
|
std::fs::write(dir.join("alpha.jar"), b"PK\x03\x04").unwrap();
|
||||||
|
std::fs::write(dir.join("Beta.jar"), b"PK\x03\x04").unwrap();
|
||||||
|
let mods = scan_mods(tmp.path(), "inst");
|
||||||
|
let names: Vec<&str> = mods.iter().map(|m| m.name.as_str()).collect();
|
||||||
|
assert_eq!(names, vec!["alpha", "Beta", "Zebra"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn toggle_entry_enable() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||||
|
let disabled_path = dir.join("mymod.jar.disabled");
|
||||||
|
std::fs::write(&disabled_path, b"PK\x03\x04").unwrap();
|
||||||
|
|
||||||
|
let entry = ContentEntry {
|
||||||
|
file_stem: "mymod".to_string(),
|
||||||
|
name: "mymod".to_string(),
|
||||||
|
source_slug: None,
|
||||||
|
installed_path: None,
|
||||||
|
provider_project: None,
|
||||||
|
world_details: None,
|
||||||
|
title_suffix: None,
|
||||||
|
footer_label: None,
|
||||||
|
footer_change: None,
|
||||||
|
description: String::new(),
|
||||||
|
enabled: false,
|
||||||
|
icon_bytes: None,
|
||||||
|
provider_icon: false,
|
||||||
|
provider_description: false,
|
||||||
|
path: disabled_path.clone(),
|
||||||
|
icon_lines: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
toggle_entry(&entry).unwrap();
|
||||||
|
assert!(!disabled_path.exists());
|
||||||
|
assert!(dir.join("mymod.jar").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
use std::io::Write as _;
|
||||||
|
|
||||||
|
fn make_jar(dir: &Path, name: &str, entries: &[(&str, &[u8])]) {
|
||||||
|
let path = dir.join(name);
|
||||||
|
let file = std::fs::File::create(&path).unwrap();
|
||||||
|
let mut zip = zip::ZipWriter::new(file);
|
||||||
|
let options: zip::write::FileOptions<()> =
|
||||||
|
zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored);
|
||||||
|
for (entry_name, data) in entries {
|
||||||
|
zip.start_file(*entry_name, options).unwrap();
|
||||||
|
zip.write_all(data).unwrap();
|
||||||
|
}
|
||||||
|
zip.finish().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scan_mods_reads_fabric_metadata() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||||
|
let meta =
|
||||||
|
r#"{"name":"Fabric Mod","description":"A fabric mod","version":"1.2.3","icon":"icon.png"}"#;
|
||||||
|
make_jar(
|
||||||
|
&dir,
|
||||||
|
"fabric-mod.jar",
|
||||||
|
&[("fabric.mod.json", meta.as_bytes())],
|
||||||
|
);
|
||||||
|
let mods = scan_mods(tmp.path(), "inst");
|
||||||
|
assert_eq!(mods.len(), 1);
|
||||||
|
assert_eq!(mods[0].name, "Fabric Mod");
|
||||||
|
assert_eq!(mods[0].description, "A fabric mod");
|
||||||
|
assert_eq!(mods[0].footer_label.as_deref(), Some("1.2.3"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scan_mods_reads_quilt_metadata() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||||
|
let meta = r#"{"quilt_loader":{"metadata":{"name":"Quilt Mod","description":"A quilt mod"}}}"#;
|
||||||
|
make_jar(
|
||||||
|
&dir,
|
||||||
|
"quilt-mod.jar",
|
||||||
|
&[("quilt.mod.json", meta.as_bytes())],
|
||||||
|
);
|
||||||
|
let mods = scan_mods(tmp.path(), "inst");
|
||||||
|
assert_eq!(mods.len(), 1);
|
||||||
|
assert_eq!(mods[0].name, "Quilt Mod");
|
||||||
|
assert_eq!(mods[0].description, "A quilt mod");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scan_mods_reads_forge_toml_metadata() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||||
|
let meta = r#"
|
||||||
|
logoFile = "logo.png"
|
||||||
|
|
||||||
|
[[mods]]
|
||||||
|
displayName = "Forge Mod"
|
||||||
|
description = "A forge mod"
|
||||||
|
"#;
|
||||||
|
make_jar(
|
||||||
|
&dir,
|
||||||
|
"forge-mod.jar",
|
||||||
|
&[("META-INF/mods.toml", meta.as_bytes())],
|
||||||
|
);
|
||||||
|
let mods = scan_mods(tmp.path(), "inst");
|
||||||
|
assert_eq!(mods.len(), 1);
|
||||||
|
assert_eq!(mods[0].name, "Forge Mod");
|
||||||
|
assert_eq!(mods[0].description, "A forge mod");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scan_mods_reads_neoforge_toml_metadata() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||||
|
let meta = r#"
|
||||||
|
logoFile = "logo.png"
|
||||||
|
|
||||||
|
[[mods]]
|
||||||
|
displayName = "NeoForge Mod"
|
||||||
|
description = "A neoforge mod"
|
||||||
|
"#;
|
||||||
|
make_jar(
|
||||||
|
&dir,
|
||||||
|
"neoforge-mod.jar",
|
||||||
|
&[("META-INF/neoforge.mods.toml", meta.as_bytes())],
|
||||||
|
);
|
||||||
|
let mods = scan_mods(tmp.path(), "inst");
|
||||||
|
assert_eq!(mods.len(), 1);
|
||||||
|
assert_eq!(mods[0].name, "NeoForge Mod");
|
||||||
|
assert_eq!(mods[0].description, "A neoforge mod");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scan_mods_reads_mcmod_info_array() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||||
|
let meta = r#"[{"name":"Legacy Mod","description":"An old forge mod"}]"#;
|
||||||
|
make_jar(&dir, "legacy-mod.jar", &[("mcmod.info", meta.as_bytes())]);
|
||||||
|
let mods = scan_mods(tmp.path(), "inst");
|
||||||
|
assert_eq!(mods.len(), 1);
|
||||||
|
assert_eq!(mods[0].name, "Legacy Mod");
|
||||||
|
assert_eq!(mods[0].description, "An old forge mod");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scan_mods_reads_mcmod_info_modlist() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||||
|
let meta = r#"{"modList":[{"name":"Wrapped Mod","description":"Has modList wrapper"}]}"#;
|
||||||
|
make_jar(&dir, "wrapped-mod.jar", &[("mcmod.info", meta.as_bytes())]);
|
||||||
|
let mods = scan_mods(tmp.path(), "inst");
|
||||||
|
assert_eq!(mods.len(), 1);
|
||||||
|
assert_eq!(mods[0].name, "Wrapped Mod");
|
||||||
|
assert_eq!(mods[0].description, "Has modList wrapper");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scan_mods_prefers_fabric_over_forge() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||||
|
let fabric = r#"{"name":"Fabric Name","description":"fabric desc"}"#;
|
||||||
|
let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n";
|
||||||
|
make_jar(
|
||||||
|
&dir,
|
||||||
|
"multi.jar",
|
||||||
|
&[
|
||||||
|
("fabric.mod.json", fabric.as_bytes()),
|
||||||
|
("META-INF/mods.toml", forge.as_bytes()),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
let mods = scan_mods(tmp.path(), "inst");
|
||||||
|
assert_eq!(mods[0].name, "Fabric Name");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scan_mods_prefers_quilt_over_forge() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||||
|
let quilt = r#"{"quilt_loader":{"id":"x","version":"1","metadata":{"name":"Quilt Name","description":"quilt desc"}}}"#;
|
||||||
|
let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n";
|
||||||
|
make_jar(
|
||||||
|
&dir,
|
||||||
|
"quilt-over-forge.jar",
|
||||||
|
&[
|
||||||
|
("quilt.mod.json", quilt.as_bytes()),
|
||||||
|
("META-INF/mods.toml", forge.as_bytes()),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
let mods = scan_mods(tmp.path(), "inst");
|
||||||
|
assert_eq!(mods[0].name, "Quilt Name");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scan_mods_prefers_forge_toml_over_mcmod_info() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||||
|
let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n";
|
||||||
|
let mcmod = r#"[{"modid":"legacy","name":"Legacy Name","description":"legacy desc"}]"#;
|
||||||
|
make_jar(
|
||||||
|
&dir,
|
||||||
|
"forge-over-legacy.jar",
|
||||||
|
&[
|
||||||
|
("META-INF/mods.toml", forge.as_bytes()),
|
||||||
|
("mcmod.info", mcmod.as_bytes()),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
let mods = scan_mods(tmp.path(), "inst");
|
||||||
|
assert_eq!(mods[0].name, "Forge Name");
|
||||||
|
}
|
||||||
|
|
||||||
|
// when both neoforge.mods.toml and mods.toml exist in the same jar (the
|
||||||
|
// shape a dual-format mod might ship), the neoforge one wins because
|
||||||
|
// read_forge_toml_meta tries it first via .or_else.
|
||||||
|
#[test]
|
||||||
|
fn scan_mods_prefers_neoforge_toml_over_forge_toml() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||||
|
let neoforge = "[[mods]]\ndisplayName = \"NeoForge Name\"\ndescription = \"neoforge desc\"\n";
|
||||||
|
let forge = "[[mods]]\ndisplayName = \"Forge Name\"\ndescription = \"forge desc\"\n";
|
||||||
|
make_jar(
|
||||||
|
&dir,
|
||||||
|
"neoforge-over-forge.jar",
|
||||||
|
&[
|
||||||
|
("META-INF/neoforge.mods.toml", neoforge.as_bytes()),
|
||||||
|
("META-INF/mods.toml", forge.as_bytes()),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
let mods = scan_mods(tmp.path(), "inst");
|
||||||
|
assert_eq!(mods[0].name, "NeoForge Name");
|
||||||
|
}
|
||||||
|
|
||||||
|
// a mods.toml with logoFile but no [[mods]] array (e.g. a dependency-only
|
||||||
|
// library jar) should still surface as a scanned mod with empty name +
|
||||||
|
// description but with the icon resolved.
|
||||||
|
#[test]
|
||||||
|
fn scan_mods_reads_mods_toml_without_mods_array() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||||
|
let mods_toml = "logoFile = \"icon.png\"\n";
|
||||||
|
let png_bytes = b"\x89PNG fake icon";
|
||||||
|
make_jar(
|
||||||
|
&dir,
|
||||||
|
"lib-only.jar",
|
||||||
|
&[
|
||||||
|
("META-INF/mods.toml", mods_toml.as_bytes()),
|
||||||
|
("icon.png", png_bytes),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
let mods = scan_mods(tmp.path(), "inst");
|
||||||
|
assert_eq!(mods.len(), 1);
|
||||||
|
// file-stem fallback when metadata name is empty - covered here
|
||||||
|
// because no other test exercises an empty-name + present-logo combo.
|
||||||
|
assert_eq!(mods[0].name, "lib-only");
|
||||||
|
assert_eq!(mods[0].icon_bytes.as_deref(), Some(png_bytes.as_slice()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scan_mods_fallback_icon_paths() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||||
|
let png_bytes = b"\x89PNG fake";
|
||||||
|
make_jar(&dir, "no-meta.jar", &[("logo.png", png_bytes)]);
|
||||||
|
let mods = scan_mods(tmp.path(), "inst");
|
||||||
|
assert_eq!(mods.len(), 1);
|
||||||
|
assert_eq!(mods[0].name, "no-meta");
|
||||||
|
assert_eq!(mods[0].icon_bytes.as_deref(), Some(png_bytes.as_slice()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn icon_path_from_value_string() {
|
||||||
|
let val = serde_json::json!("assets/icon.png");
|
||||||
|
assert_eq!(icon_path_from_value(&val), "assets/icon.png");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn icon_path_from_value_map() {
|
||||||
|
// serde_json::Map is a BTreeMap, so iteration is sorted by key.
|
||||||
|
// "128" sorts before "64" lexicographically, so the first value wins.
|
||||||
|
let val = serde_json::json!({"64": "icon_64.png", "128": "icon_128.png"});
|
||||||
|
assert_eq!(icon_path_from_value(&val), "icon_128.png");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn icon_path_from_value_null() {
|
||||||
|
let val = serde_json::Value::Null;
|
||||||
|
assert_eq!(icon_path_from_value(&val), "");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn toggle_entry_disable() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = setup_mods_dir(tmp.path(), "inst");
|
||||||
|
let enabled_path = dir.join("mymod.jar");
|
||||||
|
std::fs::write(&enabled_path, b"PK\x03\x04").unwrap();
|
||||||
|
|
||||||
|
let entry = ContentEntry {
|
||||||
|
file_stem: "mymod".to_string(),
|
||||||
|
name: "mymod".to_string(),
|
||||||
|
source_slug: None,
|
||||||
|
installed_path: None,
|
||||||
|
provider_project: None,
|
||||||
|
world_details: None,
|
||||||
|
title_suffix: None,
|
||||||
|
footer_label: None,
|
||||||
|
footer_change: None,
|
||||||
|
description: String::new(),
|
||||||
|
enabled: true,
|
||||||
|
icon_bytes: None,
|
||||||
|
provider_icon: false,
|
||||||
|
provider_description: false,
|
||||||
|
path: enabled_path.clone(),
|
||||||
|
icon_lines: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
toggle_entry(&entry).unwrap();
|
||||||
|
assert!(!enabled_path.exists());
|
||||||
|
assert!(dir.join("mymod.jar.disabled").exists());
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn registry_falls_back_to_first_capable_provider() {
|
||||||
|
let registry = ProviderRegistry::modrinth(crate::net::HttpClient::new());
|
||||||
|
assert_eq!(registry.preferred("unknown").unwrap().id(), "modrinth");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn update_check_requires_the_installed_version_behind_a_newer_result() {
|
||||||
|
let version = |id: &str| VersionInfo {
|
||||||
|
id: id.to_owned(),
|
||||||
|
project_id: "project".to_owned(),
|
||||||
|
name: id.to_owned(),
|
||||||
|
version_number: id.to_owned(),
|
||||||
|
game_versions: vec!["1.21.1".to_owned()],
|
||||||
|
loaders: vec!["fabric".to_owned()],
|
||||||
|
version_type: crate::net::modrinth::VersionType::Release,
|
||||||
|
dependencies: Vec::new(),
|
||||||
|
date_published: String::new(),
|
||||||
|
files: Vec::new(),
|
||||||
|
};
|
||||||
|
let versions = vec![version("new"), version("installed")];
|
||||||
|
|
||||||
|
assert!(has_newer_compatible_version(&versions, "installed"));
|
||||||
|
assert!(!has_newer_compatible_version(&versions, "new"));
|
||||||
|
assert!(!has_newer_compatible_version(&versions, "missing"));
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
use super::*;
|
||||||
|
|
||||||
|
struct NoopProgress;
|
||||||
|
|
||||||
|
impl InventoryProgress for NoopProgress {
|
||||||
|
fn set_sub_action(&self, _text: &str) {}
|
||||||
|
|
||||||
|
fn set_progress(&self, _current: u64, _total: u64) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolved_record() -> ContentFileRecord {
|
||||||
|
ContentFileRecord {
|
||||||
|
relative_path: PathBuf::from("mods/example.jar"),
|
||||||
|
kind: ContentKind::Mod,
|
||||||
|
enabled: true,
|
||||||
|
fingerprint: FileFingerprint {
|
||||||
|
size: 1,
|
||||||
|
modified_ns: 1,
|
||||||
|
hashes: Default::default(),
|
||||||
|
},
|
||||||
|
resolution: Resolution::Resolved {
|
||||||
|
project: ProviderProject {
|
||||||
|
provider: "modrinth".to_owned(),
|
||||||
|
project_id: "example".to_owned(),
|
||||||
|
version_id: "1".to_owned(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
provider_aliases: Vec::new(),
|
||||||
|
provider_checks: Vec::new(),
|
||||||
|
required_dependencies: Vec::new(),
|
||||||
|
automatic_dependency: false,
|
||||||
|
cleanup_eligible: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn job(name: &str) -> ReconcileJob {
|
||||||
|
ReconcileJob {
|
||||||
|
instance: InstanceConfig {
|
||||||
|
name: name.to_owned(),
|
||||||
|
game_version: "1.21.1".to_owned(),
|
||||||
|
loader: crate::instance::ModLoader::Fabric,
|
||||||
|
loader_version: None,
|
||||||
|
created: chrono::DateTime::UNIX_EPOCH,
|
||||||
|
last_played: None,
|
||||||
|
java_path: None,
|
||||||
|
memory_max: None,
|
||||||
|
memory_min: None,
|
||||||
|
jvm_args: Vec::new(),
|
||||||
|
resolution: None,
|
||||||
|
config_sync_profile: None,
|
||||||
|
modpack_source: None,
|
||||||
|
},
|
||||||
|
instances_dir: PathBuf::new(),
|
||||||
|
client: crate::net::HttpClient::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn coordinator_queues_instances_once_and_preserves_order() {
|
||||||
|
let mut coordinator = ReconcileCoordinator::default();
|
||||||
|
let one = ("one".to_owned(), chrono::DateTime::UNIX_EPOCH);
|
||||||
|
assert!(coordinator.enqueue(job("one"), false));
|
||||||
|
assert!(!coordinator.enqueue(job("two"), false));
|
||||||
|
assert!(!coordinator.enqueue(job("one"), false));
|
||||||
|
assert!(!coordinator.rerun.contains(&one));
|
||||||
|
assert!(!coordinator.enqueue(job("one"), true));
|
||||||
|
assert_eq!(coordinator.queue.len(), 2);
|
||||||
|
assert!(coordinator.rerun.contains(&one));
|
||||||
|
assert_eq!(coordinator.queue.pop_front().unwrap().instance.name, "one");
|
||||||
|
assert_eq!(coordinator.queue.pop_front().unwrap().instance.name, "two");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn coordinator_does_not_merge_recreated_instances_with_the_same_name() {
|
||||||
|
let mut coordinator = ReconcileCoordinator::default();
|
||||||
|
let first = job("same");
|
||||||
|
let mut recreated = job("same");
|
||||||
|
recreated.instance.created += chrono::TimeDelta::seconds(1);
|
||||||
|
|
||||||
|
assert!(coordinator.enqueue(first, false));
|
||||||
|
assert!(!coordinator.enqueue(recreated, false));
|
||||||
|
assert_eq!(coordinator.queue.len(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn oversized_content_is_kept_without_hashing_or_provider_query() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let minecraft = temp.path().join("minecraft");
|
||||||
|
let resource_packs = minecraft.join("resourcepacks");
|
||||||
|
std::fs::create_dir_all(&resource_packs).unwrap();
|
||||||
|
let pack = resource_packs.join("large.zip");
|
||||||
|
let file = std::fs::File::create(&pack).unwrap();
|
||||||
|
file.set_len(2 * 1024 * 1024).unwrap();
|
||||||
|
let manifest_path = temp.path().join("manifest.json");
|
||||||
|
|
||||||
|
let inventory = reconcile_inventory(&manifest_path, &minecraft, 24, 1, &NoopProgress).unwrap();
|
||||||
|
|
||||||
|
assert!(inventory.queries.is_empty());
|
||||||
|
assert_eq!(inventory.manifest.files.len(), 1);
|
||||||
|
assert!(inventory.manifest.files[0].fingerprint.hashes.is_empty());
|
||||||
|
assert!(matches!(
|
||||||
|
inventory.manifest.files[0].resolution,
|
||||||
|
Resolution::Unmatched { .. }
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unchanged_saved_index_reuses_fingerprint_and_skips_provider_query() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let minecraft = temp.path().join("minecraft");
|
||||||
|
let mods = minecraft.join("mods");
|
||||||
|
std::fs::create_dir_all(&mods).unwrap();
|
||||||
|
std::fs::write(mods.join("example.jar"), b"example").unwrap();
|
||||||
|
let manifest_path = temp.path().join("manifest.json");
|
||||||
|
|
||||||
|
let mut first =
|
||||||
|
reconcile_inventory(&manifest_path, &minecraft, 24, 512, &NoopProgress).unwrap();
|
||||||
|
assert_eq!(first.queries.len(), 1);
|
||||||
|
let fingerprint = first.manifest.files[0].fingerprint.clone();
|
||||||
|
first.manifest.files[0].resolution = Resolution::Unmatched {
|
||||||
|
checked_at: chrono::Utc::now().timestamp(),
|
||||||
|
providers: vec!["modrinth".to_owned(), "curseforge".to_owned()],
|
||||||
|
};
|
||||||
|
first.manifest.save(&manifest_path).unwrap();
|
||||||
|
|
||||||
|
let second = reconcile_inventory(&manifest_path, &minecraft, 24, 512, &NoopProgress).unwrap();
|
||||||
|
assert!(second.queries.is_empty());
|
||||||
|
assert_eq!(second.manifest.files[0].fingerprint, fingerprint);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn newly_configured_provider_retries_an_unmatched_record() {
|
||||||
|
let mut record = resolved_record();
|
||||||
|
|
||||||
|
assert!(provider_was_not_checked(&record, "curseforge"));
|
||||||
|
assert!(!provider_was_not_checked(&record, "modrinth"));
|
||||||
|
record.provider_checks.push("curseforge".to_owned());
|
||||||
|
assert!(!provider_was_not_checked(&record, "curseforge"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reconciliation_saves_provider_aliases_for_an_existing_resolution() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let manifest_path = temp.path().join("manifest.json");
|
||||||
|
let current = ContentManifest {
|
||||||
|
version: 1,
|
||||||
|
files: vec![resolved_record()],
|
||||||
|
};
|
||||||
|
current.save(&manifest_path).unwrap();
|
||||||
|
|
||||||
|
let mut enriched = resolved_record();
|
||||||
|
enriched.provider_aliases.push(ProviderProject {
|
||||||
|
provider: "curseforge".to_owned(),
|
||||||
|
project_id: "42".to_owned(),
|
||||||
|
version_id: "84".to_owned(),
|
||||||
|
});
|
||||||
|
enriched.provider_checks = vec!["modrinth".to_owned(), "curseforge".to_owned()];
|
||||||
|
let saved = save_reconciled_manifest(
|
||||||
|
&manifest_path,
|
||||||
|
&temp.path().join("minecraft"),
|
||||||
|
ContentManifest {
|
||||||
|
version: 1,
|
||||||
|
files: vec![enriched.clone()],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(saved.files, vec![enriched]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn directory_packs_are_indexed_without_provider_queries() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let minecraft = temp.path().join("minecraft");
|
||||||
|
let pack = minecraft.join("resourcepacks/example");
|
||||||
|
std::fs::create_dir_all(&pack).unwrap();
|
||||||
|
std::fs::write(pack.join("pack.mcmeta"), b"{}").unwrap();
|
||||||
|
|
||||||
|
let inventory = reconcile_inventory(
|
||||||
|
&temp.path().join("manifest.json"),
|
||||||
|
&minecraft,
|
||||||
|
24,
|
||||||
|
512,
|
||||||
|
&NoopProgress,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert!(inventory.queries.is_empty());
|
||||||
|
assert_eq!(
|
||||||
|
inventory.manifest.files[0].relative_path,
|
||||||
|
PathBuf::from("resourcepacks/example")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn datapacks_are_indexed_under_their_world() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let minecraft = temp.path().join("minecraft");
|
||||||
|
let datapacks = minecraft.join("saves/world/datapacks");
|
||||||
|
std::fs::create_dir_all(datapacks.join("folder-pack")).unwrap();
|
||||||
|
std::fs::write(datapacks.join("zipped-pack.zip"), b"zip").unwrap();
|
||||||
|
|
||||||
|
let inventory = reconcile_inventory(
|
||||||
|
&temp.path().join("manifest.json"),
|
||||||
|
&minecraft,
|
||||||
|
24,
|
||||||
|
512,
|
||||||
|
&NoopProgress,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(inventory.manifest.files.len(), 2);
|
||||||
|
assert!(inventory.manifest.files.iter().all(|record| {
|
||||||
|
record.kind == ContentKind::DataPack
|
||||||
|
&& record.relative_path.starts_with("saves/world/datapacks")
|
||||||
|
}));
|
||||||
|
assert_eq!(inventory.queries.len(), 1);
|
||||||
|
}
|
||||||
Loaded 100 of 243 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user