Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
f594d1ae49 | ||
|
|
2bc0728a48 | ||
|
|
bf65814b7d | ||
|
|
a407d460f7 | ||
|
|
35ecf2f810 | ||
|
|
ae2524f2ce | ||
|
|
2b3aa4df32 | ||
|
|
d5cbc11c8a | ||
|
|
2ea20b0a99 | ||
|
|
d9004f3761 | ||
|
|
1dcd625ea2 | ||
|
|
f226358b1c | ||
|
|
de6af2de18 | ||
|
|
ff7bb55faa | ||
|
|
495a4b3fa1 | ||
|
|
3d8b3deb74 | ||
|
|
ec378b0b59 | ||
|
|
a0a03a8f8f | ||
|
|
2acbec94c9 | ||
|
|
ec016293cb | ||
|
|
b4b1b0ffca | ||
|
|
0a7f9282cc | ||
|
|
6d6e67bbba | ||
|
|
1a6c6ad9f5 | ||
|
|
1feb1679ff | ||
|
|
441607f0da | ||
|
|
33b2d856bc | ||
|
|
de9d11e2f3 | ||
|
|
b43ed3e807 | ||
|
|
035bae98d9 | ||
|
|
82665bd4e6 | ||
|
|
82d215f58b | ||
|
|
52747158e9 | ||
|
|
1019169100 | ||
|
|
5dbb2be873 | ||
|
|
9f463c80bc | ||
|
|
aa19e5bde1 | ||
|
|
7c1de45a2a | ||
|
|
ce34a28776 | ||
|
|
edb8efd033 | ||
|
|
b3da19cbaf | ||
|
|
e2caf66c19 | ||
|
|
a660f4a31b | ||
|
|
05f34de5ad | ||
|
|
a5c38fcf6d | ||
|
|
f821f2b482 | ||
|
|
e9c9db892c | ||
|
|
1349958507 | ||
|
|
d660f3f999 | ||
|
|
6929496c4f | ||
|
|
b7f55bcf70 | ||
|
|
14a5a9ca33 | ||
|
|
0b1f259cee | ||
|
|
4d055a58e9 | ||
|
|
462645f2e7 | ||
|
|
db27b0bd0e | ||
|
|
a8992f6219 | ||
|
|
c71bc6229a | ||
|
|
2bfad8b441 | ||
|
|
7ee342bfe0 | ||
|
|
ea59e39159 | ||
|
|
a29c90e86b | ||
|
|
5f3f7890aa | ||
|
|
e1353bbcdd | ||
|
|
90caad474b | ||
|
|
02a40ba7be | ||
|
|
9a85857f1d | ||
|
|
1d30744f77 | ||
|
|
133544b500 |
No files matched your search
@@ -0,0 +1,52 @@
|
|||||||
|
name: bug report
|
||||||
|
description: something isn't working right
|
||||||
|
labels: ["bug"]
|
||||||
|
body:
|
||||||
|
- type: textarea
|
||||||
|
id: description
|
||||||
|
attributes:
|
||||||
|
label: what happened
|
||||||
|
description: describe what went wrong and what you expected to happen instead.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
id: steps
|
||||||
|
attributes:
|
||||||
|
label: steps to reproduce
|
||||||
|
description: how can we trigger this?
|
||||||
|
placeholder: |
|
||||||
|
1. open rmcl
|
||||||
|
2. do this
|
||||||
|
3. then this
|
||||||
|
4. it breaks
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: input
|
||||||
|
id: version
|
||||||
|
attributes:
|
||||||
|
label: rmcl version
|
||||||
|
description: run `rmcl --version` or check the bottom of the TUI.
|
||||||
|
placeholder: 0.3.0
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: dropdown
|
||||||
|
id: os
|
||||||
|
attributes:
|
||||||
|
label: operating system
|
||||||
|
options:
|
||||||
|
- Linux
|
||||||
|
- macOS
|
||||||
|
- Windows
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
id: context
|
||||||
|
attributes:
|
||||||
|
label: additional context
|
||||||
|
description: anything else that might help. screenshots, config changes, etc.
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
blank_issues_enabled: true
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
name: crash report
|
||||||
|
description: rmcl crashed or panicked
|
||||||
|
labels: ["crash"]
|
||||||
|
body:
|
||||||
|
- type: textarea
|
||||||
|
id: description
|
||||||
|
attributes:
|
||||||
|
label: what happened
|
||||||
|
description: what were you doing when rmcl crashed?
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
id: logs
|
||||||
|
attributes:
|
||||||
|
label: logs
|
||||||
|
description: |
|
||||||
|
paste relevant log output here. you can find logs at:
|
||||||
|
|
||||||
|
- **rmcl logs**: `~/.cache/rmcl/` (per-session files like `rmcl_2026-04-20_12-34-56.log`)
|
||||||
|
- **launch logs**: `~/.local/share/rmcl/instances/{instance}/.minecraft/logs/launches/`
|
||||||
|
|
||||||
|
you can also view logs in the TUI via the log overlay or use `rmcl log` from the CLI.
|
||||||
|
render: text
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
|
|
||||||
|
- type: input
|
||||||
|
id: version
|
||||||
|
attributes:
|
||||||
|
label: rmcl version
|
||||||
|
description: run `rmcl --version` or check the bottom of the TUI.
|
||||||
|
placeholder: 0.3.0
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: dropdown
|
||||||
|
id: os
|
||||||
|
attributes:
|
||||||
|
label: operating system
|
||||||
|
options:
|
||||||
|
- Linux
|
||||||
|
- macOS
|
||||||
|
- Windows
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
id: context
|
||||||
|
attributes:
|
||||||
|
label: additional context
|
||||||
|
description: minecraft version, loader, instance setup, anything that might help narrow it down.
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
name: feature request
|
||||||
|
description: suggest something new or an improvement to something existing
|
||||||
|
labels: ["enhancement"]
|
||||||
|
body:
|
||||||
|
- type: textarea
|
||||||
|
id: description
|
||||||
|
attributes:
|
||||||
|
label: what would you like
|
||||||
|
description: describe the feature or improvement. if it's solving a problem, explain the problem too.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
id: alternatives
|
||||||
|
attributes:
|
||||||
|
label: alternatives or workarounds
|
||||||
|
description: is there anything you're currently doing instead? other approaches you've considered?
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
id: context
|
||||||
|
attributes:
|
||||||
|
label: additional context
|
||||||
|
description: anything else. mockups, links, examples from other tools, etc.
|
||||||
|
validations:
|
||||||
|
required: false
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
- name: install JDK
|
||||||
|
uses: actions/setup-java@v5
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: "21"
|
||||||
+36
-91
@@ -1,4 +1,4 @@
|
|||||||
name: build
|
name: ci
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
@@ -7,110 +7,55 @@ on:
|
|||||||
branches: [master]
|
branches: [master]
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ci-${{ github.ref }}
|
||||||
|
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||||
|
|
||||||
|
env:
|
||||||
|
CARGO_TERM_COLOR: always
|
||||||
|
RUST_BACKTRACE: 1
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
verify:
|
||||||
strategy:
|
name: ${{ matrix.os }}
|
||||||
matrix:
|
|
||||||
include:
|
|
||||||
- os: ubuntu-latest
|
|
||||||
target: x86_64-unknown-linux-gnu
|
|
||||||
artifact: mcl
|
|
||||||
- os: ubuntu-latest
|
|
||||||
target: aarch64-unknown-linux-gnu
|
|
||||||
artifact: mcl
|
|
||||||
- os: windows-latest
|
|
||||||
target: x86_64-pc-windows-msvc
|
|
||||||
artifact: mcl.exe
|
|
||||||
- os: macos-latest
|
|
||||||
target: x86_64-apple-darwin
|
|
||||||
artifact: mcl
|
|
||||||
- os: macos-latest
|
|
||||||
target: aarch64-apple-darwin
|
|
||||||
artifact: mcl
|
|
||||||
|
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v6
|
||||||
|
|
||||||
- name: install Rust
|
- name: install Rust
|
||||||
uses: dtolnay/rust-toolchain@stable
|
uses: dtolnay/rust-toolchain@stable
|
||||||
with:
|
with:
|
||||||
targets: ${{ matrix.target }}
|
components: clippy
|
||||||
|
|
||||||
|
- name: install JDK
|
||||||
|
uses: actions/setup-java@v5
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: "21"
|
||||||
|
|
||||||
- uses: Swatinem/rust-cache@v2
|
- uses: Swatinem/rust-cache@v2
|
||||||
with:
|
with:
|
||||||
key: ${{ matrix.target }}
|
key: ${{ matrix.os }}
|
||||||
|
|
||||||
- name: install cross-compilation deps (aarch64-linux)
|
- name: cargo check
|
||||||
if: matrix.target == 'aarch64-unknown-linux-gnu'
|
run: cargo check --locked --all-targets
|
||||||
run: |
|
|
||||||
sudo apt-get update
|
|
||||||
sudo apt-get install -y gcc-aarch64-linux-gnu g++-aarch64-linux-gnu
|
|
||||||
|
|
||||||
- name: build
|
- name: cargo clippy
|
||||||
env:
|
run: cargo clippy --all-targets --locked -- -D warnings
|
||||||
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
|
|
||||||
run: cargo build --release --target ${{ matrix.target }}
|
|
||||||
|
|
||||||
- name: package (unix)
|
- name: cargo test
|
||||||
if: runner.os != 'Windows'
|
run: cargo test --locked --all-targets
|
||||||
run: |
|
|
||||||
cd target/${{ matrix.target }}/release
|
|
||||||
tar czf ../../../mcl-${{ matrix.target }}.tar.gz ${{ matrix.artifact }}
|
|
||||||
|
|
||||||
- name: package (windows)
|
- name: cargo build
|
||||||
if: runner.os == 'Windows'
|
run: cargo build --locked
|
||||||
run: |
|
|
||||||
cd target/${{ matrix.target }}/release
|
|
||||||
Compress-Archive -Path ${{ matrix.artifact }} -DestinationPath ../../../mcl-${{ matrix.target }}.zip
|
|
||||||
|
|
||||||
- name: upload artifact
|
- name: cargo test --ignored (network canaries, master only)
|
||||||
uses: actions/upload-artifact@v4
|
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
|
||||||
with:
|
run: cargo test --locked --all-targets -- --ignored
|
||||||
name: mcl-${{ matrix.target }}
|
|
||||||
path: mcl-${{ matrix.target }}.*
|
|
||||||
|
|
||||||
release:
|
|
||||||
needs: build
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
if: github.ref == 'refs/heads/master' && github.event_name == 'push'
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: get version
|
|
||||||
id: version
|
|
||||||
run: |
|
|
||||||
version=$(grep '^version' Cargo.toml | head -1 | sed 's/.*"\(.*\)".*/\1/')
|
|
||||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
|
||||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
|
||||||
|
|
||||||
- name: check if release exists
|
|
||||||
id: check
|
|
||||||
run: |
|
|
||||||
if gh release view "${{ steps.version.outputs.tag }}" > /dev/null 2>&1; then
|
|
||||||
echo "exists=true" >> "$GITHUB_OUTPUT"
|
|
||||||
else
|
|
||||||
echo "exists=false" >> "$GITHUB_OUTPUT"
|
|
||||||
fi
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- name: download artifacts
|
|
||||||
if: steps.check.outputs.exists == 'false'
|
|
||||||
uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
path: artifacts
|
|
||||||
|
|
||||||
- name: create release
|
|
||||||
if: steps.check.outputs.exists == 'false'
|
|
||||||
run: |
|
|
||||||
gh release create "${{ steps.version.outputs.tag }}" \
|
|
||||||
--title "${{ steps.version.outputs.tag }}" \
|
|
||||||
--generate-notes \
|
|
||||||
artifacts/mcl-*/*
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
name: publish aur
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
plan:
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
env:
|
||||||
|
PLAN: ${{ inputs.plan }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
ref: ${{ fromJson(inputs.plan).announcement_tag }}
|
||||||
|
|
||||||
|
- name: get version
|
||||||
|
id: version
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
version="$(jq --raw-output '.releases[0].app_version' <<< "$PLAN")"
|
||||||
|
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: prepare rmcl
|
||||||
|
run: |
|
||||||
|
sed -i "s|^pkgver=.*|pkgver=${{ steps.version.outputs.version }}|" pkg/rmcl/PKGBUILD
|
||||||
|
cp pkg/rmcl/PKGBUILD PKGBUILD
|
||||||
|
|
||||||
|
- name: update checksums for rmcl
|
||||||
|
uses: datakrama/archlinux-package-action@v2
|
||||||
|
with:
|
||||||
|
updpkgsums: true
|
||||||
|
srcinfo: true
|
||||||
|
flags: ""
|
||||||
|
namcap: false
|
||||||
|
|
||||||
|
- name: publish rmcl to AUR
|
||||||
|
uses: KSXGitHub/github-actions-deploy-aur@v4.1.3
|
||||||
|
with:
|
||||||
|
pkgname: rmcl
|
||||||
|
pkgbuild: PKGBUILD
|
||||||
|
assets: .SRCINFO
|
||||||
|
commit_username: objz
|
||||||
|
commit_email: me@objz.dev
|
||||||
|
ssh_private_key: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
|
||||||
|
commit_message: "Update to ${{ steps.version.outputs.version }}"
|
||||||
|
|
||||||
|
- name: prepare rmcl-bin
|
||||||
|
run: |
|
||||||
|
sed -i "s|^pkgver=.*|pkgver=${{ steps.version.outputs.version }}|" pkg/rmcl-bin/PKGBUILD
|
||||||
|
sed -i "s|^pkgrel=.*|pkgrel=1|" pkg/rmcl-bin/PKGBUILD
|
||||||
|
cp pkg/rmcl-bin/PKGBUILD PKGBUILD
|
||||||
|
rm -f .SRCINFO
|
||||||
|
|
||||||
|
- name: update checksums for rmcl-bin
|
||||||
|
uses: datakrama/archlinux-package-action@v2
|
||||||
|
with:
|
||||||
|
updpkgsums: true
|
||||||
|
srcinfo: true
|
||||||
|
flags: ""
|
||||||
|
namcap: false
|
||||||
|
|
||||||
|
- name: publish rmcl-bin to AUR
|
||||||
|
uses: KSXGitHub/github-actions-deploy-aur@v4.1.3
|
||||||
|
with:
|
||||||
|
pkgname: rmcl-bin
|
||||||
|
pkgbuild: PKGBUILD
|
||||||
|
assets: .SRCINFO
|
||||||
|
commit_username: objz
|
||||||
|
commit_email: me@objz.dev
|
||||||
|
ssh_private_key: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
|
||||||
|
commit_message: "Update to ${{ steps.version.outputs.version }}"
|
||||||
|
|
||||||
|
- name: prepare rmcl-git
|
||||||
|
run: |
|
||||||
|
cp pkg/rmcl-git/PKGBUILD PKGBUILD
|
||||||
|
rm -f .SRCINFO
|
||||||
|
|
||||||
|
- name: update metadata for rmcl-git
|
||||||
|
uses: datakrama/archlinux-package-action@v2
|
||||||
|
with:
|
||||||
|
updpkgsums: true
|
||||||
|
srcinfo: true
|
||||||
|
flags: ""
|
||||||
|
namcap: false
|
||||||
|
|
||||||
|
- name: publish rmcl-git to AUR
|
||||||
|
uses: KSXGitHub/github-actions-deploy-aur@v4.1.3
|
||||||
|
with:
|
||||||
|
pkgname: rmcl-git
|
||||||
|
pkgbuild: PKGBUILD
|
||||||
|
assets: .SRCINFO
|
||||||
|
commit_username: objz
|
||||||
|
commit_email: me@objz.dev
|
||||||
|
ssh_private_key: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
|
||||||
|
commit_message: "Update package metadata"
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
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
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
name: publish crates
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
plan:
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
dry_run:
|
||||||
|
required: false
|
||||||
|
type: boolean
|
||||||
|
default: true
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
plan:
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
dry_run:
|
||||||
|
required: false
|
||||||
|
type: boolean
|
||||||
|
default: false
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
ref: ${{ fromJson(inputs.plan).announcement_tag }}
|
||||||
|
|
||||||
|
- name: install Rust
|
||||||
|
uses: dtolnay/rust-toolchain@stable
|
||||||
|
|
||||||
|
- name: publish to crates.io
|
||||||
|
run: |
|
||||||
|
if [ "${{ inputs.dry_run }}" = "true" ]; then
|
||||||
|
cargo publish --allow-dirty --dry-run
|
||||||
|
else
|
||||||
|
cargo publish --allow-dirty
|
||||||
|
fi
|
||||||
|
env:
|
||||||
|
CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
name: publish winget
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
plan:
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
runs-on: windows-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: prepare WinGet manifest
|
||||||
|
id: manifest
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
PLAN: ${{ inputs.plan }}
|
||||||
|
run: |
|
||||||
|
$plan = $env:PLAN | ConvertFrom-Json
|
||||||
|
$tag = $plan.announcement_tag
|
||||||
|
$version = $plan.releases[0].app_version
|
||||||
|
$identifier = 'Objz.Rmcl'
|
||||||
|
$packagePath = "manifests/o/Objz/Rmcl/$version"
|
||||||
|
$assetPath = "winget-manifest-$version.zip"
|
||||||
|
$installerFile = 'rmcl-x86_64-pc-windows-msvc.msi'
|
||||||
|
$checksumFile = "$installerFile.sha256"
|
||||||
|
$installerUrl = "https://github.com/objz/rmcl/releases/download/$tag/$installerFile"
|
||||||
|
$checksumUrl = "https://github.com/objz/rmcl/releases/download/$tag/$checksumFile"
|
||||||
|
|
||||||
|
New-Item -ItemType Directory -Path $packagePath -Force | Out-Null
|
||||||
|
Invoke-WebRequest -Uri $checksumUrl -OutFile "$packagePath/$checksumFile"
|
||||||
|
$checksum = (((Get-Content "$packagePath/$checksumFile" -Raw) -split '\s+')[0]).ToUpperInvariant()
|
||||||
|
|
||||||
|
$versionManifest = @(
|
||||||
|
'# yaml-language-server: $schema=https://aka.ms/winget-manifest.version.1.9.0.schema.json'
|
||||||
|
"PackageIdentifier: $identifier"
|
||||||
|
"PackageVersion: $version"
|
||||||
|
'DefaultLocale: en-US'
|
||||||
|
'ManifestType: version'
|
||||||
|
'ManifestVersion: 1.9.0'
|
||||||
|
) -join "`n"
|
||||||
|
$versionManifest | Set-Content -Path "$packagePath/$identifier.yaml" -Encoding utf8
|
||||||
|
|
||||||
|
$installerManifest = @(
|
||||||
|
'# yaml-language-server: $schema=https://aka.ms/winget-manifest.installer.1.9.0.schema.json'
|
||||||
|
"PackageIdentifier: $identifier"
|
||||||
|
"PackageVersion: $version"
|
||||||
|
'InstallerType: wix'
|
||||||
|
'Scope: machine'
|
||||||
|
'InstallerSwitches:'
|
||||||
|
' Silent: /quiet /norestart'
|
||||||
|
' SilentWithProgress: /passive /norestart'
|
||||||
|
'UpgradeBehavior: install'
|
||||||
|
'Commands:'
|
||||||
|
'- rmcl'
|
||||||
|
'Installers:'
|
||||||
|
'- Architecture: x64'
|
||||||
|
" InstallerUrl: $installerUrl"
|
||||||
|
" InstallerSha256: $checksum"
|
||||||
|
'ManifestType: installer'
|
||||||
|
'ManifestVersion: 1.9.0'
|
||||||
|
) -join "`n"
|
||||||
|
$installerManifest | Set-Content -Path "$packagePath/$identifier.installer.yaml" -Encoding utf8
|
||||||
|
|
||||||
|
$localeManifest = @(
|
||||||
|
'# yaml-language-server: $schema=https://aka.ms/winget-manifest.defaultLocale.1.9.0.schema.json'
|
||||||
|
"PackageIdentifier: $identifier"
|
||||||
|
"PackageVersion: $version"
|
||||||
|
'PackageLocale: en-US'
|
||||||
|
'Publisher: objz'
|
||||||
|
'PublisherUrl: https://github.com/objz'
|
||||||
|
'PublisherSupportUrl: https://github.com/objz/rmcl/issues'
|
||||||
|
'Author: objz'
|
||||||
|
'PackageName: rmcl'
|
||||||
|
'PackageUrl: https://github.com/objz/rmcl'
|
||||||
|
'License: GPL-3.0-only'
|
||||||
|
'LicenseUrl: https://github.com/objz/rmcl/blob/master/LICENSE'
|
||||||
|
'Copyright: Copyright (c) objz'
|
||||||
|
'ShortDescription: Minecraft launcher TUI'
|
||||||
|
'Description: A fully featured Minecraft launcher TUI with Microsoft account authentication, instance management, mod loaders, imports, content management, and launch support.'
|
||||||
|
'Moniker: rmcl'
|
||||||
|
'Tags:'
|
||||||
|
'- minecraft'
|
||||||
|
'- launcher'
|
||||||
|
'- cli'
|
||||||
|
'- tui'
|
||||||
|
'ManifestType: defaultLocale'
|
||||||
|
'ManifestVersion: 1.9.0'
|
||||||
|
) -join "`n"
|
||||||
|
$localeManifest | Set-Content -Path "$packagePath/$identifier.locale.en-US.yaml" -Encoding utf8
|
||||||
|
|
||||||
|
Remove-Item "$packagePath/$checksumFile"
|
||||||
|
Compress-Archive -Path manifests -DestinationPath $assetPath -Force
|
||||||
|
|
||||||
|
"path=$packagePath" >> $env:GITHUB_OUTPUT
|
||||||
|
"asset=$assetPath" >> $env:GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: upload WinGet manifest to GitHub Release
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
GH_REPO: ${{ github.repository }}
|
||||||
|
PLAN: ${{ inputs.plan }}
|
||||||
|
run: |
|
||||||
|
$plan = $env:PLAN | ConvertFrom-Json
|
||||||
|
gh release upload "$($plan.announcement_tag)" "${{ steps.manifest.outputs.asset }}" --clobber
|
||||||
|
|
||||||
|
- name: submit WinGet manifest
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
Invoke-WebRequest -Uri https://aka.ms/wingetcreate/latest -OutFile wingetcreate.exe
|
||||||
|
.\wingetcreate.exe submit "${{ steps.manifest.outputs.path }}" --token "${{ secrets.WINGET_TOKEN }}"
|
||||||
@@ -0,0 +1,472 @@
|
|||||||
|
# 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
|
||||||
|
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:
|
||||||
|
pull_request:
|
||||||
|
workflow_dispatch:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- '**[0-9]+.[0-9]+.[0-9]+*'
|
||||||
|
|
||||||
|
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: ${{ !github.event.pull_request && github.ref_name || '' }}
|
||||||
|
tag-flag: ${{ !github.event.pull_request && format('--tag={0}', github.ref_name) || '' }}
|
||||||
|
publishing: ${{ !github.event.pull_request }}
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
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 ${{ (!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-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) |
|
||||||
|
|
||||||
|
## 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
|
||||||
|
|
||||||
|
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"
|
||||||
|
|
||||||
|
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:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
submodules: recursive
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
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}"
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
# Contributor Covenant Code of Conduct
|
||||||
|
|
||||||
|
## Our Pledge
|
||||||
|
|
||||||
|
We as members, contributors, and leaders pledge to make participation in our
|
||||||
|
community a harassment-free experience for everyone, regardless of age, body
|
||||||
|
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||||
|
identity and expression, level of experience, education, socio-economic status,
|
||||||
|
nationality, personal appearance, race, religion, or sexual identity
|
||||||
|
and orientation.
|
||||||
|
|
||||||
|
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||||
|
diverse, inclusive, and healthy community.
|
||||||
|
|
||||||
|
## Our Standards
|
||||||
|
|
||||||
|
Examples of behavior that contributes to a positive environment for our
|
||||||
|
community include:
|
||||||
|
|
||||||
|
* Demonstrating empathy and kindness toward other people
|
||||||
|
* Being respectful of differing opinions, viewpoints, and experiences
|
||||||
|
* Giving and gracefully accepting constructive feedback
|
||||||
|
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||||
|
and learning from the experience
|
||||||
|
* Focusing on what is best not just for us as individuals, but for the
|
||||||
|
overall community
|
||||||
|
|
||||||
|
Examples of unacceptable behavior include:
|
||||||
|
|
||||||
|
* The use of sexualized language or imagery, and sexual attention or
|
||||||
|
advances of any kind
|
||||||
|
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||||
|
* Public or private harassment
|
||||||
|
* Publishing others' private information, such as a physical or email
|
||||||
|
address, without their explicit permission
|
||||||
|
* Other conduct which could reasonably be considered inappropriate in a
|
||||||
|
professional setting
|
||||||
|
|
||||||
|
## Enforcement Responsibilities
|
||||||
|
|
||||||
|
Community leaders are responsible for clarifying and enforcing our standards of
|
||||||
|
acceptable behavior and will take appropriate and fair corrective action in
|
||||||
|
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||||
|
or harmful.
|
||||||
|
|
||||||
|
Community leaders have the right and responsibility to remove, edit, or reject
|
||||||
|
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||||
|
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||||
|
decisions when appropriate.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
This Code of Conduct applies within all community spaces, and also applies when
|
||||||
|
an individual is officially representing the community in public spaces.
|
||||||
|
Examples of representing our community include using an official e-mail address,
|
||||||
|
posting via an official social media account, or acting as an appointed
|
||||||
|
representative at an online or offline event.
|
||||||
|
|
||||||
|
## Enforcement
|
||||||
|
|
||||||
|
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||||
|
reported to the community leaders responsible for enforcement at
|
||||||
|
me@objz.dev.
|
||||||
|
All complaints will be reviewed and investigated promptly and fairly.
|
||||||
|
|
||||||
|
All community leaders are obligated to respect the privacy and security of the
|
||||||
|
reporter of any incident.
|
||||||
|
|
||||||
|
## Enforcement Guidelines
|
||||||
|
|
||||||
|
Community leaders will follow these Community Impact Guidelines in determining
|
||||||
|
the consequences for any action they deem in violation of this Code of Conduct:
|
||||||
|
|
||||||
|
### 1. Correction
|
||||||
|
|
||||||
|
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||||
|
unprofessional or unwelcome in the community.
|
||||||
|
|
||||||
|
**Consequence**: A private, written warning from community leaders, providing
|
||||||
|
clarity around the nature of the violation and an explanation of why the
|
||||||
|
behavior was inappropriate. A public apology may be requested.
|
||||||
|
|
||||||
|
### 2. Warning
|
||||||
|
|
||||||
|
**Community Impact**: A violation through a single incident or series
|
||||||
|
of actions.
|
||||||
|
|
||||||
|
**Consequence**: A warning with consequences for continued behavior. No
|
||||||
|
interaction with the people involved, including unsolicited interaction with
|
||||||
|
those enforcing the Code of Conduct, for a specified period of time. This
|
||||||
|
includes avoiding interactions in community spaces as well as external channels
|
||||||
|
like social media. Violating these terms may lead to a temporary or
|
||||||
|
permanent ban.
|
||||||
|
|
||||||
|
### 3. Temporary Ban
|
||||||
|
|
||||||
|
**Community Impact**: A serious violation of community standards, including
|
||||||
|
sustained inappropriate behavior.
|
||||||
|
|
||||||
|
**Consequence**: A temporary ban from any sort of interaction or public
|
||||||
|
communication with the community for a specified period of time. No public or
|
||||||
|
private interaction with the people involved, including unsolicited interaction
|
||||||
|
with those enforcing the Code of Conduct, is allowed during this period.
|
||||||
|
Violating these terms may lead to a permanent ban.
|
||||||
|
|
||||||
|
### 4. Permanent Ban
|
||||||
|
|
||||||
|
**Community Impact**: Demonstrating a pattern of violation of community
|
||||||
|
standards, including sustained inappropriate behavior, harassment of an
|
||||||
|
individual, or aggression toward or disparagement of classes of individuals.
|
||||||
|
|
||||||
|
**Consequence**: A permanent ban from any sort of public interaction within
|
||||||
|
the community.
|
||||||
|
|
||||||
|
## Attribution
|
||||||
|
|
||||||
|
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||||
|
version 2.0, available at
|
||||||
|
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
||||||
|
|
||||||
|
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||||
|
enforcement ladder](https://github.com/mozilla/diversity).
|
||||||
|
|
||||||
|
[homepage]: https://www.contributor-covenant.org
|
||||||
|
|
||||||
|
For answers to common questions about this code of conduct, see the FAQ at
|
||||||
|
https://www.contributor-covenant.org/faq. Translations are available at
|
||||||
|
https://www.contributor-covenant.org/translations.
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# contributing
|
||||||
|
|
||||||
|
thanks for wanting to contribute. here's how we/I do things around here.
|
||||||
|
|
||||||
|
## code style
|
||||||
|
|
||||||
|
### comments
|
||||||
|
|
||||||
|
preferred are `//` comments with a lowercase, casual tone. try to explain **why** something is done rather than restating what the code does. file-level comments are nice for describing what a file is responsible for, and function-level comments help when the behavior isn't obvious. enum variants and struct fields usually don't need comments if the names are clear enough. basically just look at how existing comments are written and match that vibe.
|
||||||
|
|
||||||
|
### visibility and naming
|
||||||
|
|
||||||
|
try to keep visibility as narrow as makes sense. `pub` when something is actually used outside the crate, `pub(crate)` across modules, `pub(super)` within a module. don't leave things `pub` just because they might be useful someday. function names should ideally be clear enough that you don't need a comment to explain what they do.
|
||||||
|
|
||||||
|
### modules and file organization
|
||||||
|
|
||||||
|
each file should have one clear responsibility. if a file starts doing two unrelated things, split it up. when a module gets big enough, convert `foo.rs` into `foo/mod.rs` with submodules. keep format-specific or protocol-specific code in its own file (e.g. `mrpack.rs` for modrinth, `mmc.rs` for multimc) and put shared types and dispatching in `mod.rs`. the general idea is that you shouldn't find multimc logic in the modrinth file or vice versa.
|
||||||
|
|
||||||
|
### tests
|
||||||
|
|
||||||
|
every test should cover a distinct code path. don't test the same branch twice with just different inputs. test names should describe the scenario, not just the function name. no need to test trivially correct code.
|
||||||
|
|
||||||
|
### general advice
|
||||||
|
|
||||||
|
- avoid "obvious" comments like `// save the profile` right above `save_profile()`
|
||||||
|
- avoid unnecessary abstractions or wrappers for things that only happen once
|
||||||
|
- avoid speculative features or "just in case" parameters
|
||||||
|
- prefer iterating directly over collecting into a vec when you only need one pass
|
||||||
|
- match existing error handling patterns, usually `map_err` with `format!`
|
||||||
|
|
||||||
|
## architecture
|
||||||
|
|
||||||
|
the codebase is split roughly like this:
|
||||||
|
|
||||||
|
- `src/cli/` handles command line interface
|
||||||
|
- `src/config/` has settings, paths, theme config
|
||||||
|
- `src/instance/` is the core. `content/` scans mods, resource packs, shaders, worlds. `import/` handles modpack importing with `mod.rs` dispatching to format-specific modules like `mrpack.rs` and `mmc.rs`. `loader/` installs mod loaders (fabric, forge, neoforge, quilt). `launch/` builds the java command and spawns minecraft, with `patches.rs` handling lwjgl3ify classpath patches. `manager.rs` does instance CRUD
|
||||||
|
- `src/net/` is the networking layer. http client, file downloads, and API clients per service
|
||||||
|
- `src/tui/` is the terminal UI built with ratatui
|
||||||
|
|
||||||
|
### adding a new import format
|
||||||
|
|
||||||
|
create a new file in `src/instance/import/`, add the variant to `PackFormat` in `mod.rs`, add detection logic in `detect_format()`, and add the dispatch arms in `build_summary()` and `execute_import()`.
|
||||||
|
|
||||||
|
### adding a new mod loader
|
||||||
|
|
||||||
|
create a new file in `src/instance/loader/` implementing `ModLoaderInstaller`, add the variant to `ModLoader` in `models.rs`, and register it in `get_installer()`.
|
||||||
|
|
||||||
|
## commits
|
||||||
|
|
||||||
|
start with what you did: `added`, `fixed`, `refactored`, etc. lowercase. separate logical changes into separate commits. don't bundle unrelated things into one commit.
|
||||||
|
|
||||||
|
## before submitting
|
||||||
|
|
||||||
|
make sure `cargo build`, `cargo clippy`, and `cargo test` all pass. you'll need a JDK (`javac` and `jar` on PATH) for the build script that compiles the java shim.
|
||||||
Generated
+500
-90
@@ -19,13 +19,13 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "aes"
|
name = "aes"
|
||||||
version = "0.8.4"
|
version = "0.9.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
|
checksum = "66bd29a732b644c0431c6140f370d097879203d79b80c94a6747ba0872adaef8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
|
||||||
"cipher",
|
"cipher",
|
||||||
"cpufeatures",
|
"cpubits",
|
||||||
|
"cpufeatures 0.3.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -120,6 +120,16 @@ version = "0.5.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236"
|
checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "assert-json-diff"
|
||||||
|
version = "2.0.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12"
|
||||||
|
dependencies = [
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "async-trait"
|
name = "async-trait"
|
||||||
version = "0.1.89"
|
version = "0.1.89"
|
||||||
@@ -234,6 +244,16 @@ dependencies = [
|
|||||||
"generic-array",
|
"generic-array",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "block-buffer"
|
||||||
|
version = "0.12.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cdd35008169921d80bc60d3d0ab416eecb028c4cd653352907921d95084790be"
|
||||||
|
dependencies = [
|
||||||
|
"hybrid-array",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bon"
|
name = "bon"
|
||||||
version = "3.9.1"
|
version = "3.9.1"
|
||||||
@@ -323,9 +343,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cc"
|
name = "cc"
|
||||||
version = "1.2.60"
|
version = "1.2.61"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "43c5703da9466b66a946814e1adf53ea2c90f10063b86290cc9eb67ce3478a20"
|
checksum = "d16d90359e986641506914ba71350897565610e87ce0ad9e6f28569db3dd5c6d"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"find-msvc-tools",
|
"find-msvc-tools",
|
||||||
"jobserver",
|
"jobserver",
|
||||||
@@ -361,11 +381,11 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cipher"
|
name = "cipher"
|
||||||
version = "0.4.4"
|
version = "0.5.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
|
checksum = "e34d8227fe1ba289043aeb13792056ff80fd6de1a9f49137a5f499de8e8c78ea"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"crypto-common",
|
"crypto-common 0.2.1",
|
||||||
"inout",
|
"inout",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -396,6 +416,12 @@ version = "1.1.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
|
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cmov"
|
||||||
|
version = "0.5.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3f88a43d011fc4a6876cb7344703e297c71dda42494fee094d5f7c76bf13f746"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "color-eyre"
|
name = "color-eyre"
|
||||||
version = "0.6.5"
|
version = "0.6.5"
|
||||||
@@ -464,6 +490,23 @@ dependencies = [
|
|||||||
"yaml-rust2",
|
"yaml-rust2",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "console"
|
||||||
|
version = "0.16.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d64e8af5551369d19cf50138de61f1c42074ab970f74e99be916646777f8fc87"
|
||||||
|
dependencies = [
|
||||||
|
"encode_unicode",
|
||||||
|
"libc",
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "const-oid"
|
||||||
|
version = "0.10.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "const-random"
|
name = "const-random"
|
||||||
version = "0.1.18"
|
version = "0.1.18"
|
||||||
@@ -514,6 +557,12 @@ version = "0.8.7"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cpubits"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5ef0c543070d296ea414df2dd7625d1b24866ce206709d8a4a424f28377f5861"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cpufeatures"
|
name = "cpufeatures"
|
||||||
version = "0.2.17"
|
version = "0.2.17"
|
||||||
@@ -523,6 +572,15 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cpufeatures"
|
||||||
|
version = "0.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "crc32fast"
|
name = "crc32fast"
|
||||||
version = "1.5.0"
|
version = "1.5.0"
|
||||||
@@ -627,6 +685,15 @@ dependencies = [
|
|||||||
"typenum",
|
"typenum",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crypto-common"
|
||||||
|
version = "0.2.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "77727bb15fa921304124b128af125e7e3b968275d1b108b379190264f4423710"
|
||||||
|
dependencies = [
|
||||||
|
"hybrid-array",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "csscolorparser"
|
name = "csscolorparser"
|
||||||
version = "0.6.2"
|
version = "0.6.2"
|
||||||
@@ -637,6 +704,15 @@ dependencies = [
|
|||||||
"phf",
|
"phf",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ctutils"
|
||||||
|
version = "0.4.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"
|
||||||
|
dependencies = [
|
||||||
|
"cmov",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "darling"
|
name = "darling"
|
||||||
version = "0.21.3"
|
version = "0.21.3"
|
||||||
@@ -706,6 +782,24 @@ dependencies = [
|
|||||||
"syn 2.0.117",
|
"syn 2.0.117",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "deadpool"
|
||||||
|
version = "0.12.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0be2b1d1d6ec8d846f05e137292d0b89133caf95ef33695424c09568bdd39b1b"
|
||||||
|
dependencies = [
|
||||||
|
"deadpool-runtime",
|
||||||
|
"lazy_static",
|
||||||
|
"num_cpus",
|
||||||
|
"tokio",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "deadpool-runtime"
|
||||||
|
version = "0.1.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "deflate64"
|
name = "deflate64"
|
||||||
version = "0.1.12"
|
version = "0.1.12"
|
||||||
@@ -778,9 +872,21 @@ version = "0.10.7"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"block-buffer",
|
"block-buffer 0.10.4",
|
||||||
"crypto-common",
|
"crypto-common 0.1.7",
|
||||||
"subtle",
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "digest"
|
||||||
|
version = "0.11.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4850db49bf08e663084f7fb5c87d202ef91a3907271aff24a94eb97ff039153c"
|
||||||
|
dependencies = [
|
||||||
|
"block-buffer 0.12.0",
|
||||||
|
"const-oid",
|
||||||
|
"crypto-common 0.2.1",
|
||||||
|
"ctutils",
|
||||||
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -860,6 +966,12 @@ version = "1.15.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
|
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "encode_unicode"
|
||||||
|
version = "1.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "encoding_rs"
|
name = "encoding_rs"
|
||||||
version = "0.8.35"
|
version = "0.8.35"
|
||||||
@@ -1023,12 +1135,36 @@ dependencies = [
|
|||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "fsevent-sys"
|
||||||
|
version = "4.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "funty"
|
name = "funty"
|
||||||
version = "2.0.0"
|
version = "2.0.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
|
checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "futures"
|
||||||
|
version = "0.3.32"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d"
|
||||||
|
dependencies = [
|
||||||
|
"futures-channel",
|
||||||
|
"futures-core",
|
||||||
|
"futures-executor",
|
||||||
|
"futures-io",
|
||||||
|
"futures-sink",
|
||||||
|
"futures-task",
|
||||||
|
"futures-util",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "futures-channel"
|
name = "futures-channel"
|
||||||
version = "0.3.32"
|
version = "0.3.32"
|
||||||
@@ -1036,6 +1172,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
|
checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"futures-core",
|
"futures-core",
|
||||||
|
"futures-sink",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1044,6 +1181,17 @@ version = "0.3.32"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
|
checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "futures-executor"
|
||||||
|
version = "0.3.32"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d"
|
||||||
|
dependencies = [
|
||||||
|
"futures-core",
|
||||||
|
"futures-task",
|
||||||
|
"futures-util",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "futures-io"
|
name = "futures-io"
|
||||||
version = "0.3.32"
|
version = "0.3.32"
|
||||||
@@ -1073,12 +1221,19 @@ version = "0.3.32"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
|
checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "futures-timer"
|
||||||
|
version = "3.0.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "futures-util"
|
name = "futures-util"
|
||||||
version = "0.3.32"
|
version = "0.3.32"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
|
checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"futures-channel",
|
||||||
"futures-core",
|
"futures-core",
|
||||||
"futures-io",
|
"futures-io",
|
||||||
"futures-macro",
|
"futures-macro",
|
||||||
@@ -1159,6 +1314,31 @@ version = "0.32.3"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7"
|
checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "glob"
|
||||||
|
version = "0.3.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "h2"
|
||||||
|
version = "0.4.14"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "171fefbc92fe4a4de27e0698d6a5b392d6a0e333506bc49133760b3bcf948733"
|
||||||
|
dependencies = [
|
||||||
|
"atomic-waker",
|
||||||
|
"bytes",
|
||||||
|
"fnv",
|
||||||
|
"futures-core",
|
||||||
|
"futures-sink",
|
||||||
|
"http",
|
||||||
|
"indexmap",
|
||||||
|
"slab",
|
||||||
|
"tokio",
|
||||||
|
"tokio-util",
|
||||||
|
"tracing",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hashbrown"
|
name = "hashbrown"
|
||||||
version = "0.14.5"
|
version = "0.14.5"
|
||||||
@@ -1206,6 +1386,12 @@ version = "0.5.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hermit-abi"
|
||||||
|
version = "0.5.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hex"
|
name = "hex"
|
||||||
version = "0.4.3"
|
version = "0.4.3"
|
||||||
@@ -1214,11 +1400,11 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hmac"
|
name = "hmac"
|
||||||
version = "0.12.1"
|
version = "0.13.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"digest",
|
"digest 0.11.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1260,6 +1446,21 @@ version = "1.10.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "httpdate"
|
||||||
|
version = "1.0.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hybrid-array"
|
||||||
|
version = "0.4.11"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "08d46837a0ed51fe95bd3b05de33cd64a1ee88fc797477ca48446872504507c5"
|
||||||
|
dependencies = [
|
||||||
|
"typenum",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hyper"
|
name = "hyper"
|
||||||
version = "1.9.0"
|
version = "1.9.0"
|
||||||
@@ -1270,9 +1471,11 @@ dependencies = [
|
|||||||
"bytes",
|
"bytes",
|
||||||
"futures-channel",
|
"futures-channel",
|
||||||
"futures-core",
|
"futures-core",
|
||||||
|
"h2",
|
||||||
"http",
|
"http",
|
||||||
"http-body",
|
"http-body",
|
||||||
"httparse",
|
"httparse",
|
||||||
|
"httpdate",
|
||||||
"itoa",
|
"itoa",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
"smallvec",
|
"smallvec",
|
||||||
@@ -1509,12 +1712,44 @@ dependencies = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "inout"
|
name = "inotify"
|
||||||
version = "0.1.4"
|
version = "0.11.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
|
checksum = "bd5b3eaf1a28b758ac0faa5a4254e8ab2705605496f1b1f3fbbc3988ad73d199"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"generic-array",
|
"bitflags 2.11.1",
|
||||||
|
"inotify-sys",
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "inotify-sys"
|
||||||
|
version = "0.1.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "inout"
|
||||||
|
version = "0.2.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
|
||||||
|
dependencies = [
|
||||||
|
"hybrid-array",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "insta"
|
||||||
|
version = "1.47.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7b4a6248eb93a4401ed2f37dfe8ea592d3cf05b7cf4f8efa867b6895af7e094e"
|
||||||
|
dependencies = [
|
||||||
|
"console",
|
||||||
|
"once_cell",
|
||||||
|
"similar",
|
||||||
|
"tempfile",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1588,9 +1823,9 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "jiff"
|
name = "jiff"
|
||||||
version = "0.2.23"
|
version = "0.2.24"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "1a3546dc96b6d42c5f24902af9e2538e82e39ad350b0c766eb3fbf2d8f3d8359"
|
checksum = "f00b5dbd620d61dfdcb6007c9c1f6054ebd75319f163d886a9055cec1155073d"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"jiff-static",
|
"jiff-static",
|
||||||
"jiff-tzdb-platform",
|
"jiff-tzdb-platform",
|
||||||
@@ -1603,9 +1838,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "jiff-static"
|
name = "jiff-static"
|
||||||
version = "0.2.23"
|
version = "0.2.24"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2a8c8b344124222efd714b73bb41f8b5120b27a7cc1c75593a6ff768d9d05aa4"
|
checksum = "e000de030ff8022ea1da3f466fbb0f3a809f5e51ed31f6dd931c35181ad8e6d7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
@@ -1692,6 +1927,26 @@ dependencies = [
|
|||||||
"syn 2.0.117",
|
"syn 2.0.117",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "kqueue"
|
||||||
|
version = "1.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "eac30106d7dce88daf4a3fcb4879ea939476d5074a9b7ddd0fb97fa4bed5596a"
|
||||||
|
dependencies = [
|
||||||
|
"kqueue-sys",
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "kqueue-sys"
|
||||||
|
version = "1.0.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ed9625ffda8729b85e45cf04090035ac368927b8cebc34898e7c120f52e4838b"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 1.3.2",
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "lab"
|
name = "lab"
|
||||||
version = "0.11.0"
|
version = "0.11.0"
|
||||||
@@ -1718,9 +1973,9 @@ checksum = "b3a6a8c165077efc8f3a971534c50ea6a1a18b329ef4a66e897a7e3a1494565f"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libc"
|
name = "libc"
|
||||||
version = "0.2.185"
|
version = "0.2.186"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f"
|
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libm"
|
name = "libm"
|
||||||
@@ -1828,48 +2083,6 @@ dependencies = [
|
|||||||
"regex-automata",
|
"regex-automata",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "mcl"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"async-trait",
|
|
||||||
"chrono",
|
|
||||||
"clap",
|
|
||||||
"color-eyre",
|
|
||||||
"config",
|
|
||||||
"crossterm 0.29.0",
|
|
||||||
"dirs",
|
|
||||||
"dirs-next",
|
|
||||||
"image",
|
|
||||||
"log",
|
|
||||||
"minecraft-msa-auth",
|
|
||||||
"oauth2",
|
|
||||||
"open",
|
|
||||||
"ratatui",
|
|
||||||
"ratatui-image",
|
|
||||||
"ratatui-textarea",
|
|
||||||
"ratatui-themekit",
|
|
||||||
"reqwest",
|
|
||||||
"serde",
|
|
||||||
"serde_json",
|
|
||||||
"tachyonfx",
|
|
||||||
"tempfile",
|
|
||||||
"thiserror 2.0.18",
|
|
||||||
"throbber-widgets-tui",
|
|
||||||
"tokio",
|
|
||||||
"toml",
|
|
||||||
"tracing",
|
|
||||||
"tracing-appender",
|
|
||||||
"tracing-subscriber",
|
|
||||||
"tui-logger",
|
|
||||||
"tui-popup",
|
|
||||||
"tui-prompts",
|
|
||||||
"tui-scrollview",
|
|
||||||
"tui-widget-list",
|
|
||||||
"which",
|
|
||||||
"zip",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "memchr"
|
name = "memchr"
|
||||||
version = "2.8.0"
|
version = "2.8.0"
|
||||||
@@ -1972,6 +2185,33 @@ dependencies = [
|
|||||||
"minimal-lexical",
|
"minimal-lexical",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "notify"
|
||||||
|
version = "8.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.11.1",
|
||||||
|
"fsevent-sys",
|
||||||
|
"inotify",
|
||||||
|
"kqueue",
|
||||||
|
"libc",
|
||||||
|
"log",
|
||||||
|
"mio",
|
||||||
|
"notify-types",
|
||||||
|
"walkdir",
|
||||||
|
"windows-sys 0.60.2",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "notify-types"
|
||||||
|
version = "2.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.11.1",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "nu-ansi-term"
|
name = "nu-ansi-term"
|
||||||
version = "0.50.3"
|
version = "0.50.3"
|
||||||
@@ -2008,6 +2248,16 @@ dependencies = [
|
|||||||
"libm",
|
"libm",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num_cpus"
|
||||||
|
version = "1.17.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"
|
||||||
|
dependencies = [
|
||||||
|
"hermit-abi",
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "num_threads"
|
name = "num_threads"
|
||||||
version = "0.1.7"
|
version = "0.1.7"
|
||||||
@@ -2089,9 +2339,9 @@ checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "open"
|
name = "open"
|
||||||
version = "5.3.3"
|
version = "5.3.4"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "43bb73a7fa3799b198970490a51174027ba0d4ec504b03cd08caf513d40024bc"
|
checksum = "9f3bab717c29a857abf75fcef718d441ec7cb2725f937343c734740a985d37fd"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"is-wsl",
|
"is-wsl",
|
||||||
"libc",
|
"libc",
|
||||||
@@ -2199,11 +2449,11 @@ checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pbkdf2"
|
name = "pbkdf2"
|
||||||
version = "0.12.2"
|
version = "0.13.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
|
checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"digest",
|
"digest 0.11.2",
|
||||||
"hmac",
|
"hmac",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -2388,6 +2638,15 @@ dependencies = [
|
|||||||
"syn 2.0.117",
|
"syn 2.0.117",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "proc-macro-crate"
|
||||||
|
version = "3.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
|
||||||
|
dependencies = [
|
||||||
|
"toml_edit",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "proc-macro-error-attr2"
|
name = "proc-macro-error-attr2"
|
||||||
version = "2.0.0"
|
version = "2.0.0"
|
||||||
@@ -2835,6 +3094,12 @@ version = "0.8.10"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
|
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "relative-path"
|
||||||
|
version = "1.9.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "reqwest"
|
name = "reqwest"
|
||||||
version = "0.12.28"
|
version = "0.12.28"
|
||||||
@@ -2890,6 +3155,52 @@ dependencies = [
|
|||||||
"windows-sys 0.52.0",
|
"windows-sys 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rmcl"
|
||||||
|
version = "0.3.1"
|
||||||
|
dependencies = [
|
||||||
|
"async-trait",
|
||||||
|
"chrono",
|
||||||
|
"clap",
|
||||||
|
"color-eyre",
|
||||||
|
"config",
|
||||||
|
"crossterm 0.29.0",
|
||||||
|
"dirs",
|
||||||
|
"dirs-next",
|
||||||
|
"image",
|
||||||
|
"insta",
|
||||||
|
"log",
|
||||||
|
"minecraft-msa-auth",
|
||||||
|
"notify",
|
||||||
|
"oauth2",
|
||||||
|
"open",
|
||||||
|
"ratatui",
|
||||||
|
"ratatui-image",
|
||||||
|
"ratatui-textarea",
|
||||||
|
"ratatui-themekit",
|
||||||
|
"reqwest",
|
||||||
|
"rstest",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"tachyonfx",
|
||||||
|
"tempfile",
|
||||||
|
"thiserror 2.0.18",
|
||||||
|
"throbber-widgets-tui",
|
||||||
|
"tokio",
|
||||||
|
"toml",
|
||||||
|
"tracing",
|
||||||
|
"tracing-appender",
|
||||||
|
"tracing-subscriber",
|
||||||
|
"tui-logger",
|
||||||
|
"tui-popup",
|
||||||
|
"tui-prompts",
|
||||||
|
"tui-scrollview",
|
||||||
|
"tui-widget-list",
|
||||||
|
"which",
|
||||||
|
"wiremock",
|
||||||
|
"zip",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ron"
|
name = "ron"
|
||||||
version = "0.12.1"
|
version = "0.12.1"
|
||||||
@@ -2904,6 +3215,36 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rstest"
|
||||||
|
version = "0.23.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0a2c585be59b6b5dd66a9d2084aa1d8bd52fbdb806eafdeffb52791147862035"
|
||||||
|
dependencies = [
|
||||||
|
"futures",
|
||||||
|
"futures-timer",
|
||||||
|
"rstest_macros",
|
||||||
|
"rustc_version",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rstest_macros"
|
||||||
|
version = "0.23.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "825ea780781b15345a146be27eaefb05085e337e869bff01b4306a4fd4a9ad5a"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"glob",
|
||||||
|
"proc-macro-crate",
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"regex",
|
||||||
|
"relative-path",
|
||||||
|
"rustc_version",
|
||||||
|
"syn 2.0.117",
|
||||||
|
"unicode-ident",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rust-ini"
|
name = "rust-ini"
|
||||||
version = "0.21.3"
|
version = "0.21.3"
|
||||||
@@ -2963,9 +3304,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustls"
|
name = "rustls"
|
||||||
version = "0.23.38"
|
version = "0.23.39"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "69f9466fb2c14ea04357e91413efb882e2a6d4a406e625449bc0a5d360d53a21"
|
checksum = "7c2c118cb077cca2822033836dfb1b975355dfb784b5e8da48f7b6c5db74e60e"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"once_cell",
|
"once_cell",
|
||||||
"ring",
|
"ring",
|
||||||
@@ -2977,9 +3318,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustls-pki-types"
|
name = "rustls-pki-types"
|
||||||
version = "1.14.0"
|
version = "1.14.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"
|
checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"web-time",
|
"web-time",
|
||||||
"zeroize",
|
"zeroize",
|
||||||
@@ -2987,9 +3328,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustls-webpki"
|
name = "rustls-webpki"
|
||||||
version = "0.103.12"
|
version = "0.103.13"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "8279bb85272c9f10811ae6a6c547ff594d6a7f3c6c6b02ee9726d1d0dcfcdd06"
|
checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"ring",
|
"ring",
|
||||||
"rustls-pki-types",
|
"rustls-pki-types",
|
||||||
@@ -3017,6 +3358,15 @@ dependencies = [
|
|||||||
"bytemuck",
|
"bytemuck",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "same-file"
|
||||||
|
version = "1.0.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
|
||||||
|
dependencies = [
|
||||||
|
"winapi-util",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "scopeguard"
|
name = "scopeguard"
|
||||||
version = "1.2.0"
|
version = "1.2.0"
|
||||||
@@ -3118,13 +3468,13 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sha1"
|
name = "sha1"
|
||||||
version = "0.10.6"
|
version = "0.11.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
|
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
"cpufeatures",
|
"cpufeatures 0.3.0",
|
||||||
"digest",
|
"digest 0.11.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -3134,8 +3484,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
"cpufeatures",
|
"cpufeatures 0.2.17",
|
||||||
"digest",
|
"digest 0.10.7",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -3190,6 +3540,12 @@ version = "0.3.9"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"
|
checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "similar"
|
||||||
|
version = "2.7.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "siphasher"
|
name = "siphasher"
|
||||||
version = "1.0.2"
|
version = "1.0.2"
|
||||||
@@ -3621,6 +3977,18 @@ dependencies = [
|
|||||||
"serde_core",
|
"serde_core",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "toml_edit"
|
||||||
|
version = "0.25.11+spec-1.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0b59c4d22ed448339746c59b905d24568fcbb3ab65a500494f7b8c3e97739f2b"
|
||||||
|
dependencies = [
|
||||||
|
"indexmap",
|
||||||
|
"toml_datetime",
|
||||||
|
"toml_parser",
|
||||||
|
"winnow",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "toml_parser"
|
name = "toml_parser"
|
||||||
version = "1.1.2+spec-1.1.0"
|
version = "1.1.2+spec-1.1.0"
|
||||||
@@ -3850,9 +4218,9 @@ checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "typenum"
|
name = "typenum"
|
||||||
version = "1.19.0"
|
version = "1.20.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
|
checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ucd-trie"
|
name = "ucd-trie"
|
||||||
@@ -3972,6 +4340,16 @@ dependencies = [
|
|||||||
"utf8parse",
|
"utf8parse",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "walkdir"
|
||||||
|
version = "2.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
|
||||||
|
dependencies = [
|
||||||
|
"same-file",
|
||||||
|
"winapi-util",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "want"
|
name = "want"
|
||||||
version = "0.3.1"
|
version = "0.3.1"
|
||||||
@@ -4245,6 +4623,15 @@ version = "0.4.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
|
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "winapi-util"
|
||||||
|
version = "0.1.11"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||||
|
dependencies = [
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "winapi-x86_64-pc-windows-gnu"
|
name = "winapi-x86_64-pc-windows-gnu"
|
||||||
version = "0.4.0"
|
version = "0.4.0"
|
||||||
@@ -4541,13 +4928,36 @@ checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "winnow"
|
name = "winnow"
|
||||||
version = "1.0.1"
|
version = "1.0.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "09dac053f1cd375980747450bfc7250c264eaae0583872e845c0c7cd578872b5"
|
checksum = "2ee1708bef14716a11bae175f579062d4554d95be2c6829f518df847b7b3fdd0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"memchr",
|
"memchr",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wiremock"
|
||||||
|
version = "0.6.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "08db1edfb05d9b3c1542e521aea074442088292f00b5f28e435c714a98f85031"
|
||||||
|
dependencies = [
|
||||||
|
"assert-json-diff",
|
||||||
|
"base64",
|
||||||
|
"deadpool",
|
||||||
|
"futures",
|
||||||
|
"http",
|
||||||
|
"http-body-util",
|
||||||
|
"hyper",
|
||||||
|
"hyper-util",
|
||||||
|
"log",
|
||||||
|
"once_cell",
|
||||||
|
"regex",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"tokio",
|
||||||
|
"url",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wit-bindgen"
|
name = "wit-bindgen"
|
||||||
version = "0.51.0"
|
version = "0.51.0"
|
||||||
@@ -4773,9 +5183,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zip"
|
name = "zip"
|
||||||
version = "8.5.1"
|
version = "8.6.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "dcab981e19633ebcf0b001ddd37dd802996098bc1864f90b7c5d970ce76c1d59"
|
checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes",
|
"aes",
|
||||||
"bzip2",
|
"bzip2",
|
||||||
|
|||||||
+29
-2
@@ -1,8 +1,25 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "mcl"
|
name = "rmcl"
|
||||||
version = "0.1.0"
|
version = "0.3.1"
|
||||||
authors = ["objz"]
|
authors = ["objz"]
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
description = "A fully featured Minecraft TUI launcher"
|
||||||
|
repository = "https://github.com/objz/rmcl"
|
||||||
|
homepage = "https://github.com/objz/rmcl"
|
||||||
|
license = "GPL-3.0-only"
|
||||||
|
readme = "README.md"
|
||||||
|
keywords = ["minecraft", "launcher", "tui", "ratatui"]
|
||||||
|
categories = ["command-line-utilities", "games"]
|
||||||
|
|
||||||
|
[package.metadata.wix]
|
||||||
|
upgrade-guid = "BEC08BE4-6A8F-4C1D-A1B4-B1AC963000AE"
|
||||||
|
path-guid = "E5863AC2-13FC-45C8-B79D-55338F371A8A"
|
||||||
|
license = false
|
||||||
|
eula = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "rmcl"
|
||||||
|
path = "src/main.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
async-trait = "0.1"
|
async-trait = "0.1"
|
||||||
@@ -40,6 +57,7 @@ oauth2 = "5.0.0"
|
|||||||
open = "5"
|
open = "5"
|
||||||
which = "8.0.2"
|
which = "8.0.2"
|
||||||
dirs = "6.0.0"
|
dirs = "6.0.0"
|
||||||
|
notify = "8"
|
||||||
|
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
@@ -48,5 +66,14 @@ lto = true
|
|||||||
opt-level = "s"
|
opt-level = "s"
|
||||||
strip = true
|
strip = true
|
||||||
|
|
||||||
|
# The profile that 'dist' will build with
|
||||||
|
[profile.dist]
|
||||||
|
inherits = "release"
|
||||||
|
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"] }
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
# mcl
|
# rmcl
|
||||||
|
|
||||||
[![Contributors][contributors-shield]][contributors-url]
|
[![Contributors][contributors-shield]][contributors-url]
|
||||||
[![Forks][forks-shield]][forks-url]
|
[![Forks][forks-shield]][forks-url]
|
||||||
@@ -8,11 +8,11 @@
|
|||||||
[![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]
|
||||||
|
|
||||||
**MineCraft Launcher. or MineCraft cLi. 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.
|
||||||
|
|
||||||
<!--  -->
|

|
||||||
|
|
||||||
[Report Bug](https://github.com/objz/mcl/issues) · [Request Feature](https://github.com/objz/mcl/issues)
|
[Report Bug](https://github.com/objz/rmcl/issues) · [Request Feature](https://github.com/objz/rmcl/issues)
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -20,7 +20,7 @@
|
|||||||
|
|
||||||
## about
|
## about
|
||||||
|
|
||||||
we all love TUIs. and we all know the official Minecraft launcher is not exactly a joy to use. so here's mcl, 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 because if you're replacing something bloated you might as well go all the way.
|
||||||
|
|
||||||
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. 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.
|
||||||
|
|
||||||
@@ -34,59 +34,115 @@ it does everything you'd expect from a launcher. multiple instances, mod loaders
|
|||||||
| **modpack import** | import from Modrinth via `.mrpack` file, URL, or slug |
|
| **modpack import** | import from Modrinth via `.mrpack` file, URL, or slug |
|
||||||
| **accounts** | multiple Microsoft accounts and offline players, switch between them |
|
| **accounts** | multiple Microsoft accounts and offline players, switch between them |
|
||||||
| **launching** | launch directly from the TUI or generate a desktop shortcut for any instance |
|
| **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 mcl or type anything |
|
| **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 |
|
| **CLI** | every feature the TUI has is also available as a subcommand |
|
||||||
| **theming** | 10 built-in themes, custom themes, color overrides |
|
| **theming** | 10 built-in themes, custom themes, color overrides |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## authentication
|
||||||
|
|
||||||
|
rmcl uses its own Microsoft client ID for Minecraft account authentication.
|
||||||
|
|
||||||
|
Authentication is performed through Microsoft’s official services.
|
||||||
|
|
||||||
## installation
|
## installation
|
||||||
|
|
||||||
|
### macOS / Linux
|
||||||
|
|
||||||
|
prebuilt archives are attached to each GitHub release.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# Homebrew
|
||||||
|
brew install objz/tap/rmcl
|
||||||
|
```
|
||||||
|
|
||||||
|
### Windows
|
||||||
|
|
||||||
|
release builds include a `.zip` archive and an `.msi`. WinGet and Chocolatey
|
||||||
|
packages are submitted from release CI and become available after review.
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# WinGet
|
||||||
|
winget install Objz.Rmcl
|
||||||
|
|
||||||
|
# Chocolatey
|
||||||
|
choco install rmcl
|
||||||
|
```
|
||||||
|
|
||||||
### Arch Linux
|
### Arch Linux
|
||||||
|
|
||||||
[](https://aur.archlinux.org/packages/mcl-launcher)
|
|
||||||
[](https://aur.archlinux.org/packages/mcl-launcher-bin)
|
|
||||||
[](https://aur.archlinux.org/packages/mcl-launcher-git)
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
# from source (release tarball)
|
# from source (release tarball)
|
||||||
paru -S mcl-launcher
|
paru -S rmcl
|
||||||
|
|
||||||
# prebuilt binary
|
# prebuilt binary
|
||||||
paru -S mcl-launcher-bin
|
paru -S rmcl-bin
|
||||||
|
|
||||||
# latest git
|
# latest git
|
||||||
paru -S mcl-launcher-git
|
paru -S rmcl-git
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Cargo
|
||||||
|
|
||||||
|
```sh
|
||||||
|
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 OpenSSL.
|
requires a Rust toolchain and a JDK (`javac` and `jar` on `PATH`).
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
git clone https://github.com/objz/mcl.git
|
git clone https://github.com/objz/rmcl.git
|
||||||
cd mcl
|
cd rmcl
|
||||||
cargo build --release
|
cargo build --release
|
||||||
```
|
```
|
||||||
|
|
||||||
### other platforms
|
|
||||||
|
|
||||||
mcl can be compiled for Linux, macOS, and Windows. right now it's only packaged for Arch Linux (AUR) but official packages for other platforms and package managers will be added continuously.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## where things live
|
## where things live
|
||||||
|
|
||||||
| path | what |
|
### config & data
|
||||||
|---|---|
|
|
||||||
| `~/.config/mcl/config.toml` | general config (paths, memory defaults, UI settings) |
|
settings, accounts, instances, and cached game metadata.
|
||||||
| `~/.config/mcl/theme.toml` | theme, border style, color overrides |
|
|
||||||
| `~/.config/mcl/accounts.json` | accounts |
|
| what | Linux | macOS | Windows |
|
||||||
| `~/.local/share/mcl/instances/` | instances, each in its own directory |
|
|---|---|---|---|
|
||||||
| `~/.local/share/mcl/meta/` | cached game metadata, libraries, assets, loader profiles |
|
| config (`config.toml`, `theme.toml`, `accounts.json`) | `~/.config/rmcl/` | `~/Library/Application Support/rmcl/` | `%APPDATA%\rmcl\` |
|
||||||
|
| instances | `~/.local/share/rmcl/instances/` | `~/Library/Application Support/rmcl/instances/` | `%LOCALAPPDATA%\rmcl\instances\` |
|
||||||
|
| metadata (versions, libraries, assets, loader profiles) | `~/.local/share/rmcl/meta/` | `~/Library/Application Support/rmcl/meta/` | `%LOCALAPPDATA%\rmcl\meta\` |
|
||||||
|
|
||||||
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. standard layout, nothing weird.
|
||||||
|
|
||||||
|
### logs
|
||||||
|
|
||||||
|
launcher logs are per-session and contain rmcl's own output. instance launch logs capture game stdout/stderr per launch.
|
||||||
|
|
||||||
|
| what | Linux | macOS | Windows |
|
||||||
|
|---|---|---|---|
|
||||||
|
| launcher logs | `~/.cache/rmcl/` | `~/Library/Caches/rmcl/` | `%LOCALAPPDATA%\rmcl\` |
|
||||||
|
| instance launch logs | `<instances>/<name>/.minecraft/logs/launches/` | same | same |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## configuration
|
## configuration
|
||||||
@@ -97,17 +153,17 @@ everything is configured through TOML files. `config.toml` for paths, default me
|
|||||||
|
|
||||||
## themes
|
## themes
|
||||||
|
|
||||||
mcl ships with 10 built-in themes:
|
rmcl ships with 10 built-in themes:
|
||||||
|
|
||||||
`catppuccin` · `dracula` · `nord` · `gruvbox` · `one-dark` · `solarized` · `tailwind` · `tokyo-night` · `rose-pine` · `terminal`
|
`catppuccin` · `dracula` · `nord` · `gruvbox` · `one-dark` · `solarized` · `tailwind` · `tokyo-night` · `rose-pine` · `terminal`
|
||||||
|
|
||||||
you can create your own by dropping a TOML file in `~/.config/mcl/theme/` and referencing it by name, or point to an absolute path.
|
you can create your own by dropping a TOML file in `~/.config/rmcl/theme/` and referencing it by name, or point to an absolute path.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## contributing
|
## contributing
|
||||||
|
|
||||||
contributions are welcome. fork it, branch it, PR it. make sure `cargo clippy` and `cargo test` pass before opening a PR.
|
contributions are welcome. fork it, branch it, PR it. see [CONTRIBUTING.md](CONTRIBUTING.md) for code style and project structure.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -117,13 +173,13 @@ GPL-3.0. see [LICENSE](LICENSE).
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
[contributors-shield]: https://img.shields.io/github/contributors/objz/mcl.svg?style=for-the-badge
|
[contributors-shield]: https://img.shields.io/github/contributors/objz/rmcl.svg?style=for-the-badge
|
||||||
[contributors-url]: https://github.com/objz/mcl/graphs/contributors
|
[contributors-url]: https://github.com/objz/rmcl/graphs/contributors
|
||||||
[forks-shield]: https://img.shields.io/github/forks/objz/mcl.svg?style=for-the-badge
|
[forks-shield]: https://img.shields.io/github/forks/objz/rmcl.svg?style=for-the-badge
|
||||||
[forks-url]: https://github.com/objz/mcl/network/members
|
[forks-url]: https://github.com/objz/rmcl/network/members
|
||||||
[stars-shield]: https://img.shields.io/github/stars/objz/mcl.svg?style=for-the-badge
|
[stars-shield]: https://img.shields.io/github/stars/objz/rmcl.svg?style=for-the-badge
|
||||||
[stars-url]: https://github.com/objz/mcl/stargazers
|
[stars-url]: https://github.com/objz/rmcl/stargazers
|
||||||
[issues-shield]: https://img.shields.io/github/issues/objz/mcl.svg?style=for-the-badge
|
[issues-shield]: https://img.shields.io/github/issues/objz/rmcl.svg?style=for-the-badge
|
||||||
[issues-url]: https://github.com/objz/mcl/issues
|
[issues-url]: https://github.com/objz/rmcl/issues
|
||||||
[license-shield]: https://img.shields.io/github/license/objz/mcl.svg?style=for-the-badge
|
[license-shield]: https://img.shields.io/github/license/objz/rmcl.svg?style=for-the-badge
|
||||||
[license-url]: https://github.com/objz/mcl/blob/master/LICENSE
|
[license-url]: https://github.com/objz/rmcl/blob/master/LICENSE
|
||||||
+2
-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 = ""
|
||||||
|
|||||||
+1
-1
@@ -5,7 +5,7 @@
|
|||||||
# custom themes:
|
# custom themes:
|
||||||
# theme = "my-theme" (loads ~/.config/mcl/theme/my-theme.toml)
|
# theme = "my-theme" (loads ~/.config/mcl/theme/my-theme.toml)
|
||||||
# theme = "/path/to/file" (loads from absolute path)
|
# theme = "/path/to/file" (loads from absolute path)
|
||||||
theme = "terminal"
|
theme = "gruvbox"
|
||||||
|
|
||||||
# rounded, plain, double, thick
|
# rounded, plain, double, thick
|
||||||
border_style = "rounded"
|
border_style = "rounded"
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
use std::env;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
println!("cargo:rerun-if-changed=java/RmclShim.java");
|
||||||
|
|
||||||
|
let out_dir = env::var("OUT_DIR").unwrap();
|
||||||
|
let out = Path::new(&out_dir);
|
||||||
|
|
||||||
|
// compile RmclShim.java into a jar that gets embedded via include_bytes!
|
||||||
|
let status = Command::new("javac")
|
||||||
|
.arg("-source")
|
||||||
|
.arg("8")
|
||||||
|
.arg("-target")
|
||||||
|
.arg("8")
|
||||||
|
.arg("-d")
|
||||||
|
.arg(out.to_str().unwrap())
|
||||||
|
.arg("java/RmclShim.java")
|
||||||
|
.status()
|
||||||
|
.expect("Failed to run javac - is a JDK installed?");
|
||||||
|
|
||||||
|
assert!(status.success(), "javac failed to compile RmclShim.java");
|
||||||
|
|
||||||
|
// package into a jar
|
||||||
|
let jar_path = out.join("rmcl-shim.jar");
|
||||||
|
let status = Command::new("jar")
|
||||||
|
.arg("cfe")
|
||||||
|
.arg(jar_path.to_str().unwrap())
|
||||||
|
.arg("RmclShim")
|
||||||
|
.arg("-C")
|
||||||
|
.arg(out.to_str().unwrap())
|
||||||
|
.arg("RmclShim.class")
|
||||||
|
.status()
|
||||||
|
.expect("Failed to run jar - is a JDK installed?");
|
||||||
|
|
||||||
|
assert!(status.success(), "jar failed to create rmcl-shim.jar");
|
||||||
|
}
|
||||||
+103
@@ -0,0 +1,103 @@
|
|||||||
|
# git-cliff ~ configuration file
|
||||||
|
# https://git-cliff.org/docs/configuration
|
||||||
|
|
||||||
|
|
||||||
|
[remote.github]
|
||||||
|
owner = "objz"
|
||||||
|
repo = "rmcl"
|
||||||
|
|
||||||
|
[changelog]
|
||||||
|
# A Tera template to be rendered for each release in the changelog.
|
||||||
|
# See https://keats.github.io/tera/docs/#introduction
|
||||||
|
body = """
|
||||||
|
{% if version %}\
|
||||||
|
## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }}
|
||||||
|
{% else %}\
|
||||||
|
## [unreleased]
|
||||||
|
{% endif %}\
|
||||||
|
{% for group, commits in commits | group_by(attribute="group") %}
|
||||||
|
### {{ group | striptags | trim | upper_first }}
|
||||||
|
{% for commit in commits %}
|
||||||
|
- {% if commit.scope %}*({{ commit.scope }})* {% endif %}\
|
||||||
|
{% if commit.breaking %}[**breaking**] {% endif %}\
|
||||||
|
{{ commit.message | upper_first }}\
|
||||||
|
{% if commit.github.pr_number %} ([#{{ commit.github.pr_number }}](https://github.com/objz/rmcl/pull/{{ commit.github.pr_number }})){% endif %}\
|
||||||
|
{% endfor %}
|
||||||
|
{% endfor %}
|
||||||
|
{% if github.contributors | filter(attribute="is_first_time", value=true) | length != 0 %}
|
||||||
|
### New Contributors
|
||||||
|
{% for contributor in github.contributors | filter(attribute="is_first_time", value=true) %}
|
||||||
|
- @{{ contributor.username }} made their first contribution\
|
||||||
|
{% if contributor.pr_number %} in [#{{ contributor.pr_number }}](https://github.com/objz/rmcl/pull/{{ contributor.pr_number }}){% endif %}\
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
|
"""
|
||||||
|
# Remove leading and trailing whitespaces from the changelog's body.
|
||||||
|
trim = true
|
||||||
|
# Render body even when there are no releases to process.
|
||||||
|
render_always = true
|
||||||
|
# An array of regex based postprocessors to modify the changelog.
|
||||||
|
postprocessors = [
|
||||||
|
# Replace the placeholder <REPO> with a URL.
|
||||||
|
#{ pattern = '<REPO>', replace = "https://github.com/orhun/git-cliff" },
|
||||||
|
]
|
||||||
|
# render body even when there are no releases to process
|
||||||
|
# render_always = true
|
||||||
|
# output file path
|
||||||
|
# output = "test.md"
|
||||||
|
|
||||||
|
[git]
|
||||||
|
# Parse commits according to the conventional commits specification.
|
||||||
|
# See https://www.conventionalcommits.org
|
||||||
|
conventional_commits = true
|
||||||
|
# Exclude commits that do not match the conventional commits specification.
|
||||||
|
filter_unconventional = false
|
||||||
|
# Require all commits to be conventional.
|
||||||
|
# Takes precedence over filter_unconventional.
|
||||||
|
require_conventional = false
|
||||||
|
# Split commits on newlines, treating each line as an individual commit.
|
||||||
|
split_commits = false
|
||||||
|
# An array of regex based parsers to modify commit messages prior to further processing.
|
||||||
|
commit_preprocessors = [
|
||||||
|
# Replace issue numbers in commit messages with links.
|
||||||
|
{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](https://github.com/objz/rmcl/issues/${2}))" },
|
||||||
|
]
|
||||||
|
# Prevent commits that are breaking from being excluded by commit parsers.
|
||||||
|
protect_breaking_commits = false
|
||||||
|
# An array of regex based parsers for extracting data from the commit message.
|
||||||
|
# Assigns commits to groups.
|
||||||
|
# Optionally sets the commit's scope and can decide to exclude commits from further processing.
|
||||||
|
commit_parsers = [
|
||||||
|
{ message = "^feat", group = "<!-- 0 -->Features" },
|
||||||
|
{ message = "^fix", group = "<!-- 1 -->Bug Fixes" },
|
||||||
|
{ message = "^doc", group = "<!-- 3 -->Documentation" },
|
||||||
|
{ message = "^perf", group = "<!-- 4 -->Performance" },
|
||||||
|
{ message = "^refactor", group = "<!-- 2 -->Refactor" },
|
||||||
|
{ message = "^style", group = "<!-- 5 -->Styling" },
|
||||||
|
{ message = "^test", group = "<!-- 6 -->Testing" },
|
||||||
|
{ message = "^chore\\(release\\): prepare for", skip = true },
|
||||||
|
{ message = "^chore\\(deps.*\\)", skip = true },
|
||||||
|
{ message = "^chore\\(pr\\)", skip = true },
|
||||||
|
{ message = "^chore\\(pull\\)", skip = true },
|
||||||
|
{ message = "^chore|^ci", group = "<!-- 7 -->Miscellaneous Tasks" },
|
||||||
|
{ body = ".*security", group = "<!-- 8 -->Security" },
|
||||||
|
{ message = "^revert", group = "<!-- 9 -->Revert" },
|
||||||
|
{ message = ".*", group = "<!-- 10 -->Other" },
|
||||||
|
]
|
||||||
|
# Exclude commits that are not matched by any commit parser.
|
||||||
|
filter_commits = false
|
||||||
|
# Fail on a commit that is not matched by any commit parser.
|
||||||
|
fail_on_unmatched_commit = false
|
||||||
|
# An array of link parsers for extracting external references, and turning them into URLs, using regex.
|
||||||
|
link_parsers = []
|
||||||
|
# Include only the tags that belong to the current branch.
|
||||||
|
use_branch_tags = false
|
||||||
|
# Order releases topologically instead of chronologically.
|
||||||
|
topo_order = false
|
||||||
|
# Order commits topologically instead of chronologically.
|
||||||
|
topo_order_commits = true
|
||||||
|
# Order of commits in each group/release within the changelog.
|
||||||
|
# Allowed values: newest, oldest
|
||||||
|
sort_commits = "oldest"
|
||||||
|
# Process submodules commits
|
||||||
|
recurse_submodules = false
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
[workspace]
|
||||||
|
members = ["cargo:."]
|
||||||
|
|
||||||
|
# Config for 'dist'
|
||||||
|
[dist]
|
||||||
|
# The preferred dist version to use in CI (Cargo.toml SemVer syntax)
|
||||||
|
cargo-dist-version = "0.31.0"
|
||||||
|
# CI backends to support
|
||||||
|
ci = "github"
|
||||||
|
# The installers to generate for each app
|
||||||
|
installers = ["homebrew", "msi"]
|
||||||
|
# A GitHub repo to push Homebrew formulas to
|
||||||
|
tap = "objz/homebrew-tap"
|
||||||
|
# Target platforms to build apps for (Rust target-triple syntax)
|
||||||
|
targets = ["aarch64-apple-darwin", "aarch64-unknown-linux-gnu", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu", "x86_64-pc-windows-msvc"]
|
||||||
|
# Path that installers should place binaries in
|
||||||
|
install-path = "CARGO_HOME"
|
||||||
|
# Publish jobs to run in CI
|
||||||
|
publish-jobs = ["homebrew", "./publish-crates", "./publish-aur", "./publish-winget", "./publish-chocolatey"]
|
||||||
|
# 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" } }
|
||||||
|
# Extra setup steps for release artifact builders
|
||||||
|
github-build-setup = "../dist-build-setup.yml"
|
||||||
|
# Where to host releases
|
||||||
|
hosting = "github"
|
||||||
|
# Whether to install an updater program
|
||||||
|
install-updater = false
|
||||||
|
# Allow custom edits to the generated CI file
|
||||||
|
allow-dirty = ["ci"]
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import java.lang.reflect.Method;
|
||||||
|
|
||||||
|
public class RmclShim {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
if (args.length == 0) {
|
||||||
|
System.err.println("Usage: RmclShim <mainClass> [args...]");
|
||||||
|
System.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
String mainClass = args[0];
|
||||||
|
String[] remaining = new String[args.length - 1];
|
||||||
|
System.arraycopy(args, 1, remaining, 0, remaining.length);
|
||||||
|
|
||||||
|
ClassLoader loader = ClassLoader.getSystemClassLoader();
|
||||||
|
Class<?> clazz = loader.loadClass(mainClass);
|
||||||
|
Method main = clazz.getMethod("main", String[].class);
|
||||||
|
main.invoke(null, (Object) remaining);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<?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>
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
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__
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
$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
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
# Maintainer: objz <me@objz.dev>
|
|
||||||
pkgname=mcl-launcher-bin
|
|
||||||
pkgver=0.1.0
|
|
||||||
pkgrel=1
|
|
||||||
pkgdesc="Minecraft launcher TUI"
|
|
||||||
arch=('x86_64' 'aarch64')
|
|
||||||
url="https://github.com/objz/mcl"
|
|
||||||
license=('GPL-3.0-only')
|
|
||||||
depends=('openssl')
|
|
||||||
provides=('mcl-launcher')
|
|
||||||
conflicts=('mcl-launcher' 'mcl-launcher-git')
|
|
||||||
source=("LICENSE-${pkgver}::${url}/raw/v${pkgver}/LICENSE")
|
|
||||||
source_x86_64=("${url}/releases/download/v${pkgver}/mcl-x86_64-unknown-linux-gnu.tar.gz")
|
|
||||||
source_aarch64=("${url}/releases/download/v${pkgver}/mcl-aarch64-unknown-linux-gnu.tar.gz")
|
|
||||||
sha256sums=('SKIP')
|
|
||||||
sha256sums_x86_64=('SKIP')
|
|
||||||
sha256sums_aarch64=('SKIP')
|
|
||||||
|
|
||||||
package() {
|
|
||||||
install -Dm755 mcl "$pkgdir/usr/bin/mcl"
|
|
||||||
install -Dm644 "LICENSE-${pkgver}" "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
# Maintainer: objz <me@objz.dev>
|
|
||||||
pkgname=mcl-launcher-git
|
|
||||||
pkgver=r116.ab9d9dd
|
|
||||||
pkgrel=1
|
|
||||||
pkgdesc="Minecraft launcher TUI"
|
|
||||||
arch=('x86_64' 'aarch64')
|
|
||||||
url="https://github.com/objz/mcl"
|
|
||||||
license=('GPL-3.0-only')
|
|
||||||
depends=('openssl')
|
|
||||||
makedepends=('git' 'rust' 'cargo' 'openssl' 'pkgconf')
|
|
||||||
provides=('mcl-launcher')
|
|
||||||
conflicts=('mcl-launcher' 'mcl-launcher-bin')
|
|
||||||
source=("git+$url.git")
|
|
||||||
sha256sums=('SKIP')
|
|
||||||
|
|
||||||
pkgver() {
|
|
||||||
cd "$srcdir/mcl"
|
|
||||||
printf "r%s.%s" "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)"
|
|
||||||
}
|
|
||||||
|
|
||||||
build() {
|
|
||||||
cd "$srcdir/mcl"
|
|
||||||
cargo build --release --locked
|
|
||||||
}
|
|
||||||
|
|
||||||
check() {
|
|
||||||
cd "$srcdir/mcl"
|
|
||||||
cargo test --release --locked
|
|
||||||
}
|
|
||||||
|
|
||||||
package() {
|
|
||||||
cd "$srcdir/mcl"
|
|
||||||
install -Dm755 "target/release/mcl" "$pkgdir/usr/bin/mcl"
|
|
||||||
install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
# Maintainer: objz <me@objz.dev>
|
|
||||||
pkgname=mcl-launcher
|
|
||||||
pkgver=0.1.0
|
|
||||||
pkgrel=1
|
|
||||||
pkgdesc="Minecraft launcher TUI"
|
|
||||||
arch=('x86_64' 'aarch64')
|
|
||||||
url="https://github.com/objz/mcl"
|
|
||||||
license=('GPL-3.0-only')
|
|
||||||
depends=('openssl')
|
|
||||||
makedepends=('rust' 'cargo' 'openssl' 'pkgconf')
|
|
||||||
provides=('mcl-launcher')
|
|
||||||
conflicts=('mcl-launcher-bin' 'mcl-launcher-git')
|
|
||||||
source=("${url}/archive/v${pkgver}.tar.gz")
|
|
||||||
sha256sums=('SKIP')
|
|
||||||
|
|
||||||
build() {
|
|
||||||
cd "$srcdir/mcl-${pkgver}"
|
|
||||||
cargo build --release --locked
|
|
||||||
}
|
|
||||||
|
|
||||||
check() {
|
|
||||||
cd "$srcdir/mcl-${pkgver}"
|
|
||||||
cargo test --release --locked
|
|
||||||
}
|
|
||||||
|
|
||||||
package() {
|
|
||||||
cd "$srcdir/mcl-${pkgver}"
|
|
||||||
install -Dm755 "target/release/mcl" "$pkgdir/usr/bin/mcl"
|
|
||||||
install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Maintainer: objz <me@objz.dev>
|
||||||
|
pkgname=rmcl-bin
|
||||||
|
pkgver=0.3.0
|
||||||
|
pkgrel=1
|
||||||
|
pkgdesc="Minecraft launcher TUI"
|
||||||
|
arch=('x86_64' 'aarch64')
|
||||||
|
url="https://github.com/objz/rmcl"
|
||||||
|
license=('GPL-3.0-only')
|
||||||
|
depends=()
|
||||||
|
provides=('rmcl')
|
||||||
|
conflicts=('rmcl' 'rmcl-git' 'mcl-launcher' 'mcl-launcher-bin' 'mcl-launcher-git')
|
||||||
|
replaces=('mcl-launcher' 'mcl-launcher-bin' 'mcl-launcher-git')
|
||||||
|
source=("LICENSE-${pkgver}::${url}/raw/v${pkgver}/LICENSE" "README-${pkgver}::${url}/raw/v${pkgver}/README.md")
|
||||||
|
source_x86_64=("rmcl-${pkgver}-x86_64-unknown-linux-gnu.tar.xz::${url}/releases/download/v${pkgver}/rmcl-x86_64-unknown-linux-gnu.tar.xz")
|
||||||
|
source_aarch64=("rmcl-${pkgver}-aarch64-unknown-linux-gnu.tar.xz::${url}/releases/download/v${pkgver}/rmcl-aarch64-unknown-linux-gnu.tar.xz")
|
||||||
|
sha256sums=('SKIP' 'SKIP')
|
||||||
|
sha256sums_x86_64=('SKIP')
|
||||||
|
sha256sums_aarch64=('SKIP')
|
||||||
|
|
||||||
|
package() {
|
||||||
|
local _dir="rmcl-${CARCH}-unknown-linux-gnu"
|
||||||
|
install -Dm755 "$_dir/rmcl" "$pkgdir/usr/bin/rmcl"
|
||||||
|
install -Dm644 "LICENSE-${pkgver}" "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
||||||
|
install -Dm644 "README-${pkgver}" "$pkgdir/usr/share/doc/$pkgname/README.md"
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# Maintainer: objz <me@objz.dev>
|
||||||
|
pkgname=rmcl-git
|
||||||
|
pkgver=r116.ab9d9dd
|
||||||
|
pkgrel=1
|
||||||
|
pkgdesc="Minecraft launcher TUI"
|
||||||
|
arch=('x86_64' 'aarch64')
|
||||||
|
url="https://github.com/objz/rmcl"
|
||||||
|
license=('GPL-3.0-only')
|
||||||
|
depends=()
|
||||||
|
makedepends=('git' 'rust' 'cargo' 'jdk-openjdk')
|
||||||
|
provides=('rmcl')
|
||||||
|
conflicts=('rmcl' 'rmcl-bin' 'mcl-launcher' 'mcl-launcher-bin' 'mcl-launcher-git')
|
||||||
|
replaces=('mcl-launcher' 'mcl-launcher-bin' 'mcl-launcher-git')
|
||||||
|
source=("git+$url.git")
|
||||||
|
sha256sums=('SKIP')
|
||||||
|
|
||||||
|
pkgver() {
|
||||||
|
cd "$srcdir/rmcl"
|
||||||
|
printf "r%s.%s" "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)"
|
||||||
|
}
|
||||||
|
|
||||||
|
build() {
|
||||||
|
cd "$srcdir/rmcl"
|
||||||
|
cargo build --release --locked
|
||||||
|
}
|
||||||
|
|
||||||
|
check() {
|
||||||
|
cd "$srcdir/rmcl"
|
||||||
|
cargo test --release --locked
|
||||||
|
}
|
||||||
|
|
||||||
|
package() {
|
||||||
|
cd "$srcdir/rmcl"
|
||||||
|
install -Dm755 "target/release/rmcl" "$pkgdir/usr/bin/rmcl"
|
||||||
|
install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
||||||
|
install -Dm644 README.md "$pkgdir/usr/share/doc/$pkgname/README.md"
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# Maintainer: objz <me@objz.dev>
|
||||||
|
pkgname=rmcl
|
||||||
|
pkgver=0.3.0
|
||||||
|
pkgrel=1
|
||||||
|
pkgdesc="Minecraft launcher TUI"
|
||||||
|
arch=('x86_64' 'aarch64')
|
||||||
|
url="https://github.com/objz/rmcl"
|
||||||
|
license=('GPL-3.0-only')
|
||||||
|
depends=()
|
||||||
|
makedepends=('rust' 'cargo' 'jdk-openjdk')
|
||||||
|
provides=('rmcl')
|
||||||
|
conflicts=('rmcl-bin' 'rmcl-git' 'mcl-launcher' 'mcl-launcher-bin' 'mcl-launcher-git')
|
||||||
|
replaces=('mcl-launcher' 'mcl-launcher-bin' 'mcl-launcher-git')
|
||||||
|
source=("${url}/archive/v${pkgver}.tar.gz")
|
||||||
|
sha256sums=('SKIP')
|
||||||
|
|
||||||
|
build() {
|
||||||
|
cd "$srcdir/rmcl-${pkgver}"
|
||||||
|
cargo build --release --locked
|
||||||
|
}
|
||||||
|
|
||||||
|
check() {
|
||||||
|
cd "$srcdir/rmcl-${pkgver}"
|
||||||
|
cargo test --release --locked
|
||||||
|
}
|
||||||
|
|
||||||
|
package() {
|
||||||
|
cd "$srcdir/rmcl-${pkgver}"
|
||||||
|
install -Dm755 "target/release/rmcl" "$pkgdir/usr/bin/rmcl"
|
||||||
|
install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
||||||
|
install -Dm644 README.md "$pkgdir/usr/share/doc/$pkgname/README.md"
|
||||||
|
}
|
||||||
+47
-19
@@ -12,6 +12,10 @@ pub struct Account {
|
|||||||
pub active: bool,
|
pub active: bool,
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
pub refresh_token: Option<String>,
|
pub refresh_token: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub cached_mc_token: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub cached_mc_token_expires_at: Option<i64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||||
@@ -62,6 +66,12 @@ impl AccountStore {
|
|||||||
self.accounts.iter().find(|a| a.active)
|
self.accounts.iter().find(|a| a.active)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn has_microsoft_account(&self) -> bool {
|
||||||
|
self.accounts
|
||||||
|
.iter()
|
||||||
|
.any(|account| account.account_type == AccountType::Microsoft)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn set_active(&mut self, index: usize) {
|
pub fn set_active(&mut self, index: usize) {
|
||||||
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;
|
||||||
@@ -123,6 +133,8 @@ pub fn create_offline_account(username: &str) -> Account {
|
|||||||
account_type: AccountType::Offline,
|
account_type: AccountType::Offline,
|
||||||
active: false,
|
active: false,
|
||||||
refresh_token: None,
|
refresh_token: None,
|
||||||
|
cached_mc_token: None,
|
||||||
|
cached_mc_token_expires_at: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -174,7 +186,10 @@ mod tests {
|
|||||||
assert_eq!(acc.account_type, AccountType::Offline);
|
assert_eq!(acc.account_type, AccountType::Offline);
|
||||||
assert!(!acc.active);
|
assert!(!acc.active);
|
||||||
assert!(acc.refresh_token.is_none());
|
assert!(acc.refresh_token.is_none());
|
||||||
assert!(!acc.uuid.is_empty());
|
// 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 {
|
fn make_store(dir: &std::path::Path) -> AccountStore {
|
||||||
@@ -184,13 +199,15 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn dummy_account(name: &str) -> Account {
|
fn microsoft_account(name: &str) -> Account {
|
||||||
Account {
|
Account {
|
||||||
uuid: offline_uuid(name),
|
uuid: format!("00000000-0000-0000-0000-{:012}", name.len()),
|
||||||
username: name.to_owned(),
|
username: name.to_owned(),
|
||||||
account_type: AccountType::Offline,
|
account_type: AccountType::Microsoft,
|
||||||
active: false,
|
active: false,
|
||||||
refresh_token: None,
|
refresh_token: Some("refresh".to_owned()),
|
||||||
|
cached_mc_token: None,
|
||||||
|
cached_mc_token_expires_at: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -198,7 +215,7 @@ mod tests {
|
|||||||
fn store_add_first_becomes_active() {
|
fn store_add_first_becomes_active() {
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
let mut store = make_store(tmp.path());
|
let mut store = make_store(tmp.path());
|
||||||
store.add(dummy_account("Alice"));
|
store.add(create_offline_account("Alice"));
|
||||||
assert_eq!(store.accounts.len(), 1);
|
assert_eq!(store.accounts.len(), 1);
|
||||||
assert!(store.accounts[0].active);
|
assert!(store.accounts[0].active);
|
||||||
}
|
}
|
||||||
@@ -207,8 +224,8 @@ mod tests {
|
|||||||
fn store_add_second_stays_inactive() {
|
fn store_add_second_stays_inactive() {
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
let mut store = make_store(tmp.path());
|
let mut store = make_store(tmp.path());
|
||||||
store.add(dummy_account("Alice"));
|
store.add(create_offline_account("Alice"));
|
||||||
store.add(dummy_account("Bob"));
|
store.add(create_offline_account("Bob"));
|
||||||
assert_eq!(store.accounts.len(), 2);
|
assert_eq!(store.accounts.len(), 2);
|
||||||
assert!(store.accounts[0].active);
|
assert!(store.accounts[0].active);
|
||||||
assert!(!store.accounts[1].active);
|
assert!(!store.accounts[1].active);
|
||||||
@@ -218,8 +235,8 @@ mod tests {
|
|||||||
fn store_add_duplicate_uuid_replaces() {
|
fn store_add_duplicate_uuid_replaces() {
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
let mut store = make_store(tmp.path());
|
let mut store = make_store(tmp.path());
|
||||||
store.add(dummy_account("Alice"));
|
store.add(create_offline_account("Alice"));
|
||||||
let mut dup = dummy_account("Alice");
|
let mut dup = create_offline_account("Alice");
|
||||||
dup.username = "AliceRenamed".to_owned();
|
dup.username = "AliceRenamed".to_owned();
|
||||||
dup.uuid = store.accounts[0].uuid.clone();
|
dup.uuid = store.accounts[0].uuid.clone();
|
||||||
store.add(dup);
|
store.add(dup);
|
||||||
@@ -234,12 +251,23 @@ mod tests {
|
|||||||
assert!(store.active_account().is_none());
|
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]
|
#[test]
|
||||||
fn store_active_account_returns_active() {
|
fn store_active_account_returns_active() {
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
let mut store = make_store(tmp.path());
|
let mut store = make_store(tmp.path());
|
||||||
store.add(dummy_account("Alice"));
|
store.add(create_offline_account("Alice"));
|
||||||
store.add(dummy_account("Bob"));
|
store.add(create_offline_account("Bob"));
|
||||||
let active = store.active_account().unwrap();
|
let active = store.active_account().unwrap();
|
||||||
assert_eq!(active.username, "Alice");
|
assert_eq!(active.username, "Alice");
|
||||||
}
|
}
|
||||||
@@ -248,8 +276,8 @@ mod tests {
|
|||||||
fn store_set_active_changes_active() {
|
fn store_set_active_changes_active() {
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
let mut store = make_store(tmp.path());
|
let mut store = make_store(tmp.path());
|
||||||
store.add(dummy_account("Alice"));
|
store.add(create_offline_account("Alice"));
|
||||||
store.add(dummy_account("Bob"));
|
store.add(create_offline_account("Bob"));
|
||||||
store.set_active(1);
|
store.set_active(1);
|
||||||
assert!(!store.accounts[0].active);
|
assert!(!store.accounts[0].active);
|
||||||
assert!(store.accounts[1].active);
|
assert!(store.accounts[1].active);
|
||||||
@@ -259,8 +287,8 @@ mod tests {
|
|||||||
fn store_remove_activates_first_remaining() {
|
fn store_remove_activates_first_remaining() {
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
let mut store = make_store(tmp.path());
|
let mut store = make_store(tmp.path());
|
||||||
store.add(dummy_account("Alice"));
|
store.add(create_offline_account("Alice"));
|
||||||
store.add(dummy_account("Bob"));
|
store.add(create_offline_account("Bob"));
|
||||||
store.remove(0);
|
store.remove(0);
|
||||||
assert_eq!(store.accounts.len(), 1);
|
assert_eq!(store.accounts.len(), 1);
|
||||||
assert_eq!(store.accounts[0].username, "Bob");
|
assert_eq!(store.accounts[0].username, "Bob");
|
||||||
@@ -271,7 +299,7 @@ mod tests {
|
|||||||
fn store_remove_out_of_bounds_noop() {
|
fn store_remove_out_of_bounds_noop() {
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
let mut store = make_store(tmp.path());
|
let mut store = make_store(tmp.path());
|
||||||
store.add(dummy_account("Alice"));
|
store.add(create_offline_account("Alice"));
|
||||||
store.remove(5);
|
store.remove(5);
|
||||||
assert_eq!(store.accounts.len(), 1);
|
assert_eq!(store.accounts.len(), 1);
|
||||||
}
|
}
|
||||||
@@ -280,8 +308,8 @@ mod tests {
|
|||||||
fn store_save_and_reload() {
|
fn store_save_and_reload() {
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
let mut store = make_store(tmp.path());
|
let mut store = make_store(tmp.path());
|
||||||
store.add(dummy_account("Alice"));
|
store.add(create_offline_account("Alice"));
|
||||||
store.add(dummy_account("Bob"));
|
store.add(create_offline_account("Bob"));
|
||||||
store.save();
|
store.save();
|
||||||
|
|
||||||
let reloaded = AccountStore {
|
let reloaded = AccountStore {
|
||||||
|
|||||||
+3
-3
@@ -3,7 +3,7 @@ mod accounts;
|
|||||||
mod oauth;
|
mod oauth;
|
||||||
|
|
||||||
pub use accounts::{
|
pub use accounts::{
|
||||||
account_store_path, create_offline_account, offline_uuid, Account, AccountStore, AccountType,
|
Account, AccountStore, AccountType, AuthResult, account_store_path, create_offline_account,
|
||||||
AuthResult,
|
offline_uuid,
|
||||||
};
|
};
|
||||||
pub use oauth::{refresh_and_get_token, start_microsoft_auth, DeviceCodeInfo, DEVICE_CODE_DISPLAY};
|
pub use oauth::{DEVICE_CODE_DISPLAY, DeviceCodeInfo, refresh_and_get_token, start_microsoft_auth};
|
||||||
+84
-7
@@ -14,11 +14,13 @@ use serde::Deserialize;
|
|||||||
|
|
||||||
use super::accounts::{Account, AccountType, AuthResult};
|
use super::accounts::{Account, AccountType, AuthResult};
|
||||||
|
|
||||||
const CLIENT_ID: &str = "708e91b5-99f8-4a1d-80ec-e746cbb24771";
|
const CLIENT_ID: &str = "cc1b2d89-8d8b-439f-94e6-4a7fc484f672";
|
||||||
const DEVICE_CODE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode";
|
const DEVICE_CODE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode";
|
||||||
const MSA_AUTHORIZE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize";
|
const MSA_AUTHORIZE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize";
|
||||||
const MSA_TOKEN_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token";
|
const MSA_TOKEN_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token";
|
||||||
const MC_PROFILE_URL: &str = "https://api.minecraftservices.com/minecraft/profile";
|
const MC_PROFILE_URL: &str = "https://api.minecraftservices.com/minecraft/profile";
|
||||||
|
const MC_TOKEN_CACHE_TTL_SECS: i64 = 20 * 60 * 60;
|
||||||
|
const MC_TOKEN_CACHE_REFRESH_MARGIN_SECS: i64 = 5 * 60;
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
pub struct DeviceCodeInfo {
|
pub struct DeviceCodeInfo {
|
||||||
@@ -131,7 +133,7 @@ async fn exchange_and_build_account(
|
|||||||
Err(e) => return AuthResult::Error(format!("Profile parse failed: {e}")),
|
Err(e) => return AuthResult::Error(format!("Profile parse failed: {e}")),
|
||||||
};
|
};
|
||||||
|
|
||||||
// mojang returns uuids without dashes because of course they do
|
// mojang returns uuids without dashes
|
||||||
let uuid = if profile.id.len() == 32 {
|
let uuid = if profile.id.len() == 32 {
|
||||||
format!(
|
format!(
|
||||||
"{}-{}-{}-{}-{}",
|
"{}-{}-{}-{}-{}",
|
||||||
@@ -151,15 +153,42 @@ async fn exchange_and_build_account(
|
|||||||
account_type: AccountType::Microsoft,
|
account_type: AccountType::Microsoft,
|
||||||
active: false,
|
active: false,
|
||||||
refresh_token: ms_refresh_token.map(|s| s.to_owned()),
|
refresh_token: ms_refresh_token.map(|s| s.to_owned()),
|
||||||
|
cached_mc_token: None,
|
||||||
|
cached_mc_token_expires_at: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// returns (mc_access_token, new_refresh_token). for offline accounts it just
|
fn valid_cached_mc_token(account: &Account, now: i64) -> Option<&str> {
|
||||||
// hands back a dummy token since the server doesn't care.
|
let (Some(cached), Some(expires_at)) = (
|
||||||
pub async fn refresh_and_get_token(account: &Account) -> Result<(String, Option<String>), String> {
|
account.cached_mc_token.as_deref(),
|
||||||
|
account.cached_mc_token_expires_at,
|
||||||
|
) else {
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
|
||||||
|
if now < expires_at - MC_TOKEN_CACHE_REFRESH_MARGIN_SECS {
|
||||||
|
Some(cached)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// returns (mc_access_token, new_refresh_token, new_mc_token_expires_at).
|
||||||
|
// cached tokens return no expiry so callers don't rewrite the account store.
|
||||||
|
pub async fn refresh_and_get_token(
|
||||||
|
account: &Account,
|
||||||
|
) -> Result<(String, Option<String>, Option<i64>), String> {
|
||||||
match account.account_type {
|
match account.account_type {
|
||||||
AccountType::Offline => Ok(("0".to_owned(), None)),
|
AccountType::Offline => Ok(("0".to_owned(), None, None)),
|
||||||
AccountType::Microsoft => {
|
AccountType::Microsoft => {
|
||||||
|
let now = chrono::Utc::now().timestamp();
|
||||||
|
if let Some(cached) = valid_cached_mc_token(account, now) {
|
||||||
|
tracing::info!("Using cached Minecraft token for '{}'", account.username);
|
||||||
|
return Ok((cached.to_owned(), None, None));
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::info!("Refreshing Minecraft token for '{}'", account.username);
|
||||||
|
|
||||||
let refresh = account.refresh_token.as_deref().ok_or_else(|| {
|
let refresh = account.refresh_token.as_deref().ok_or_else(|| {
|
||||||
format!(
|
format!(
|
||||||
"No saved credentials for '{}'. Please remove and re-add the account.",
|
"No saved credentials for '{}'. Please remove and re-add the account.",
|
||||||
@@ -192,7 +221,55 @@ pub async fn refresh_and_get_token(account: &Account) -> Result<(String, Option<
|
|||||||
.await
|
.await
|
||||||
.map_err(|e| format!("Minecraft auth failed: {e}"))?;
|
.map_err(|e| format!("Minecraft auth failed: {e}"))?;
|
||||||
|
|
||||||
Ok((mc_token.access_token().as_ref().to_owned(), new_refresh))
|
// minecraft-msa-auth does not expose this expiry here, so cache
|
||||||
|
// conservatively and refresh before the token gets close.
|
||||||
|
let expires_at = chrono::Utc::now().timestamp() + MC_TOKEN_CACHE_TTL_SECS;
|
||||||
|
|
||||||
|
Ok((
|
||||||
|
mc_token.access_token().as_ref().to_owned(),
|
||||||
|
new_refresh,
|
||||||
|
Some(expires_at),
|
||||||
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
+47
-14
@@ -21,13 +21,13 @@ pub async fn handle_account(matches: &ArgMatches) -> CliResult {
|
|||||||
|
|
||||||
// trait indirection so a mock store can be swapped in for tests
|
// trait indirection so a mock store can be swapped in for tests
|
||||||
trait AccountStoreLike {
|
trait AccountStoreLike {
|
||||||
fn accounts(&self) -> &[Account];
|
fn has_microsoft_account(&self) -> bool;
|
||||||
fn add_account(&mut self, account: Account);
|
fn add_account(&mut self, account: Account);
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AccountStoreLike for AccountStore {
|
impl AccountStoreLike for AccountStore {
|
||||||
fn accounts(&self) -> &[Account] {
|
fn has_microsoft_account(&self) -> bool {
|
||||||
&self.accounts
|
AccountStore::has_microsoft_account(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_account(&mut self, account: Account) {
|
fn add_account(&mut self, account: Account) {
|
||||||
@@ -81,7 +81,8 @@ async fn add_microsoft_account() -> CliResult {
|
|||||||
// wait for the device code to become available before showing it
|
// wait for the device code to become available before showing it
|
||||||
loop {
|
loop {
|
||||||
if let Ok(slot) = crate::auth::DEVICE_CODE_DISPLAY.lock()
|
if let Ok(slot) = crate::auth::DEVICE_CODE_DISPLAY.lock()
|
||||||
&& let Some(info) = slot.as_ref() {
|
&& let Some(info) = slot.as_ref()
|
||||||
|
{
|
||||||
println!("Open: {}", info.verification_uri);
|
println!("Open: {}", info.verification_uri);
|
||||||
println!("Code: {}", info.user_code);
|
println!("Code: {}", info.user_code);
|
||||||
break;
|
break;
|
||||||
@@ -92,7 +93,8 @@ async fn add_microsoft_account() -> CliResult {
|
|||||||
// now wait for the user to complete auth in their browser
|
// now wait for the user to complete auth in their browser
|
||||||
loop {
|
loop {
|
||||||
if let Ok(slot) = result_arc.lock()
|
if let Ok(slot) = result_arc.lock()
|
||||||
&& let Some(result) = slot.as_ref() {
|
&& let Some(result) = slot.as_ref()
|
||||||
|
{
|
||||||
return match result {
|
return match result {
|
||||||
AuthResult::Success(account) => {
|
AuthResult::Success(account) => {
|
||||||
let mut store = AccountStore::load();
|
let mut store = AccountStore::load();
|
||||||
@@ -112,6 +114,12 @@ fn add_offline_account<T: AccountStoreLike>(store: &mut T, username: &str) -> Cl
|
|||||||
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());
|
||||||
}
|
}
|
||||||
|
if !store.has_microsoft_account() {
|
||||||
|
return Err(io::Error::other(
|
||||||
|
"add a Microsoft account that owns Minecraft before adding offline accounts",
|
||||||
|
)
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
|
||||||
store.add_account(crate::auth::create_offline_account(username));
|
store.add_account(crate::auth::create_offline_account(username));
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -120,7 +128,7 @@ fn add_offline_account<T: AccountStoreLike>(store: &mut T, username: &str) -> Cl
|
|||||||
fn delete_account(matches: &ArgMatches) -> CliResult {
|
fn delete_account(matches: &ArgMatches) -> CliResult {
|
||||||
let username = required_arg(matches, "username")?;
|
let username = required_arg(matches, "username")?;
|
||||||
let mut store = AccountStore::load();
|
let mut store = AccountStore::load();
|
||||||
let index = find_account_index(store.accounts(), username)
|
let index = find_account_index(&store.accounts, username)
|
||||||
.ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?;
|
.ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?;
|
||||||
|
|
||||||
if !matches.get_flag("yes") && !confirm(&format!("Delete '{}'", username))? {
|
if !matches.get_flag("yes") && !confirm(&format!("Delete '{}'", username))? {
|
||||||
@@ -136,7 +144,7 @@ fn delete_account(matches: &ArgMatches) -> CliResult {
|
|||||||
fn use_account(matches: &ArgMatches) -> CliResult {
|
fn use_account(matches: &ArgMatches) -> CliResult {
|
||||||
let username = required_arg(matches, "username")?;
|
let username = required_arg(matches, "username")?;
|
||||||
let mut store = AccountStore::load();
|
let mut store = AccountStore::load();
|
||||||
let index = find_account_index(store.accounts(), username)
|
let index = find_account_index(&store.accounts, username)
|
||||||
.ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?;
|
.ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?;
|
||||||
store.set_active(index);
|
store.set_active(index);
|
||||||
println!("Active account set to '{}'.", username);
|
println!("Active account set to '{}'.", username);
|
||||||
@@ -153,7 +161,7 @@ use super::utils::{confirm, required_arg};
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{add_offline_account, AccountStoreLike};
|
use super::{AccountStoreLike, add_offline_account};
|
||||||
use crate::auth::{Account, AccountType};
|
use crate::auth::{Account, AccountType};
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
@@ -162,8 +170,10 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl AccountStoreLike for MockStore {
|
impl AccountStoreLike for MockStore {
|
||||||
fn accounts(&self) -> &[Account] {
|
fn has_microsoft_account(&self) -> bool {
|
||||||
&self.accounts
|
self.accounts
|
||||||
|
.iter()
|
||||||
|
.any(|account| account.account_type == AccountType::Microsoft)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_account(&mut self, account: Account) {
|
fn add_account(&mut self, account: Account) {
|
||||||
@@ -171,14 +181,37 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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]
|
#[test]
|
||||||
fn creates_offline_account_through_store() {
|
fn creates_offline_account_after_microsoft_account_exists() {
|
||||||
let mut store = MockStore::default();
|
let mut store = MockStore::default();
|
||||||
|
store.add_account(microsoft_account());
|
||||||
add_offline_account(&mut store, "Steve").expect("offline account should be added");
|
add_offline_account(&mut store, "Steve").expect("offline account should be added");
|
||||||
|
|
||||||
assert_eq!(store.accounts.len(), 1);
|
assert_eq!(store.accounts.len(), 2);
|
||||||
assert_eq!(store.accounts[0].username, "Steve");
|
assert_eq!(store.accounts[1].username, "Steve");
|
||||||
assert_eq!(store.accounts[0].account_type, AccountType::Offline);
|
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]
|
#[test]
|
||||||
|
|||||||
+9
-12
@@ -1,8 +1,9 @@
|
|||||||
// modpack importing from modrinth (remote slug/url) or local .mrpack files.
|
// modpack importing from modrinth (remote slug/url) or local files (.mrpack, mmc zips).
|
||||||
// resolves the input, downloads if needed, then hands off to the import engine.
|
// resolves the input, downloads if needed, then hands off to the import engine.
|
||||||
use clap::ArgMatches;
|
use clap::ArgMatches;
|
||||||
|
|
||||||
use crate::instance::InstanceManager;
|
use crate::instance::InstanceManager;
|
||||||
|
use crate::instance::import::{ImportInput, parse_import_input};
|
||||||
use crate::net::modrinth;
|
use crate::net::modrinth;
|
||||||
|
|
||||||
type CliResult = Result<(), Box<dyn std::error::Error>>;
|
type CliResult = Result<(), Box<dyn std::error::Error>>;
|
||||||
@@ -17,18 +18,17 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
|||||||
let manager = InstanceManager::new(instances_dir, meta_dir);
|
let manager = InstanceManager::new(instances_dir, meta_dir);
|
||||||
let client = crate::net::HttpClient::new();
|
let client = crate::net::HttpClient::new();
|
||||||
|
|
||||||
// figure out what the user gave us: a local file, a project slug, or a versioned URL
|
let parsed = parse_import_input(input);
|
||||||
let parsed = modrinth::parse_input(input);
|
|
||||||
|
|
||||||
let mrpack_path = match parsed {
|
let archive_path = match parsed {
|
||||||
modrinth::ModrinthInput::LocalFile(ref path) => {
|
ImportInput::LocalFile(ref path) => {
|
||||||
let resolved = crate::config::settings::resolve_path(path);
|
let resolved = crate::config::settings::resolve_path(path);
|
||||||
if !resolved.exists() {
|
if !resolved.exists() {
|
||||||
return Err(format!("File not found: {}", resolved.display()).into());
|
return Err(format!("File not found: {}", resolved.display()).into());
|
||||||
}
|
}
|
||||||
resolved
|
resolved
|
||||||
}
|
}
|
||||||
modrinth::ModrinthInput::ProjectSlug(ref slug) => {
|
ImportInput::ProjectSlug(ref slug) => {
|
||||||
println!("Fetching project '{slug}'...");
|
println!("Fetching project '{slug}'...");
|
||||||
let project = modrinth::fetch_project(&client, slug)
|
let project = modrinth::fetch_project(&client, slug)
|
||||||
.await
|
.await
|
||||||
@@ -64,7 +64,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
|||||||
.await
|
.await
|
||||||
.map_err(|e| format!("Failed to download .mrpack: {e}"))?
|
.map_err(|e| format!("Failed to download .mrpack: {e}"))?
|
||||||
}
|
}
|
||||||
modrinth::ModrinthInput::VersionId {
|
ImportInput::VersionId {
|
||||||
slug: _,
|
slug: _,
|
||||||
ref version_id,
|
ref version_id,
|
||||||
} => {
|
} => {
|
||||||
@@ -87,10 +87,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let index = modrinth::parse_mrpack(&mrpack_path)
|
let mut summary = crate::instance::import::build_summary(&archive_path)
|
||||||
.map_err(|e| format!("Failed to parse .mrpack: {e}"))?;
|
|
||||||
|
|
||||||
let mut summary = crate::instance::import::build_summary(&index, mrpack_path)
|
|
||||||
.map_err(|e| format!("Invalid modpack: {e}"))?;
|
.map_err(|e| format!("Invalid modpack: {e}"))?;
|
||||||
|
|
||||||
if let Some(name) = override_name {
|
if let Some(name) = override_name {
|
||||||
@@ -98,7 +95,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,
|
||||||
|
|||||||
+5
-15
@@ -65,7 +65,7 @@ fn manager() -> InstanceManager {
|
|||||||
|
|
||||||
fn list_instances() -> CliResult {
|
fn list_instances() -> CliResult {
|
||||||
let mut instances = manager().load_all();
|
let mut instances = manager().load_all();
|
||||||
instances.sort_by(|left, right| left.name.to_lowercase().cmp(&right.name.to_lowercase()));
|
instances.sort_by_key(|instance| instance.name.to_lowercase());
|
||||||
|
|
||||||
let rows = instances
|
let rows = instances
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -134,7 +134,6 @@ 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)
|
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)))?;
|
||||||
@@ -144,16 +143,15 @@ async fn launch_instance(matches: &ArgMatches) -> CliResult {
|
|||||||
loop {
|
loop {
|
||||||
match crate::running::get(name) {
|
match crate::running::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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -249,18 +247,10 @@ fn apply_config_update(
|
|||||||
) -> CliResult {
|
) -> CliResult {
|
||||||
match key {
|
match key {
|
||||||
"memory-max" => {
|
"memory-max" => {
|
||||||
config.memory_max = if value.is_empty() {
|
config.memory_max = crate::instance::normalize_memory_value(value);
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(value.to_string())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
"memory-min" => {
|
"memory-min" => {
|
||||||
config.memory_min = if value.is_empty() {
|
config.memory_min = crate::instance::normalize_memory_value(value);
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(value.to_string())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
"java-path" => {
|
"java-path" => {
|
||||||
config.java_path = if value.is_empty() {
|
config.java_path = if value.is_empty() {
|
||||||
|
|||||||
+7
-21
@@ -91,47 +91,33 @@ use super::utils::{require_instance, required_arg};
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::resolve_log_path;
|
use super::resolve_log_path;
|
||||||
|
|
||||||
fn unique_temp_dir() -> std::path::PathBuf {
|
|
||||||
std::env::temp_dir().join(format!(
|
|
||||||
"mcl_cli_log_test_{}",
|
|
||||||
std::time::SystemTime::now()
|
|
||||||
.duration_since(std::time::UNIX_EPOCH)
|
|
||||||
.expect("time should work")
|
|
||||||
.as_nanos()
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn resolves_latest_log_when_no_file_is_given() {
|
fn resolves_latest_log_when_no_file_is_given() {
|
||||||
let root = unique_temp_dir();
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
let dir = root.join("demo/.minecraft/logs/launches");
|
let dir = tmp.path().join("demo/.minecraft/logs/launches");
|
||||||
std::fs::create_dir_all(&dir).expect("log directory should exist");
|
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-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");
|
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");
|
let path = resolve_log_path(tmp.path(), "demo", None).expect("latest log should resolve");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
path.file_name().and_then(|name| name.to_str()),
|
path.file_name().and_then(|name| name.to_str()),
|
||||||
Some("2024-01-02_03-04-05.log")
|
Some("2024-01-02_03-04-05.log")
|
||||||
);
|
);
|
||||||
|
|
||||||
let _ = std::fs::remove_dir_all(&root);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn resolves_named_log_file() {
|
fn resolves_named_log_file() {
|
||||||
let root = unique_temp_dir();
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
let dir = root.join("demo/.minecraft/logs/launches");
|
let dir = tmp.path().join("demo/.minecraft/logs/launches");
|
||||||
std::fs::create_dir_all(&dir).expect("log directory should exist");
|
std::fs::create_dir_all(&dir).expect("log directory should exist");
|
||||||
std::fs::write(dir.join("latest.log"), "hello").expect("write named log");
|
std::fs::write(dir.join("latest.log"), "hello").expect("write named log");
|
||||||
|
|
||||||
let path =
|
let path = resolve_log_path(tmp.path(), "demo", Some("latest.log"))
|
||||||
resolve_log_path(&root, "demo", Some("latest.log")).expect("named log should resolve");
|
.expect("named log should resolve");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
path.file_name().and_then(|name| name.to_str()),
|
path.file_name().and_then(|name| name.to_str()),
|
||||||
Some("latest.log")
|
Some("latest.log")
|
||||||
);
|
);
|
||||||
|
|
||||||
let _ = std::fs::remove_dir_all(&root);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+11
-4
@@ -14,7 +14,7 @@ use clap::{Arg, ArgAction, ArgGroup, Command};
|
|||||||
pub async fn init() {
|
pub async fn init() {
|
||||||
let matches = build_command().get_matches();
|
let matches = build_command().get_matches();
|
||||||
|
|
||||||
// no subcommand means the user just ran `mcl` bare, so fall through to TUI mode
|
// no subcommand means the user just ran `rmcl` bare, so fall through to TUI mode
|
||||||
if matches.subcommand().is_none() {
|
if matches.subcommand().is_none() {
|
||||||
// force-init the theme so it's ready before the TUI renders
|
// force-init the theme so it's ready before the TUI renders
|
||||||
let _ = &*crate::config::theme::THEME;
|
let _ = &*crate::config::theme::THEME;
|
||||||
@@ -43,7 +43,7 @@ pub async fn init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn build_command() -> Command {
|
fn build_command() -> Command {
|
||||||
Command::new("mcl")
|
Command::new("rmcl")
|
||||||
.about("Minecraft CLI Launcher")
|
.about("Minecraft CLI Launcher")
|
||||||
.version(env!("CARGO_PKG_VERSION"))
|
.version(env!("CARGO_PKG_VERSION"))
|
||||||
.subcommand_required(false)
|
.subcommand_required(false)
|
||||||
@@ -245,8 +245,15 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn parses_instance_list_subcommand() {
|
fn parses_instance_list_subcommand() {
|
||||||
let matches = build_command()
|
let matches = build_command()
|
||||||
.try_get_matches_from(["mcl", "instance", "list"])
|
.try_get_matches_from(["rmcl", "instance", "list"])
|
||||||
.expect("command should parse");
|
.expect("command should parse");
|
||||||
assert!(matches.subcommand_matches("instance").is_some());
|
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"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+1
-5
@@ -34,11 +34,7 @@ pub fn format_datetime(value: &DateTime<Utc>) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn active_marker(active: bool) -> &'static str {
|
pub fn active_marker(active: bool) -> &'static str {
|
||||||
if active {
|
if active { ">" } else { " " }
|
||||||
">"
|
|
||||||
} else {
|
|
||||||
" "
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// find the widest value in each column to pad everything evenly
|
// find the widest value in each column to pad everything evenly
|
||||||
|
|||||||
+1
-1
@@ -9,8 +9,8 @@ use clap::ArgMatches;
|
|||||||
use crate::cli::instance::parse_loader;
|
use crate::cli::instance::parse_loader;
|
||||||
use crate::cli::output::print_table;
|
use crate::cli::output::print_table;
|
||||||
use crate::instance::ModLoader;
|
use crate::instance::ModLoader;
|
||||||
use crate::net::mojang::{VersionEntry, VersionManifest};
|
|
||||||
use crate::net::HttpClient;
|
use crate::net::HttpClient;
|
||||||
|
use crate::net::mojang::{VersionEntry, VersionManifest};
|
||||||
|
|
||||||
type CliResult = Result<(), Box<dyn std::error::Error>>;
|
type CliResult = Result<(), Box<dyn std::error::Error>>;
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -15,7 +15,7 @@ pub use settings::Config;
|
|||||||
pub fn get_config_path() -> PathBuf {
|
pub fn get_config_path() -> PathBuf {
|
||||||
dirs_next::config_dir()
|
dirs_next::config_dir()
|
||||||
.unwrap_or_else(|| PathBuf::from("."))
|
.unwrap_or_else(|| PathBuf::from("."))
|
||||||
.join("mcl")
|
.join("rmcl")
|
||||||
}
|
}
|
||||||
|
|
||||||
// seeds the config file from the bundled default on first run
|
// seeds the config file from the bundled default on first run
|
||||||
|
|||||||
+7
-43
@@ -21,7 +21,7 @@ pub struct Paths {
|
|||||||
fn default_instances_dir() -> String {
|
fn default_instances_dir() -> String {
|
||||||
dirs_next::data_dir()
|
dirs_next::data_dir()
|
||||||
.unwrap_or_else(|| PathBuf::from("."))
|
.unwrap_or_else(|| PathBuf::from("."))
|
||||||
.join("mcl")
|
.join("rmcl")
|
||||||
.join("instances")
|
.join("instances")
|
||||||
.to_string_lossy()
|
.to_string_lossy()
|
||||||
.into_owned()
|
.into_owned()
|
||||||
@@ -30,7 +30,7 @@ fn default_instances_dir() -> String {
|
|||||||
fn default_meta_dir() -> String {
|
fn default_meta_dir() -> String {
|
||||||
dirs_next::data_dir()
|
dirs_next::data_dir()
|
||||||
.unwrap_or_else(|| PathBuf::from("."))
|
.unwrap_or_else(|| PathBuf::from("."))
|
||||||
.join("mcl")
|
.join("rmcl")
|
||||||
.join("meta")
|
.join("meta")
|
||||||
.to_string_lossy()
|
.to_string_lossy()
|
||||||
.into_owned()
|
.into_owned()
|
||||||
@@ -53,7 +53,8 @@ pub fn resolve_path(raw: &str) -> PathBuf {
|
|||||||
return home.join(stripped);
|
return home.join(stripped);
|
||||||
}
|
}
|
||||||
} else if raw == "~"
|
} else if raw == "~"
|
||||||
&& let Some(home) = dirs_next::home_dir() {
|
&& let Some(home) = dirs_next::home_dir()
|
||||||
|
{
|
||||||
return home;
|
return home;
|
||||||
}
|
}
|
||||||
PathBuf::from(raw)
|
PathBuf::from(raw)
|
||||||
@@ -180,14 +181,14 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn resolve_path_absolute() {
|
fn resolve_path_absolute() {
|
||||||
assert_eq!(resolve_path("/opt/mcl"), PathBuf::from("/opt/mcl"));
|
assert_eq!(resolve_path("/opt/rmcl"), PathBuf::from("/opt/rmcl"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn resolve_path_tilde_prefix() {
|
fn resolve_path_tilde_prefix() {
|
||||||
let resolved = resolve_path("~/games/mcl");
|
let resolved = resolve_path("~/games/rmcl");
|
||||||
assert!(!resolved.to_string_lossy().starts_with('~'));
|
assert!(!resolved.to_string_lossy().starts_with('~'));
|
||||||
assert!(resolved.to_string_lossy().ends_with("games/mcl"));
|
assert!(resolved.to_string_lossy().ends_with("games/rmcl"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -196,43 +197,6 @@ mod tests {
|
|||||||
assert!(!resolved.to_string_lossy().starts_with('~'));
|
assert!(!resolved.to_string_lossy().starts_with('~'));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolve_instances_dir_absolute() {
|
|
||||||
let paths = Paths {
|
|
||||||
instances_dir: "/opt/mcl/instances".to_owned(),
|
|
||||||
..Paths::default()
|
|
||||||
};
|
|
||||||
assert_eq!(
|
|
||||||
paths.resolve_instances_dir(),
|
|
||||||
PathBuf::from("/opt/mcl/instances")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolve_meta_dir_absolute() {
|
|
||||||
let paths = Paths {
|
|
||||||
meta_dir: "/opt/mcl/meta".to_owned(),
|
|
||||||
..Paths::default()
|
|
||||||
};
|
|
||||||
assert_eq!(paths.resolve_meta_dir(), PathBuf::from("/opt/mcl/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]
|
#[test]
|
||||||
fn config_deserializes_from_empty_toml() {
|
fn config_deserializes_from_empty_toml() {
|
||||||
let config: Config = toml::from_str("").unwrap();
|
let config: Config = toml::from_str("").unwrap();
|
||||||
|
|||||||
+9
-12
@@ -172,18 +172,15 @@ pub static BORDER_STYLE: LazyLock<BorderStyle> =
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
// cover every BorderStyle variant. a mutation that swaps two arms of the
|
||||||
fn default_theme_config() {
|
// match (e.g. Rounded -> Plain) would slip past testing just one variant.
|
||||||
let config = ThemeConfig::default();
|
#[rstest::rstest]
|
||||||
assert_eq!(config.theme, "catppuccin");
|
#[case::plain(BorderStyle::Plain, BorderType::Plain)]
|
||||||
assert_eq!(config.border_style, BorderStyle::Rounded);
|
#[case::rounded(BorderStyle::Rounded, BorderType::Rounded)]
|
||||||
assert!(config.custom.is_none());
|
#[case::double(BorderStyle::Double, BorderType::Double)]
|
||||||
}
|
#[case::thick(BorderStyle::Thick, BorderType::Thick)]
|
||||||
|
fn border_style_roundtrip(#[case] style: BorderStyle, #[case] expected: BorderType) {
|
||||||
#[test]
|
assert_eq!(style.to_border_type(), expected);
|
||||||
fn border_style_roundtrip() {
|
|
||||||
let style = BorderStyle::Double;
|
|
||||||
assert_eq!(style.to_border_type(), BorderType::Double);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -7,9 +7,10 @@ pub mod shaders;
|
|||||||
pub mod worlds;
|
pub mod worlds;
|
||||||
|
|
||||||
pub use mods::{ContentEntry, scan_mods, toggle_entry};
|
pub use mods::{ContentEntry, scan_mods, toggle_entry};
|
||||||
pub use resource_packs::scan_resource_packs;
|
pub use mods::scan_one_mod;
|
||||||
pub use shaders::scan_shaders;
|
pub use resource_packs::{scan_resource_packs, scan_one_resource_pack};
|
||||||
pub use worlds::scan_worlds;
|
pub use shaders::{scan_shaders, scan_one_shader};
|
||||||
|
pub use worlds::{scan_worlds, scan_one_world};
|
||||||
|
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
|
|
||||||
|
|||||||
+477
-35
@@ -1,6 +1,8 @@
|
|||||||
// mod scanning, metadata extraction, and icon rendering for the content list.
|
// mod scanning, metadata extraction, and icon rendering for the content list.
|
||||||
// jar files are just zips, so it cracks them open looking for fabric.mod.json to get
|
// jar files are just zips, so it cracks them open looking for loader-specific
|
||||||
// names, descriptions, and icons. if that fails, just the filename is used. it's fine.
|
// metadata (fabric.mod.json, quilt.mod.json, mods.toml, mcmod.info) to get
|
||||||
|
// names, descriptions, and icons. if none of those work, falls back to common
|
||||||
|
// root-level icon paths (logo.png, icon.png, pack.png) or just the filename.
|
||||||
|
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
@@ -41,10 +43,15 @@ struct FabricModJson {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl FabricModJson {
|
impl FabricModJson {
|
||||||
// fabric's icon field can be a string path or a map of resolution -> path.
|
|
||||||
// if it's a map, just grab the first one. good enough.
|
|
||||||
fn icon_path(&self) -> String {
|
fn icon_path(&self) -> String {
|
||||||
match &self.icon {
|
icon_path_from_value(&self.icon)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fabric and quilt both support icon as a string path or a map of
|
||||||
|
// resolution -> path. if it's a map, just grab the first one.
|
||||||
|
fn icon_path_from_value(value: &serde_json::Value) -> String {
|
||||||
|
match value {
|
||||||
serde_json::Value::String(s) => s.clone(),
|
serde_json::Value::String(s) => s.clone(),
|
||||||
serde_json::Value::Object(map) => map
|
serde_json::Value::Object(map) => map
|
||||||
.values()
|
.values()
|
||||||
@@ -54,6 +61,58 @@ impl FabricModJson {
|
|||||||
_ => String::new(),
|
_ => String::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// quilt puts its metadata under a "metadata" sub-object
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
struct QuiltModJson {
|
||||||
|
#[serde(default)]
|
||||||
|
quilt_loader: QuiltLoader,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
struct QuiltLoader {
|
||||||
|
#[serde(default)]
|
||||||
|
metadata: QuiltMetadata,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
struct QuiltMetadata {
|
||||||
|
#[serde(default)]
|
||||||
|
name: String,
|
||||||
|
#[serde(default)]
|
||||||
|
description: String,
|
||||||
|
#[serde(default)]
|
||||||
|
icon: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl QuiltMetadata {
|
||||||
|
fn icon_path(&self) -> String {
|
||||||
|
icon_path_from_value(&self.icon)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn scan_one_mod(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||||
|
let (name, description, icon_bytes) = read_mod_metadata(path);
|
||||||
|
let icon_lines = icon_bytes
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
|
||||||
|
.or_else(|| Some(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_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||||
@@ -80,34 +139,17 @@ pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry>
|
|||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
let (name, description, icon_bytes) = read_mod_metadata(&path);
|
entries.push(scan_one_mod(&path, &file_stem, enabled));
|
||||||
let icon_lines = icon_bytes
|
|
||||||
.as_ref()
|
|
||||||
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
|
|
||||||
.or_else(|| Some(fallback_icon()));
|
|
||||||
|
|
||||||
let display_name = if name.is_empty() {
|
|
||||||
file_stem.clone()
|
|
||||||
} else {
|
|
||||||
name
|
|
||||||
};
|
|
||||||
entries.push(ContentEntry {
|
|
||||||
file_stem,
|
|
||||||
name: display_name,
|
|
||||||
description,
|
|
||||||
enabled,
|
|
||||||
icon_bytes,
|
|
||||||
path,
|
|
||||||
icon_lines,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
entries.sort_by_cached_key(|e| e.name.to_lowercase());
|
entries.sort_by_cached_key(|e| e.name.to_lowercase());
|
||||||
entries
|
entries
|
||||||
}
|
}
|
||||||
|
|
||||||
// tries fabric.mod.json first for rich metadata. if that's missing (forge/other mods),
|
// tries each loader's metadata file to extract name, description, and icon.
|
||||||
// still attempts to grab pack.png as a last resort for an icon
|
// checks fabric.mod.json, quilt.mod.json, META-INF/mods.toml (forge),
|
||||||
|
// META-INF/neoforge.mods.toml, and mcmod.info (legacy forge). if none of
|
||||||
|
// those yield an icon, falls back to common root-level paths.
|
||||||
fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
|
fn read_mod_metadata(jar_path: &Path) -> (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,
|
||||||
@@ -119,19 +161,43 @@ fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
|
|||||||
Err(_) => return (String::new(), String::new(), None),
|
Err(_) => return (String::new(), String::new(), None),
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Some((name, description, icon_path)) = read_fabric_meta(&mut archive) {
|
// try each loader's metadata in order. if we get metadata but the
|
||||||
let icon_bytes = if icon_path.is_empty() {
|
// 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)>;
|
||||||
|
let readers: [MetaReader; 4] = [
|
||||||
|
read_fabric_meta,
|
||||||
|
read_quilt_meta,
|
||||||
|
read_forge_toml_meta,
|
||||||
|
read_mcmod_info,
|
||||||
|
];
|
||||||
|
|
||||||
|
for reader in &readers {
|
||||||
|
if let Some((name, description, icon_path)) = reader(&mut archive) {
|
||||||
|
let icon_path = icon_path.trim_start_matches('/');
|
||||||
|
let icon = if icon_path.is_empty() {
|
||||||
None
|
None
|
||||||
} else {
|
} else {
|
||||||
read_zip_bytes(&mut archive, &icon_path)
|
read_zip_bytes(&mut archive, icon_path)
|
||||||
};
|
}
|
||||||
return (name, description, icon_bytes);
|
.or_else(|| try_fallback_icons(&mut archive));
|
||||||
|
return (name, description, icon);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let icon_bytes = read_zip_bytes(&mut archive, "pack.png");
|
// no recognized metadata at all, try common icon paths
|
||||||
|
let icon_bytes = try_fallback_icons(&mut archive);
|
||||||
(String::new(), String::new(), icon_bytes)
|
(String::new(), String::new(), icon_bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn try_fallback_icons(archive: &mut zip::ZipArchive<std::fs::File>) -> Option<Vec<u8>> {
|
||||||
|
for path in ["logo.png", "icon.png", "pack.png"] {
|
||||||
|
if let Some(bytes) = read_zip_bytes(archive, path) {
|
||||||
|
return Some(bytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
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)> {
|
||||||
@@ -144,6 +210,98 @@ fn read_fabric_meta(
|
|||||||
Some((data.name, data.description, icon))
|
Some((data.name, data.description, icon))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn read_quilt_meta(
|
||||||
|
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||||
|
) -> Option<(String, String, String)> {
|
||||||
|
let mut entry = archive.by_name("quilt.mod.json").ok()?;
|
||||||
|
let mut raw = String::new();
|
||||||
|
entry.read_to_string(&mut raw).ok()?;
|
||||||
|
let sanitized = sanitize_json_strings(&raw);
|
||||||
|
let data: QuiltModJson = serde_json::from_str(&sanitized).ok()?;
|
||||||
|
let meta = data.quilt_loader.metadata;
|
||||||
|
let icon = meta.icon_path();
|
||||||
|
Some((meta.name, meta.description, icon))
|
||||||
|
}
|
||||||
|
|
||||||
|
// forge (META-INF/mods.toml) and neoforge (META-INF/neoforge.mods.toml)
|
||||||
|
// share the same format. we only need the top-level logoFile and the first
|
||||||
|
// [[mods]] entry for name/description.
|
||||||
|
// some jars (e.g. dependency-only libs) have a mods.toml with logoFile
|
||||||
|
// but no [[mods]] section. we still want the icon in that case.
|
||||||
|
fn read_forge_toml_meta(
|
||||||
|
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||||
|
) -> Option<(String, String, String)> {
|
||||||
|
let raw = read_zip_string(archive, "META-INF/neoforge.mods.toml")
|
||||||
|
.or_else(|| read_zip_string(archive, "META-INF/mods.toml"))?;
|
||||||
|
let table: toml::Table = raw.parse().ok()?;
|
||||||
|
let logo = table
|
||||||
|
.get("logoFile")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_owned();
|
||||||
|
let (name, description) = table
|
||||||
|
.get("mods")
|
||||||
|
.and_then(|v| v.as_array())
|
||||||
|
.and_then(|a| a.first())
|
||||||
|
.and_then(|v| v.as_table())
|
||||||
|
.map(|first| {
|
||||||
|
let n = first
|
||||||
|
.get("displayName")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_owned();
|
||||||
|
let d = first
|
||||||
|
.get("description")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.trim()
|
||||||
|
.to_owned();
|
||||||
|
(n, d)
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
Some((name, description, logo))
|
||||||
|
}
|
||||||
|
|
||||||
|
// legacy forge mcmod.info is either a bare json array of mod entries
|
||||||
|
// or an object with a "modList" key wrapping the array
|
||||||
|
fn read_mcmod_info(
|
||||||
|
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||||
|
) -> Option<(String, String, String)> {
|
||||||
|
let mut entry = archive.by_name("mcmod.info").ok()?;
|
||||||
|
let mut raw = String::new();
|
||||||
|
entry.read_to_string(&mut raw).ok()?;
|
||||||
|
let sanitized = sanitize_json_strings(&raw);
|
||||||
|
let parsed: serde_json::Value = serde_json::from_str(&sanitized).ok()?;
|
||||||
|
let first = match &parsed {
|
||||||
|
serde_json::Value::Array(arr) => arr.first()?,
|
||||||
|
serde_json::Value::Object(obj) => obj.get("modList")?.as_array()?.first()?,
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
let name = first
|
||||||
|
.get("name")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_owned();
|
||||||
|
let description = first
|
||||||
|
.get("description")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_owned();
|
||||||
|
let logo = first
|
||||||
|
.get("logoFile")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_owned();
|
||||||
|
Some((name, description, logo))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_zip_string(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> Option<String> {
|
||||||
|
let mut entry = archive.by_name(path).ok()?;
|
||||||
|
let mut s = String::new();
|
||||||
|
entry.read_to_string(&mut s).ok()?;
|
||||||
|
Some(s)
|
||||||
|
}
|
||||||
|
|
||||||
// some mod authors put raw newlines/tabs inside json string values which is
|
// some mod authors put raw newlines/tabs inside json string values which is
|
||||||
// technically invalid json. walks through character by character, tracking
|
// technically invalid json. walks through character by character, tracking
|
||||||
// whether it's inside a string, and escapes the offending characters.
|
// whether it's inside a string, and escapes the offending characters.
|
||||||
@@ -226,8 +384,8 @@ pub(crate) fn make_icon_pixels(
|
|||||||
Some(rows)
|
Some(rows)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 6x3 fallback icon showing a "?" pattern for mods without icons.
|
// 6x3 fallback icon showing a "?" pattern for mods without icons.
|
||||||
fn fallback_icon() -> Vec<Vec<IconCell>> {
|
pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
|
||||||
let b = IconCell {
|
let b = IconCell {
|
||||||
bg_r: 50,
|
bg_r: 50,
|
||||||
bg_g: 50,
|
bg_g: 50,
|
||||||
@@ -259,6 +417,42 @@ fn fallback_icon() -> Vec<Vec<IconCell>> {
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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.
|
// enable/disable by renaming the file with/without ".disabled" suffix.
|
||||||
// the minecraft way, apparently.
|
// the minecraft way, apparently.
|
||||||
pub fn toggle_entry(entry: &ContentEntry) -> Result<(), std::io::Error> {
|
pub fn toggle_entry(entry: &ContentEntry) -> Result<(), std::io::Error> {
|
||||||
@@ -371,6 +565,254 @@ mod tests {
|
|||||||
assert!(dir.join("mymod.jar").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","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_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]
|
#[test]
|
||||||
fn toggle_entry_disable() {
|
fn toggle_entry_disable() {
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use std::path::Path;
|
|||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
use super::mods::{make_icon_pixels, ContentEntry};
|
use super::mods::{ContentEntry, make_icon_pixels};
|
||||||
|
|
||||||
#[derive(Deserialize, Default)]
|
#[derive(Deserialize, Default)]
|
||||||
pub(crate) struct PackMcMeta {
|
pub(crate) struct PackMcMeta {
|
||||||
@@ -43,6 +43,36 @@ pub(crate) fn extract_description(value: &serde_json::Value) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn scan_one_resource_pack(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||||
|
let is_dir = path.is_dir();
|
||||||
|
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
|
let packs_dir = instances_dir
|
||||||
.join(instance_name)
|
.join(instance_name)
|
||||||
@@ -63,8 +93,7 @@ pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<Con
|
|||||||
None => continue,
|
None => continue,
|
||||||
};
|
};
|
||||||
|
|
||||||
let is_dir = path.is_dir();
|
let (enabled, file_stem) = if path.is_dir() {
|
||||||
let (enabled, file_stem) = if is_dir {
|
|
||||||
super::parse_enabled_stem_dir(&file_name)
|
super::parse_enabled_stem_dir(&file_name)
|
||||||
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
|
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
|
||||||
pair
|
pair
|
||||||
@@ -72,26 +101,7 @@ pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<Con
|
|||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
let (name, description, icon_bytes) = if is_dir {
|
entries.push(scan_one_resource_pack(&path, &file_stem, enabled));
|
||||||
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));
|
|
||||||
|
|
||||||
let display_name = if name.is_empty() { file_stem.clone() } else { name };
|
|
||||||
entries.push(ContentEntry {
|
|
||||||
file_stem,
|
|
||||||
name: display_name,
|
|
||||||
description,
|
|
||||||
enabled,
|
|
||||||
icon_bytes,
|
|
||||||
path,
|
|
||||||
icon_lines,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
entries.sort_by_cached_key(|e| e.name.to_lowercase());
|
entries.sort_by_cached_key(|e| e.name.to_lowercase());
|
||||||
@@ -131,128 +141,24 @@ fn read_pack_metadata_from_dir(dir: &Path) -> (String, String, Option<Vec<u8>>)
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
#[test]
|
// every case exercises a distinct match arm in extract_description.
|
||||||
fn extract_description_from_string() {
|
// string + object{text} + object{no text} + array(string) +
|
||||||
let val = serde_json::json!("Simple pack");
|
// array(object) + array(mixed) + array(empty) + null + number + bool.
|
||||||
assert_eq!(extract_description(&val), "Simple pack");
|
// mutating any arm to fall through to "" would fail at least one case.
|
||||||
}
|
#[rstest::rstest]
|
||||||
|
#[case::string(json!("Simple pack"), "Simple pack")]
|
||||||
#[test]
|
#[case::object_with_text(json!({"text": "Hello world"}), "Hello world")]
|
||||||
fn extract_description_from_object_with_text() {
|
#[case::object_without_text(json!({"color": "red"}), "")]
|
||||||
let val = serde_json::json!({"text": "Hello world"});
|
#[case::array_of_strings(json!(["Hello", " ", "world"]), "Hello world")]
|
||||||
assert_eq!(extract_description(&val), "Hello world");
|
#[case::array_of_objects(json!([{"text": "A"}, {"text": "B"}]), "AB")]
|
||||||
}
|
#[case::mixed_array(json!(["Prefix ", {"text": "suffix"}]), "Prefix suffix")]
|
||||||
|
#[case::empty_array(json!([]), "")]
|
||||||
#[test]
|
#[case::null(serde_json::Value::Null, "")]
|
||||||
fn extract_description_from_object_without_text() {
|
#[case::number(json!(42), "")]
|
||||||
let val = serde_json::json!({"color": "red"});
|
#[case::bool(json!(true), "")]
|
||||||
assert_eq!(extract_description(&val), "");
|
fn extract_description_handles(#[case] input: serde_json::Value, #[case] expected: &str) {
|
||||||
}
|
assert_eq!(extract_description(&input), expected);
|
||||||
|
|
||||||
#[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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,8 +3,31 @@
|
|||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use super::mods::{make_icon_pixels, ContentEntry};
|
use super::mods::{ContentEntry, make_icon_pixels};
|
||||||
use super::resource_packs::{extract_description, PackMcMeta};
|
use super::resource_packs::{PackMcMeta, extract_description};
|
||||||
|
|
||||||
|
pub fn scan_one_shader(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||||
|
let is_dir = path.is_dir();
|
||||||
|
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
|
let shaders_dir = instances_dir
|
||||||
@@ -26,8 +49,7 @@ pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEnt
|
|||||||
None => continue,
|
None => continue,
|
||||||
};
|
};
|
||||||
|
|
||||||
let is_dir = path.is_dir();
|
let (enabled, file_stem) = if path.is_dir() {
|
||||||
let (enabled, file_stem) = if is_dir {
|
|
||||||
super::parse_enabled_stem_dir(&file_name)
|
super::parse_enabled_stem_dir(&file_name)
|
||||||
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
|
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
|
||||||
pair
|
pair
|
||||||
@@ -35,25 +57,7 @@ pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEnt
|
|||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
let (description, icon_bytes) = if is_dir {
|
entries.push(scan_one_shader(&path, &file_stem, enabled));
|
||||||
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));
|
|
||||||
|
|
||||||
entries.push(ContentEntry {
|
|
||||||
name: file_stem.clone(),
|
|
||||||
file_stem,
|
|
||||||
description,
|
|
||||||
enabled,
|
|
||||||
icon_bytes,
|
|
||||||
path,
|
|
||||||
icon_lines,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
entries.sort_by_cached_key(|e| e.name.to_lowercase());
|
entries.sort_by_cached_key(|e| e.name.to_lowercase());
|
||||||
@@ -86,64 +90,3 @@ fn read_shader_metadata_from_dir(dir: &Path) -> (String, Option<Vec<u8>>) {
|
|||||||
(description, icon_bytes)
|
(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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,27 @@
|
|||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use super::mods::{make_icon_pixels, ContentEntry};
|
use super::mods::{ContentEntry, make_icon_pixels};
|
||||||
|
|
||||||
|
pub fn scan_one_world(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||||
|
let icon_bytes = std::fs::read(path.join("icon.png")).ok();
|
||||||
|
let icon_lines = icon_bytes
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|bytes| make_icon_pixels(bytes, 12, 6))
|
||||||
|
.or_else(|| Some(super::mods::fallback_icon_large()));
|
||||||
|
|
||||||
|
let description = world_description(path);
|
||||||
|
|
||||||
|
ContentEntry {
|
||||||
|
name: file_stem.to_owned(),
|
||||||
|
file_stem: file_stem.to_owned(),
|
||||||
|
description,
|
||||||
|
enabled,
|
||||||
|
icon_bytes,
|
||||||
|
path: path.to_path_buf(),
|
||||||
|
icon_lines,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
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
|
||||||
@@ -31,23 +51,7 @@ pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntr
|
|||||||
};
|
};
|
||||||
|
|
||||||
let (enabled, file_stem) = super::parse_enabled_stem_dir(&file_name);
|
let (enabled, file_stem) = super::parse_enabled_stem_dir(&file_name);
|
||||||
|
entries.push(scan_one_world(&path, &file_stem, enabled));
|
||||||
let icon_bytes = std::fs::read(path.join("icon.png")).ok();
|
|
||||||
let icon_lines = icon_bytes
|
|
||||||
.as_ref()
|
|
||||||
.and_then(|bytes| make_icon_pixels(bytes, 12, 6));
|
|
||||||
|
|
||||||
let description = world_description(&path);
|
|
||||||
|
|
||||||
entries.push(ContentEntry {
|
|
||||||
name: file_stem.clone(),
|
|
||||||
file_stem,
|
|
||||||
description,
|
|
||||||
enabled,
|
|
||||||
icon_bytes,
|
|
||||||
path,
|
|
||||||
icon_lines,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
entries.sort_by_cached_key(|e| e.name.to_lowercase());
|
entries.sort_by_cached_key(|e| e.name.to_lowercase());
|
||||||
@@ -76,12 +80,14 @@ fn world_description(world_dir: &Path) -> String {
|
|||||||
let mut lines = Vec::new();
|
let mut lines = Vec::new();
|
||||||
|
|
||||||
if let Some(secs) = created
|
if let Some(secs) = created
|
||||||
&& let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0) {
|
&& let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0)
|
||||||
|
{
|
||||||
lines.push(format!("Created: {}", dt.format("%Y-%m-%d %H:%M")));
|
lines.push(format!("Created: {}", dt.format("%Y-%m-%d %H:%M")));
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(secs) = modified
|
if let Some(secs) = modified
|
||||||
&& let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0) {
|
&& let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0)
|
||||||
|
{
|
||||||
lines.push(format!("Played: {}", dt.format("%Y-%m-%d %H:%M")));
|
lines.push(format!("Played: {}", dt.format("%Y-%m-%d %H:%M")));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,7 +105,8 @@ fn dir_size_approx(path: &Path) -> u64 {
|
|||||||
if let Ok(rd) = std::fs::read_dir(path) {
|
if let Ok(rd) = std::fs::read_dir(path) {
|
||||||
for entry in rd.flatten() {
|
for entry in rd.flatten() {
|
||||||
if let Ok(meta) = entry.metadata()
|
if let Ok(meta) = entry.metadata()
|
||||||
&& meta.is_file() {
|
&& meta.is_file()
|
||||||
|
{
|
||||||
total += meta.len();
|
total += meta.len();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -128,73 +135,3 @@ fn format_size(bytes: u64) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
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"]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+16
-22
@@ -14,13 +14,13 @@ pub fn desktop_path(name: &str) -> Option<PathBuf> {
|
|||||||
{
|
{
|
||||||
dirs_next::data_dir().map(|d| {
|
dirs_next::data_dir().map(|d| {
|
||||||
d.join("applications")
|
d.join("applications")
|
||||||
.join(format!("mcl-{sanitized}.desktop"))
|
.join(format!("rmcl-{sanitized}.desktop"))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[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")]
|
||||||
@@ -36,7 +36,7 @@ pub fn desktop_path(name: &str) -> Option<PathBuf> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn icon_path() -> Option<PathBuf> {
|
pub fn icon_path() -> Option<PathBuf> {
|
||||||
dirs_next::data_dir().map(|d| d.join("mcl").join("icon.svg"))
|
dirs_next::data_dir().map(|d| d.join("rmcl").join("icon.svg"))
|
||||||
}
|
}
|
||||||
|
|
||||||
// lazily writes the bundled svg icon to disk the first time a shortcut needs it
|
// lazily writes the bundled svg icon to disk the first time a shortcut needs it
|
||||||
@@ -141,26 +141,29 @@ 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"));
|
||||||
out.push_str(&format!("Exec=mcl instance launch \"{name}\"\n"));
|
out.push_str(&format!("Exec=rmcl instance launch \"{name}\"\n"));
|
||||||
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!("mcl instance launch \"{name}\"\r\n"));
|
"shell.Run \"rmcl instance launch \"\"{}\"\"\", 0, False\r\n",
|
||||||
out.push_str("pause\r\n");
|
escaped_name
|
||||||
|
));
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,7 +172,7 @@ fn build_macos_command(name: &str) -> String {
|
|||||||
let mut out = String::new();
|
let mut out = String::new();
|
||||||
out.push_str("#!/bin/bash\n");
|
out.push_str("#!/bin/bash\n");
|
||||||
out.push_str(&format!("# Launch Minecraft instance: {name}\n"));
|
out.push_str(&format!("# Launch Minecraft instance: {name}\n"));
|
||||||
out.push_str(&format!("mcl instance launch \"{name}\"\n"));
|
out.push_str(&format!("rmcl instance launch \"{name}\"\n"));
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -201,22 +204,13 @@ mod tests {
|
|||||||
assert_eq!(sanitize("path/traversal"), "path_traversal");
|
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]
|
#[test]
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
fn build_content_linux() {
|
fn build_content_linux() {
|
||||||
let content = build_content("TestPack", None);
|
let content = build_content("TestPack", None);
|
||||||
assert!(content.contains("Name=Minecraft - TestPack"));
|
assert!(content.contains("Name=Minecraft - TestPack"));
|
||||||
assert!(content.contains("Exec=mcl instance launch \"TestPack\""));
|
assert!(content.contains("Exec=rmcl instance launch \"TestPack\""));
|
||||||
assert!(content.contains("Terminal=true"));
|
assert!(content.contains("Terminal=false"));
|
||||||
assert!(content.contains("Categories=Game;"));
|
assert!(content.contains("Categories=Game;"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,320 @@
|
|||||||
|
// multimc / prism launcher instance import: mods and configs are bundled
|
||||||
|
// in the zip. we install the game + loader normally, then extract the
|
||||||
|
// archive contents over it.
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use crate::instance::manager::InstanceManager;
|
||||||
|
use crate::instance::models::ModLoader;
|
||||||
|
use crate::tui::progress;
|
||||||
|
|
||||||
|
use super::{ImportSummary, PackFormat};
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
struct MmcPack {
|
||||||
|
#[serde(default)]
|
||||||
|
components: Vec<MmcComponent>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
struct MmcComponent {
|
||||||
|
uid: String,
|
||||||
|
#[serde(default)]
|
||||||
|
version: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MmcPack {
|
||||||
|
fn game_version(&self) -> Option<String> {
|
||||||
|
self.components
|
||||||
|
.iter()
|
||||||
|
.find(|c| c.uid == "net.minecraft")
|
||||||
|
.map(|c| c.version.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn loader(&self) -> (Option<ModLoader>, Option<String>) {
|
||||||
|
let loaders = [
|
||||||
|
("net.fabricmc.fabric-loader", ModLoader::Fabric),
|
||||||
|
("net.minecraftforge", ModLoader::Forge),
|
||||||
|
("net.neoforged", ModLoader::NeoForge),
|
||||||
|
("org.quiltmc.quilt-loader", ModLoader::Quilt),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (uid, loader) in &loaders {
|
||||||
|
if let Some(component) = self.components.iter().find(|c| c.uid == *uid) {
|
||||||
|
return (Some(*loader), Some(component.version.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(None, None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||||
|
let pack = parse_mmc_pack(path)?;
|
||||||
|
|
||||||
|
let game_version = pack
|
||||||
|
.game_version()
|
||||||
|
.ok_or_else(|| "mmc-pack.json missing net.minecraft component".to_string())?;
|
||||||
|
|
||||||
|
let (loader_opt, loader_version) = pack.loader();
|
||||||
|
let loader = loader_opt.unwrap_or(ModLoader::Vanilla);
|
||||||
|
|
||||||
|
let name = instance_name_from_cfg(path).unwrap_or_else(|| "Imported Pack".to_string());
|
||||||
|
|
||||||
|
let (mod_count, override_count) = count_content_files(path)?;
|
||||||
|
|
||||||
|
Ok(ImportSummary {
|
||||||
|
name,
|
||||||
|
pack_version: String::new(),
|
||||||
|
game_version,
|
||||||
|
loader,
|
||||||
|
loader_version,
|
||||||
|
mod_count,
|
||||||
|
override_count,
|
||||||
|
format: PackFormat::Mmc,
|
||||||
|
archive_path: path.to_path_buf(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn execute_import(
|
||||||
|
summary: &ImportSummary,
|
||||||
|
manager: &InstanceManager,
|
||||||
|
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let name = super::unique_instance_name(&summary.name, &manager.instances_dir);
|
||||||
|
|
||||||
|
progress::set_action(format!("Importing '{name}'..."));
|
||||||
|
progress::set_sub_action(format!("{} {}", summary.game_version, summary.loader));
|
||||||
|
|
||||||
|
let config = manager
|
||||||
|
.create(
|
||||||
|
&name,
|
||||||
|
&summary.game_version,
|
||||||
|
summary.loader,
|
||||||
|
summary.loader_version.as_deref(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?;
|
||||||
|
|
||||||
|
let minecraft_dir = manager.instances_dir.join(&name).join(".minecraft");
|
||||||
|
extract_mmc_archive(&summary.archive_path, &minecraft_dir)?;
|
||||||
|
|
||||||
|
progress::clear();
|
||||||
|
Ok(config)
|
||||||
|
}
|
||||||
|
|
||||||
|
// extracts everything under .minecraft/ from the archive into the instance dir
|
||||||
|
fn extract_mmc_archive(
|
||||||
|
archive_path: &Path,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
use std::io::Read;
|
||||||
|
|
||||||
|
progress::set_action("Extracting pack contents...".to_string());
|
||||||
|
progress::set_sub_action(String::new());
|
||||||
|
|
||||||
|
let file = std::fs::File::open(archive_path)?;
|
||||||
|
let mut archive = zip::ZipArchive::new(file)?;
|
||||||
|
|
||||||
|
let prefix = find_archive_prefix(&archive);
|
||||||
|
let minecraft_prefix = format!("{prefix}.minecraft/");
|
||||||
|
|
||||||
|
let total = archive.len();
|
||||||
|
for i in 0..total {
|
||||||
|
let mut entry = archive.by_index(i)?;
|
||||||
|
let entry_name = entry.name().to_string();
|
||||||
|
|
||||||
|
let Some(relative) = entry_name.strip_prefix(&minecraft_prefix) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
if relative.is_empty() || entry_name.ends_with('/') {
|
||||||
|
std::fs::create_dir_all(minecraft_dir.join(relative))?;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let dest = minecraft_dir.join(relative);
|
||||||
|
if let Some(parent) = dest.parent() {
|
||||||
|
std::fs::create_dir_all(parent)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let filename = relative.rsplit('/').next().unwrap_or(relative);
|
||||||
|
progress::set_sub_action(filename.to_string());
|
||||||
|
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
entry.read_to_end(&mut buf)?;
|
||||||
|
std::fs::write(&dest, &buf)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_mmc_pack(path: &Path) -> Result<MmcPack, String> {
|
||||||
|
let file = std::fs::File::open(path).map_err(|e| format!("Cannot open archive: {e}"))?;
|
||||||
|
let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("Invalid ZIP: {e}"))?;
|
||||||
|
|
||||||
|
let entry_name = find_entry(&archive, "mmc-pack.json")
|
||||||
|
.ok_or_else(|| "Missing mmc-pack.json in archive".to_string())?;
|
||||||
|
|
||||||
|
let entry = archive
|
||||||
|
.by_name(&entry_name)
|
||||||
|
.map_err(|e| format!("Failed to read mmc-pack.json: {e}"))?;
|
||||||
|
|
||||||
|
serde_json::from_reader(entry).map_err(|e| format!("Invalid mmc-pack.json: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn instance_name_from_cfg(path: &Path) -> Option<String> {
|
||||||
|
let file = std::fs::File::open(path).ok()?;
|
||||||
|
let mut archive = zip::ZipArchive::new(file).ok()?;
|
||||||
|
|
||||||
|
let entry_name = find_entry(&archive, "instance.cfg")?;
|
||||||
|
let entry = archive.by_name(&entry_name).ok()?;
|
||||||
|
|
||||||
|
let reader = std::io::BufRead::lines(std::io::BufReader::new(entry));
|
||||||
|
for line in reader.map_while(Result::ok) {
|
||||||
|
if let Some(value) = line.strip_prefix("name=") {
|
||||||
|
let name = value.trim().to_string();
|
||||||
|
if !name.is_empty() {
|
||||||
|
return Some(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
// finds the prefix for the archive: empty for flat zips, "DirName/" for nested
|
||||||
|
fn find_archive_prefix(archive: &zip::ZipArchive<std::fs::File>) -> String {
|
||||||
|
for name in archive.file_names() {
|
||||||
|
if name.ends_with("mmc-pack.json") {
|
||||||
|
return name.strip_suffix("mmc-pack.json").unwrap_or("").to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String::new()
|
||||||
|
}
|
||||||
|
|
||||||
|
// looks for a file at root or one level deep (some archives nest everything
|
||||||
|
// under a single top-level directory like "GT New Horizons 2.8.4/")
|
||||||
|
fn find_entry(archive: &zip::ZipArchive<std::fs::File>, filename: &str) -> Option<String> {
|
||||||
|
if archive.file_names().any(|n| n == filename) {
|
||||||
|
return Some(filename.to_string());
|
||||||
|
}
|
||||||
|
for name in archive.file_names() {
|
||||||
|
if name.ends_with(&format!("/{filename}")) && name.matches('/').count() == 1 {
|
||||||
|
return Some(name.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
fn count_content_files(path: &Path) -> Result<(usize, usize), String> {
|
||||||
|
let file = std::fs::File::open(path).map_err(|e| e.to_string())?;
|
||||||
|
let archive = zip::ZipArchive::new(file).map_err(|e| e.to_string())?;
|
||||||
|
let prefix = find_archive_prefix(&archive);
|
||||||
|
|
||||||
|
let minecraft_prefix = format!("{prefix}.minecraft/");
|
||||||
|
let mods_prefix = format!("{prefix}.minecraft/mods/");
|
||||||
|
|
||||||
|
let mut mod_count = 0;
|
||||||
|
let mut override_count = 0;
|
||||||
|
|
||||||
|
for name in archive.file_names() {
|
||||||
|
if name.ends_with('/') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if name.starts_with(&mods_prefix) {
|
||||||
|
mod_count += 1;
|
||||||
|
} else if name.starts_with(&minecraft_prefix) {
|
||||||
|
override_count += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok((mod_count, override_count))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[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());
|
||||||
|
}
|
||||||
|
|
||||||
|
// builds an in-memory mmc-style pack zip and verifies that
|
||||||
|
// extract_mmc_archive copies only the .minecraft/ subtree into the
|
||||||
|
// destination, preserving relative paths and skipping siblings.
|
||||||
|
#[test]
|
||||||
|
fn extract_mmc_archive_copies_minecraft_subtree() {
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let archive_path = tmp.path().join("pack.zip");
|
||||||
|
let dest = tmp.path().join("instance/.minecraft");
|
||||||
|
std::fs::create_dir_all(&dest).unwrap();
|
||||||
|
|
||||||
|
// Pack/ is the prefix; only .minecraft/ entries should land in dest.
|
||||||
|
// mmc-style pack: a root dir "Pack/" wrapping the .minecraft tree
|
||||||
|
// plus a sibling mmc-pack.json that should NOT be extracted.
|
||||||
|
{
|
||||||
|
let file = std::fs::File::create(&archive_path).unwrap();
|
||||||
|
let mut zip = zip::ZipWriter::new(file);
|
||||||
|
let opts: zip::write::SimpleFileOptions = Default::default();
|
||||||
|
|
||||||
|
zip.start_file("Pack/mmc-pack.json", opts).unwrap();
|
||||||
|
zip.write_all(b"{}").unwrap();
|
||||||
|
|
||||||
|
zip.start_file("Pack/.minecraft/options.txt", opts).unwrap();
|
||||||
|
zip.write_all(b"lang:en_us").unwrap();
|
||||||
|
|
||||||
|
zip.start_file("Pack/.minecraft/mods/test-mod.jar", opts)
|
||||||
|
.unwrap();
|
||||||
|
zip.write_all(b"jar-bytes").unwrap();
|
||||||
|
|
||||||
|
zip.finish().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
extract_mmc_archive(&archive_path, &dest).expect("extract");
|
||||||
|
|
||||||
|
// .minecraft/ entries must have been copied with their relative paths
|
||||||
|
let options = std::fs::read(dest.join("options.txt")).expect("options.txt");
|
||||||
|
assert_eq!(options, b"lang:en_us");
|
||||||
|
let modjar = std::fs::read(dest.join("mods/test-mod.jar")).expect("mods/test-mod.jar");
|
||||||
|
assert_eq!(modjar, b"jar-bytes");
|
||||||
|
|
||||||
|
// and the sibling outside .minecraft/ must not have been copied
|
||||||
|
assert!(
|
||||||
|
!dest.join("mmc-pack.json").exists(),
|
||||||
|
"mmc-pack.json should not land in the instance dir"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,307 @@
|
|||||||
|
// modpack importing: parses user input, detects pack format from zip contents,
|
||||||
|
// builds a summary, and delegates the actual import to format-specific modules.
|
||||||
|
|
||||||
|
pub mod mmc;
|
||||||
|
pub mod mrpack;
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use crate::instance::manager::InstanceManager;
|
||||||
|
use crate::instance::models::ModLoader;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum PackFormat {
|
||||||
|
Mrpack,
|
||||||
|
Mmc,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub enum ImportInput {
|
||||||
|
ProjectSlug(String),
|
||||||
|
VersionId { slug: String, version_id: String },
|
||||||
|
LocalFile(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
// figures out what the user gave us: a modrinth URL, a local pack file,
|
||||||
|
// or just a project slug. accepts a pretty wide range of inputs so users
|
||||||
|
// don't have to think about it.
|
||||||
|
pub fn parse_import_input(input: &str) -> ImportInput {
|
||||||
|
let input = input.trim();
|
||||||
|
|
||||||
|
if input.ends_with(".mrpack")
|
||||||
|
|| input.ends_with(".zip")
|
||||||
|
|| input.starts_with('/')
|
||||||
|
|| input.starts_with("~/")
|
||||||
|
{
|
||||||
|
return ImportInput::LocalFile(input.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(rest) = input
|
||||||
|
.strip_prefix("https://modrinth.com/modpack/")
|
||||||
|
.or_else(|| input.strip_prefix("http://modrinth.com/modpack/"))
|
||||||
|
{
|
||||||
|
let parts: Vec<&str> = rest.split('/').filter(|s| !s.is_empty()).collect();
|
||||||
|
return match parts.as_slice() {
|
||||||
|
[slug, "version", version_id, ..] => ImportInput::VersionId {
|
||||||
|
slug: slug.to_string(),
|
||||||
|
version_id: version_id.to_string(),
|
||||||
|
},
|
||||||
|
[slug, ..] => ImportInput::ProjectSlug(slug.to_string()),
|
||||||
|
[] => ImportInput::ProjectSlug(String::new()),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
ImportInput::ProjectSlug(input.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ImportSummary {
|
||||||
|
pub name: String,
|
||||||
|
pub pack_version: String,
|
||||||
|
pub game_version: String,
|
||||||
|
pub loader: ModLoader,
|
||||||
|
pub loader_version: Option<String>,
|
||||||
|
pub mod_count: usize,
|
||||||
|
pub override_count: usize,
|
||||||
|
pub format: PackFormat,
|
||||||
|
pub archive_path: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
// peeks inside a zip to figure out what format it is.
|
||||||
|
// checks for modrinth.index.json first, then mmc-pack.json.
|
||||||
|
pub fn detect_format(path: &Path) -> Result<PackFormat, String> {
|
||||||
|
let file =
|
||||||
|
std::fs::File::open(path).map_err(|e| format!("Cannot open '{}': {e}", path.display()))?;
|
||||||
|
let archive =
|
||||||
|
zip::ZipArchive::new(file).map_err(|e| format!("Invalid ZIP '{}': {e}", path.display()))?;
|
||||||
|
|
||||||
|
if archive.file_names().any(|n| n == "modrinth.index.json") {
|
||||||
|
return Ok(PackFormat::Mrpack);
|
||||||
|
}
|
||||||
|
|
||||||
|
// mmc-pack.json can be at root or one directory deep
|
||||||
|
if archive
|
||||||
|
.file_names()
|
||||||
|
.any(|n| n == "mmc-pack.json" || n.ends_with("/mmc-pack.json"))
|
||||||
|
{
|
||||||
|
return Ok(PackFormat::Mmc);
|
||||||
|
}
|
||||||
|
|
||||||
|
Err("Unknown pack format: no modrinth.index.json or mmc-pack.json found".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||||
|
if !path.exists() {
|
||||||
|
return Err(format!("File not found: {}", path.display()));
|
||||||
|
}
|
||||||
|
let format = detect_format(path)?;
|
||||||
|
match format {
|
||||||
|
PackFormat::Mrpack => mrpack::build_summary(path),
|
||||||
|
PackFormat::Mmc => mmc::build_summary(path),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
|
||||||
|
let candidate = base.to_string();
|
||||||
|
if !instances_dir
|
||||||
|
.join(&candidate)
|
||||||
|
.join("instance.json")
|
||||||
|
.exists()
|
||||||
|
{
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
for n in 2..100 {
|
||||||
|
let candidate = format!("{base} ({n})");
|
||||||
|
if !instances_dir
|
||||||
|
.join(&candidate)
|
||||||
|
.join("instance.json")
|
||||||
|
.exists()
|
||||||
|
{
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
format!("{base} (import)")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn execute_import(
|
||||||
|
summary: &ImportSummary,
|
||||||
|
manager: &InstanceManager,
|
||||||
|
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
match summary.format {
|
||||||
|
PackFormat::Mrpack => mrpack::execute_import(summary, manager).await,
|
||||||
|
PackFormat::Mmc => mmc::execute_import(summary, manager).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
fn make_pack_zip(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> std::path::PathBuf {
|
||||||
|
let path = tmp.join(name);
|
||||||
|
let file = std::fs::File::create(&path).unwrap();
|
||||||
|
let mut zip = zip::ZipWriter::new(file);
|
||||||
|
let opts: zip::write::SimpleFileOptions = Default::default();
|
||||||
|
for (filename, bytes) in entries {
|
||||||
|
zip.start_file(*filename, opts).unwrap();
|
||||||
|
zip.write_all(bytes).unwrap();
|
||||||
|
}
|
||||||
|
zip.finish().unwrap();
|
||||||
|
path
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn detect_format_recognises_mrpack() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let path = make_pack_zip(
|
||||||
|
tmp.path(),
|
||||||
|
"pack.mrpack",
|
||||||
|
&[("modrinth.index.json", b"{}")],
|
||||||
|
);
|
||||||
|
assert_eq!(detect_format(&path), Ok(PackFormat::Mrpack));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn detect_format_recognises_mmc_flat() {
|
||||||
|
// mmc-pack.json at the zip root - the flat layout that some mmc
|
||||||
|
// archives use.
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let path = make_pack_zip(tmp.path(), "pack.zip", &[("mmc-pack.json", b"{}")]);
|
||||||
|
assert_eq!(detect_format(&path), Ok(PackFormat::Mmc));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn detect_format_recognises_mmc_nested() {
|
||||||
|
// mmc-pack.json one directory deep - the more common layout where
|
||||||
|
// the archive wraps everything in a named directory.
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let path = make_pack_zip(
|
||||||
|
tmp.path(),
|
||||||
|
"pack.zip",
|
||||||
|
&[("MyPack/mmc-pack.json", b"{}")],
|
||||||
|
);
|
||||||
|
assert_eq!(detect_format(&path), Ok(PackFormat::Mmc));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn detect_format_prefers_mrpack_when_both_markers_present() {
|
||||||
|
// a zip with both markers should resolve to Mrpack since the
|
||||||
|
// detector checks modrinth.index.json first.
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let path = make_pack_zip(
|
||||||
|
tmp.path(),
|
||||||
|
"weird.zip",
|
||||||
|
&[
|
||||||
|
("modrinth.index.json", b"{}"),
|
||||||
|
("mmc-pack.json", b"{}"),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
assert_eq!(detect_format(&path), Ok(PackFormat::Mrpack));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn detect_format_errors_on_unknown_archive() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let path = make_pack_zip(tmp.path(), "random.zip", &[("readme.txt", b"hello")]);
|
||||||
|
let err = detect_format(&path).unwrap_err();
|
||||||
|
assert!(
|
||||||
|
err.contains("Unknown pack format"),
|
||||||
|
"expected unknown format error, got: {err}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn detect_format_errors_on_missing_file() {
|
||||||
|
let err = detect_format(Path::new("/nonexistent/pack.zip")).unwrap_err();
|
||||||
|
assert!(err.contains("Cannot open"), "got: {err}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,26 +1,18 @@
|
|||||||
// importing modrinth .mrpack modpacks: parse the manifest, create the instance,
|
// modrinth .mrpack import: parse the manifest, download all the mods,
|
||||||
// download all the mods, and extract config/resource overrides from the zip
|
// and extract config/resource overrides from the zip
|
||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::Path;
|
||||||
|
|
||||||
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::net::modrinth::MrpackIndex;
|
||||||
use crate::tui::progress;
|
use crate::tui::progress;
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
use super::{ImportSummary, PackFormat};
|
||||||
pub struct ImportSummary {
|
|
||||||
pub name: String,
|
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||||
pub pack_version: String,
|
let index = crate::net::modrinth::parse_mrpack(path)?;
|
||||||
pub game_version: String,
|
|
||||||
pub loader: ModLoader,
|
|
||||||
pub loader_version: Option<String>,
|
|
||||||
pub mod_count: usize,
|
|
||||||
pub override_count: usize,
|
|
||||||
pub mrpack_path: PathBuf,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn build_summary(index: &MrpackIndex, mrpack_path: PathBuf) -> Result<ImportSummary, String> {
|
|
||||||
let game_version = crate::net::modrinth::game_version_from_dependencies(&index.dependencies)
|
let game_version = crate::net::modrinth::game_version_from_dependencies(&index.dependencies)
|
||||||
.ok_or_else(|| "Manifest missing minecraft dependency".to_string())?;
|
.ok_or_else(|| "Manifest missing minecraft dependency".to_string())?;
|
||||||
|
|
||||||
@@ -28,7 +20,7 @@ pub fn build_summary(index: &MrpackIndex, mrpack_path: PathBuf) -> Result<Import
|
|||||||
crate::net::modrinth::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(&mrpack_path).unwrap_or(0);
|
let override_count = count_overrides(path).unwrap_or(0);
|
||||||
|
|
||||||
Ok(ImportSummary {
|
Ok(ImportSummary {
|
||||||
name: index.name.clone(),
|
name: index.name.clone(),
|
||||||
@@ -38,7 +30,8 @@ pub fn build_summary(index: &MrpackIndex, mrpack_path: PathBuf) -> Result<Import
|
|||||||
loader_version,
|
loader_version,
|
||||||
mod_count: index.files.len(),
|
mod_count: index.files.len(),
|
||||||
override_count,
|
override_count,
|
||||||
mrpack_path,
|
format: PackFormat::Mrpack,
|
||||||
|
archive_path: path.to_path_buf(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,25 +49,11 @@ fn count_overrides(mrpack_path: &Path) -> Result<usize, String> {
|
|||||||
Ok(count)
|
Ok(count)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String {
|
|
||||||
let candidate = base.to_string();
|
|
||||||
if !instances_dir.join(&candidate).join("instance.json").exists() {
|
|
||||||
return candidate;
|
|
||||||
}
|
|
||||||
for n in 2..100 {
|
|
||||||
let candidate = format!("{base} ({n})");
|
|
||||||
if !instances_dir.join(&candidate).join("instance.json").exists() {
|
|
||||||
return candidate;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
format!("{base} (import)")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn execute_import(
|
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>> {
|
||||||
let name = unique_instance_name(&summary.name, &manager.instances_dir);
|
let name = super::unique_instance_name(&summary.name, &manager.instances_dir);
|
||||||
|
|
||||||
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));
|
||||||
@@ -91,12 +70,12 @@ pub async fn execute_import(
|
|||||||
|
|
||||||
let minecraft_dir = manager.instances_dir.join(&name).join(".minecraft");
|
let minecraft_dir = manager.instances_dir.join(&name).join(".minecraft");
|
||||||
|
|
||||||
let index = crate::net::modrinth::parse_mrpack(&summary.mrpack_path)
|
let index = crate::net::modrinth::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.mrpack_path, &minecraft_dir)?;
|
extract_overrides(&summary.archive_path, &minecraft_dir)?;
|
||||||
|
|
||||||
progress::clear();
|
progress::clear();
|
||||||
Ok(config)
|
Ok(config)
|
||||||
@@ -108,8 +87,8 @@ async fn download_mod_files(
|
|||||||
index: &MrpackIndex,
|
index: &MrpackIndex,
|
||||||
minecraft_dir: &Path,
|
minecraft_dir: &Path,
|
||||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
|
||||||
let client = crate::net::HttpClient::new();
|
let client = crate::net::HttpClient::new();
|
||||||
let total = index.files.len();
|
let total = index.files.len();
|
||||||
@@ -227,37 +206,3 @@ fn extract_overrides(
|
|||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[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)");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,396 +0,0 @@
|
|||||||
// builds the full java command line and spawns minecraft as a child process.
|
|
||||||
// handles classpath assembly, auth token injection, and log capture.
|
|
||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
|
|
||||||
use thiserror::Error;
|
|
||||||
|
|
||||||
use crate::instance::models::{InstanceConfig, ModLoader};
|
|
||||||
|
|
||||||
#[derive(Debug, Error)]
|
|
||||||
pub enum LaunchError {
|
|
||||||
#[error("Version metadata not found: {0}. Re-create the instance to fix this.")]
|
|
||||||
MetaNotFound(String),
|
|
||||||
#[error("IO error: {0}")]
|
|
||||||
Io(#[from] std::io::Error),
|
|
||||||
#[error("JSON error: {0}")]
|
|
||||||
Json(#[from] serde_json::Error),
|
|
||||||
#[error("{0} launch is not yet supported")]
|
|
||||||
NotSupported(String),
|
|
||||||
#[error("{0}")]
|
|
||||||
Auth(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
// subset of mojang's version meta json, only the bits relevant to launching
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
struct MetaJson {
|
|
||||||
main_class: String,
|
|
||||||
asset_index: MetaAssetIndex,
|
|
||||||
libraries: Vec<MetaLibrary>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
struct MetaAssetIndex {
|
|
||||||
id: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
struct MetaLibrary {
|
|
||||||
downloads: Option<MetaLibraryDownloads>,
|
|
||||||
rules: Option<Vec<MetaRule>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
struct MetaLibraryDownloads {
|
|
||||||
artifact: Option<MetaArtifact>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
struct MetaArtifact {
|
|
||||||
path: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
struct MetaRule {
|
|
||||||
action: String,
|
|
||||||
os: Option<MetaOsRule>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
struct MetaOsRule {
|
|
||||||
name: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
struct LoaderProfileJson {
|
|
||||||
main_class: String,
|
|
||||||
libraries: Vec<LoaderLibrary>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
struct LoaderLibrary {
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
// mojang's library rules are a fun little state machine: each rule can allow
|
|
||||||
// or disallow based on OS. if no rule matches the current OS, the library is
|
|
||||||
// included only if no rule "dominated" (matched at all). yes, it's weird.
|
|
||||||
fn lib_allowed(lib: &MetaLibrary) -> bool {
|
|
||||||
let Some(rules) = &lib.rules else {
|
|
||||||
return true;
|
|
||||||
};
|
|
||||||
let current_os = match std::env::consts::OS {
|
|
||||||
"macos" => "osx",
|
|
||||||
other => other,
|
|
||||||
};
|
|
||||||
let mut dominated = false;
|
|
||||||
for rule in rules {
|
|
||||||
let matches_os = rule
|
|
||||||
.os
|
|
||||||
.as_ref()
|
|
||||||
.and_then(|os| os.name.as_deref())
|
|
||||||
.is_none_or(|n| n == current_os);
|
|
||||||
if !matches_os {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
dominated = true;
|
|
||||||
match rule.action.as_str() {
|
|
||||||
"disallow" => return false,
|
|
||||||
"allow" => return true,
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
!dominated
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn launch(
|
|
||||||
config: &InstanceConfig,
|
|
||||||
instances_dir: &Path,
|
|
||||||
meta_dir: &Path,
|
|
||||||
) -> Result<(), LaunchError> {
|
|
||||||
let name = config.name.clone();
|
|
||||||
let instance_dir = instances_dir.join(&name);
|
|
||||||
let minecraft_dir = instance_dir.join(".minecraft");
|
|
||||||
|
|
||||||
let meta_path = meta_dir
|
|
||||||
.join("versions")
|
|
||||||
.join(&config.game_version)
|
|
||||||
.join("meta.json");
|
|
||||||
if !meta_path.exists() {
|
|
||||||
return Err(LaunchError::MetaNotFound(meta_path.display().to_string()));
|
|
||||||
}
|
|
||||||
let meta: MetaJson = serde_json::from_slice(&tokio::fs::read(&meta_path).await?)?;
|
|
||||||
|
|
||||||
let lib_dir = meta_dir.join("libraries");
|
|
||||||
let mut classpath: Vec<PathBuf> = meta
|
|
||||||
.libraries
|
|
||||||
.iter()
|
|
||||||
.filter(|l| lib_allowed(l))
|
|
||||||
.filter_map(|l| {
|
|
||||||
l.downloads
|
|
||||||
.as_ref()?
|
|
||||||
.artifact
|
|
||||||
.as_ref()
|
|
||||||
.map(|a| lib_dir.join(&a.path))
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
let lv = config.loader_version.as_deref().unwrap_or("unknown");
|
|
||||||
let profile_filename = match config.loader {
|
|
||||||
ModLoader::Vanilla => None,
|
|
||||||
ModLoader::Fabric => Some(format!("fabric-{}-{}.json", config.game_version, lv)),
|
|
||||||
ModLoader::Quilt => Some(format!("quilt-{}-{}.json", config.game_version, lv)),
|
|
||||||
ModLoader::Forge => Some(format!("forge-{}-{}.json", config.game_version, lv)),
|
|
||||||
ModLoader::NeoForge => Some(format!("neoforge-{}.json", lv)),
|
|
||||||
};
|
|
||||||
|
|
||||||
// if there's a mod loader, read its profile to get the real main class
|
|
||||||
// and extra libraries it needs on the classpath
|
|
||||||
let main_class = if let Some(filename) = profile_filename {
|
|
||||||
let profile_path = meta_dir.join("loader-profiles").join(&filename);
|
|
||||||
if !profile_path.exists() {
|
|
||||||
return Err(LaunchError::MetaNotFound(
|
|
||||||
profile_path.display().to_string(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
let profile: LoaderProfileJson =
|
|
||||||
serde_json::from_slice(&tokio::fs::read(&profile_path).await?)?;
|
|
||||||
|
|
||||||
// forge/neoforge install some libs locally in the instance dir, so
|
|
||||||
// both locations need to be checked
|
|
||||||
let has_local_libs = matches!(config.loader, ModLoader::Forge | ModLoader::NeoForge);
|
|
||||||
let local_lib_dir = minecraft_dir.join("libraries");
|
|
||||||
|
|
||||||
for lib in &profile.libraries {
|
|
||||||
if let Some(p) = crate::net::maven_coord_to_path(&lib.name) {
|
|
||||||
if has_local_libs {
|
|
||||||
let in_meta = lib_dir.join(&p);
|
|
||||||
let in_local = local_lib_dir.join(&p);
|
|
||||||
if in_meta.exists() {
|
|
||||||
classpath.push(in_meta);
|
|
||||||
} else if in_local.exists() {
|
|
||||||
classpath.push(in_local);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
classpath.push(lib_dir.join(p));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
profile.main_class
|
|
||||||
} else {
|
|
||||||
meta.main_class.clone()
|
|
||||||
};
|
|
||||||
|
|
||||||
classpath.push(
|
|
||||||
meta_dir
|
|
||||||
.join("versions")
|
|
||||||
.join(&config.game_version)
|
|
||||||
.join(format!("{}.jar", config.game_version)),
|
|
||||||
);
|
|
||||||
|
|
||||||
let sep = if cfg!(windows) { ";" } else { ":" };
|
|
||||||
let cp_str = classpath
|
|
||||||
.iter()
|
|
||||||
.map(|p| p.to_string_lossy().into_owned())
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join(sep);
|
|
||||||
|
|
||||||
// java resolution: instance override > global setting > auto-detect
|
|
||||||
let java = config
|
|
||||||
.java_path
|
|
||||||
.clone()
|
|
||||||
.or_else(|| {
|
|
||||||
crate::config::SETTINGS
|
|
||||||
.paths
|
|
||||||
.effective_java_path()
|
|
||||||
.map(str::to_owned)
|
|
||||||
})
|
|
||||||
.unwrap_or_else(crate::net::detect_java_path);
|
|
||||||
|
|
||||||
let mut jvm: Vec<String> = vec![
|
|
||||||
format!("-Xms{}", config.memory_min.as_deref().unwrap_or("512M")),
|
|
||||||
format!("-Xmx{}", config.memory_max.as_deref().unwrap_or("2G")),
|
|
||||||
];
|
|
||||||
jvm.extend(config.jvm_args.clone());
|
|
||||||
|
|
||||||
// resolve auth credentials, refreshing the microsoft token if needed.
|
|
||||||
// falls back to a generic offline player if no account is configured.
|
|
||||||
let mut account_store = crate::auth::AccountStore::load();
|
|
||||||
let (mc_username, mc_uuid, mc_token, mc_user_type) = match account_store
|
|
||||||
.active_account()
|
|
||||||
.cloned()
|
|
||||||
{
|
|
||||||
Some(acc) => {
|
|
||||||
let (token, new_refresh) = match acc.account_type {
|
|
||||||
crate::auth::AccountType::Microsoft => {
|
|
||||||
match crate::auth::refresh_and_get_token(&acc).await {
|
|
||||||
Ok(pair) => pair,
|
|
||||||
Err(e) => {
|
|
||||||
return Err(LaunchError::Auth(format!("Authentication failed: {e}")));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
crate::auth::AccountType::Offline => ("0".to_string(), None),
|
|
||||||
};
|
|
||||||
if let Some(new_rt) = new_refresh
|
|
||||||
&& let Some(stored) = account_store
|
|
||||||
.accounts
|
|
||||||
.iter_mut()
|
|
||||||
.find(|a| a.uuid == acc.uuid)
|
|
||||||
{
|
|
||||||
stored.refresh_token = Some(new_rt);
|
|
||||||
account_store.save();
|
|
||||||
}
|
|
||||||
let user_type = match acc.account_type {
|
|
||||||
crate::auth::AccountType::Microsoft => "msa",
|
|
||||||
crate::auth::AccountType::Offline => "legacy",
|
|
||||||
};
|
|
||||||
(
|
|
||||||
acc.username.clone(),
|
|
||||||
acc.uuid.clone(),
|
|
||||||
token,
|
|
||||||
user_type.to_string(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
None => (
|
|
||||||
"Player".to_string(),
|
|
||||||
"00000000-0000-0000-0000-000000000000".to_string(),
|
|
||||||
"0".to_string(),
|
|
||||||
"legacy".to_string(),
|
|
||||||
),
|
|
||||||
};
|
|
||||||
|
|
||||||
let game_args = vec![
|
|
||||||
"--username".to_string(),
|
|
||||||
mc_username,
|
|
||||||
"--version".to_string(),
|
|
||||||
config.game_version.clone(),
|
|
||||||
"--gameDir".to_string(),
|
|
||||||
minecraft_dir.to_string_lossy().into_owned(),
|
|
||||||
"--assetsDir".to_string(),
|
|
||||||
meta_dir.join("assets").to_string_lossy().into_owned(),
|
|
||||||
"--assetIndex".to_string(),
|
|
||||||
meta.asset_index.id.clone(),
|
|
||||||
"--uuid".to_string(),
|
|
||||||
mc_uuid,
|
|
||||||
"--accessToken".to_string(),
|
|
||||||
mc_token,
|
|
||||||
"--userType".to_string(),
|
|
||||||
mc_user_type,
|
|
||||||
];
|
|
||||||
|
|
||||||
let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>();
|
|
||||||
crate::running::register_kill(&name, kill_tx);
|
|
||||||
crate::running::set_state(&name, crate::running::RunState::Starting);
|
|
||||||
tracing::info!(
|
|
||||||
"[{}] Starting Minecraft ({} {})",
|
|
||||||
name,
|
|
||||||
config.game_version,
|
|
||||||
config.loader
|
|
||||||
);
|
|
||||||
|
|
||||||
let mut cmd = tokio::process::Command::new(&java);
|
|
||||||
cmd.args(&jvm);
|
|
||||||
cmd.arg("-cp").arg(&cp_str);
|
|
||||||
cmd.arg(&main_class);
|
|
||||||
cmd.args(&game_args);
|
|
||||||
cmd.current_dir(&minecraft_dir);
|
|
||||||
cmd.stdout(std::process::Stdio::piped());
|
|
||||||
cmd.stderr(std::process::Stdio::piped());
|
|
||||||
|
|
||||||
let mut child = match cmd.spawn() {
|
|
||||||
Ok(c) => c,
|
|
||||||
Err(e) => {
|
|
||||||
crate::running::cleanup_kill_sender(&name);
|
|
||||||
crate::running::remove(&name);
|
|
||||||
return Err(LaunchError::Io(e));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
crate::running::set_state(&name, crate::running::RunState::Running);
|
|
||||||
|
|
||||||
let log_file_path = crate::instance::log_files::create_log_file(instances_dir, &name);
|
|
||||||
|
|
||||||
let name_for_task = name.clone();
|
|
||||||
let instances_dir_owned = instances_dir.to_path_buf();
|
|
||||||
let meta_dir_owned = meta_dir.to_path_buf();
|
|
||||||
|
|
||||||
// spawn a background task to babysit the child process: capture stdout/stderr
|
|
||||||
// into both the TUI log viewer and a timestamped log file on disk
|
|
||||||
tokio::spawn(async move {
|
|
||||||
use std::io::Write;
|
|
||||||
use std::sync::{Arc, Mutex};
|
|
||||||
use tokio::io::AsyncBufReadExt;
|
|
||||||
|
|
||||||
let log_writer: Arc<Mutex<Option<std::fs::File>>> = Arc::new(Mutex::new(
|
|
||||||
log_file_path.and_then(|p| std::fs::File::create(p).ok()),
|
|
||||||
));
|
|
||||||
|
|
||||||
if let Some(stdout) = child.stdout.take() {
|
|
||||||
let n = name_for_task.clone();
|
|
||||||
let w = log_writer.clone();
|
|
||||||
let mut lines = tokio::io::BufReader::new(stdout).lines();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
while let Ok(Some(line)) = lines.next_line().await {
|
|
||||||
tracing::info!(target: "mc_instance", "[{}] {}", n, line);
|
|
||||||
crate::instance_logs::push(&n, &line);
|
|
||||||
if let Ok(mut f) = w.lock()
|
|
||||||
&& let Some(f) = f.as_mut() {
|
|
||||||
let _ = writeln!(f, "{}", line);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(stderr) = child.stderr.take() {
|
|
||||||
let n = name_for_task.clone();
|
|
||||||
let w = log_writer.clone();
|
|
||||||
let mut lines = tokio::io::BufReader::new(stderr).lines();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
while let Ok(Some(line)) = lines.next_line().await {
|
|
||||||
tracing::warn!(target: "mc_instance", "[{}] {}", n, line);
|
|
||||||
crate::instance_logs::push(&n, &line);
|
|
||||||
if let Ok(mut f) = w.lock()
|
|
||||||
&& let Some(f) = f.as_mut() {
|
|
||||||
let _ = writeln!(f, "[STDERR] {}", line);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// wait for either the process to exit naturally or a kill signal from the TUI
|
|
||||||
let code = tokio::select! {
|
|
||||||
_ = kill_rx => {
|
|
||||||
tracing::info!("[{}] Kill requested, terminating process", name_for_task);
|
|
||||||
let _ = child.kill().await;
|
|
||||||
let _ = child.wait().await;
|
|
||||||
None
|
|
||||||
}
|
|
||||||
result = child.wait() => {
|
|
||||||
result.ok().and_then(|s| s.code())
|
|
||||||
}
|
|
||||||
};
|
|
||||||
tracing::info!("[{}] Exited with code {:?}", name_for_task, code);
|
|
||||||
|
|
||||||
if code == Some(0) {
|
|
||||||
crate::running::remove(&name_for_task);
|
|
||||||
} else {
|
|
||||||
crate::running::set_state(&name_for_task, crate::running::RunState::Crashed(code));
|
|
||||||
}
|
|
||||||
|
|
||||||
let manager = crate::instance::InstanceManager::new(instances_dir_owned, meta_dir_owned);
|
|
||||||
if let Err(e) = manager.touch_last_played(&name_for_task) {
|
|
||||||
tracing::warn!(
|
|
||||||
"Failed to update last_played for '{}': {}",
|
|
||||||
name_for_task,
|
|
||||||
e
|
|
||||||
);
|
|
||||||
}
|
|
||||||
crate::running::push_last_played(&name_for_task, chrono::Utc::now());
|
|
||||||
crate::running::cleanup_kill_sender(&name_for_task);
|
|
||||||
});
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,874 @@
|
|||||||
|
// builds the full java command line and spawns minecraft as a child process.
|
||||||
|
// handles classpath assembly, auth token injection, and log capture.
|
||||||
|
// loader-specific patches live in submodules (e.g. patches.rs for lwjgl3ify).
|
||||||
|
|
||||||
|
mod patches;
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use thiserror::Error;
|
||||||
|
|
||||||
|
use crate::auth::AccountType;
|
||||||
|
use crate::instance::models::{InstanceConfig, ModLoader};
|
||||||
|
use crate::launch_profile::model::LaunchProfile;
|
||||||
|
use crate::launch_profile::rules::{self, FeatureSet, RuleContext};
|
||||||
|
use crate::launch_profile::templates::TemplateContext;
|
||||||
|
use crate::launch_profile::{render, resolve, system};
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum LaunchError {
|
||||||
|
#[error("Version metadata not found: {0}. Re-create the instance to fix this.")]
|
||||||
|
MetaNotFound(String),
|
||||||
|
#[error("Profile error: {0}")]
|
||||||
|
Parse(String),
|
||||||
|
#[error("IO error: {0}")]
|
||||||
|
Io(#[from] std::io::Error),
|
||||||
|
#[error("JSON error: {0}")]
|
||||||
|
Json(#[from] serde_json::Error),
|
||||||
|
#[error("{0} launch is not yet supported")]
|
||||||
|
NotSupported(String),
|
||||||
|
#[error("{0}")]
|
||||||
|
Auth(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_game_args(
|
||||||
|
profile: &LaunchProfile,
|
||||||
|
rule_ctx: &RuleContext<'_>,
|
||||||
|
template_ctx: &TemplateContext<'_>,
|
||||||
|
) -> Result<(Vec<String>, Vec<String>), LaunchError> {
|
||||||
|
let rendered = render::render_args(profile, rule_ctx, template_ctx)
|
||||||
|
.map_err(|e| LaunchError::Parse(format!("Failed to render args: {e}")))?;
|
||||||
|
Ok((rendered.jvm, rendered.game))
|
||||||
|
}
|
||||||
|
|
||||||
|
// existing installs from rmcl <= 0.3.0 have meta.json files in the
|
||||||
|
// stripped legacy format (no `arguments`, no `minecraftArguments`). every
|
||||||
|
// real upstream profile has at least one of those fields. on detecting the
|
||||||
|
// stripped format, re-fetch the version metadata from mojang's manifest
|
||||||
|
// and overwrite the file with the raw upstream bytes.
|
||||||
|
async fn migrate_legacy_meta_if_needed(
|
||||||
|
meta_path: &Path,
|
||||||
|
profile: &LaunchProfile,
|
||||||
|
game_version: &str,
|
||||||
|
) -> Result<Option<LaunchProfile>, LaunchError> {
|
||||||
|
if profile.arguments.is_some() || profile.minecraft_arguments.is_some() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::warn!(
|
||||||
|
"Cached meta.json for {game_version} is missing arguments; re-fetching from Mojang"
|
||||||
|
);
|
||||||
|
|
||||||
|
let client = crate::net::HttpClient::new();
|
||||||
|
let manifest = match crate::net::mojang::fetch_version_manifest(&client).await {
|
||||||
|
Ok(m) => m,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(
|
||||||
|
"Could not reach Mojang manifest ({e}); proceeding with the cached legacy profile. \
|
||||||
|
Modern features like Forge's --add-opens flags may be missing until the next online launch."
|
||||||
|
);
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let entry = manifest
|
||||||
|
.versions
|
||||||
|
.iter()
|
||||||
|
.find(|v| v.id == game_version)
|
||||||
|
.ok_or_else(|| {
|
||||||
|
LaunchError::Parse(format!(
|
||||||
|
"Version {game_version} not found in Mojang manifest"
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let (_meta, raw) = match crate::net::mojang::fetch_version_meta_with_raw(&client, entry).await {
|
||||||
|
Ok(ok) => ok,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(
|
||||||
|
"Could not refetch version metadata from Mojang ({e}); proceeding with the cached legacy profile."
|
||||||
|
);
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
tokio::fs::write(meta_path, &raw).await?;
|
||||||
|
|
||||||
|
let refreshed: LaunchProfile = serde_json::from_slice(&raw)
|
||||||
|
.map_err(|e| LaunchError::Parse(format!("Failed to parse refreshed meta: {e}")))?;
|
||||||
|
Ok(Some(refreshed))
|
||||||
|
}
|
||||||
|
|
||||||
|
// the forge/neoforge installer writes its version JSON to a path that's
|
||||||
|
// loader-specific. encode the naming convention here so migration code
|
||||||
|
// can find the original file when it needs to rebuild our cache.
|
||||||
|
fn installer_version_dir_name(
|
||||||
|
loader: ModLoader,
|
||||||
|
game_version: &str,
|
||||||
|
loader_version: &str,
|
||||||
|
) -> Option<String> {
|
||||||
|
match loader {
|
||||||
|
ModLoader::Forge => Some(format!("{game_version}-forge-{loader_version}")),
|
||||||
|
ModLoader::NeoForge => Some(format!("neoforge-{loader_version}")),
|
||||||
|
ModLoader::Vanilla | ModLoader::Fabric | ModLoader::Quilt => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// loader profiles installed by rmcl <= 0.3.0 are in our stripped
|
||||||
|
// `{mainClass, libraries[, gameArguments]}` format, which silently drops
|
||||||
|
// `inheritsFrom`, `arguments.jvm`, and conditional rules from upstream.
|
||||||
|
// detect that shape (no inheritsFrom AND no arguments AND no
|
||||||
|
// minecraftArguments - every real upstream profile has at least one) and
|
||||||
|
// rebuild from the installer's original JSON if it's still on disk.
|
||||||
|
async fn migrate_legacy_loader_profile_if_needed(
|
||||||
|
profile_path: &Path,
|
||||||
|
profile: &LaunchProfile,
|
||||||
|
config: &InstanceConfig,
|
||||||
|
instance_dir: &Path,
|
||||||
|
) -> Result<Option<LaunchProfile>, LaunchError> {
|
||||||
|
// Fabric and Quilt fetch their profiles from a network endpoint at
|
||||||
|
// install time; there's no installer-written JSON on disk to recover
|
||||||
|
// from. their upstream profiles also happen to match the "legacy
|
||||||
|
// stripped" predicate (no inheritsFrom, no arguments), so without this
|
||||||
|
// early return every Fabric/Quilt launch would incorrectly fail
|
||||||
|
// migration. resolve() handles their lack of inheritsFrom via the
|
||||||
|
// implicit fallback in the launch flow.
|
||||||
|
if matches!(config.loader, ModLoader::Fabric | ModLoader::Quilt) {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
// tightened predicate per the spec: only treat a profile as "legacy
|
||||||
|
// stripped" when our old `gameArguments` field is present. that field
|
||||||
|
// is unique to rmcl <= 0.3.0's custom shape; no upstream profile
|
||||||
|
// emits it. without this gate, an upstream profile that happens to
|
||||||
|
// omit inheritsFrom/arguments/minecraftArguments would be mistakenly
|
||||||
|
// re-extracted from the installer JSON.
|
||||||
|
let is_legacy = profile.inherits_from.is_none()
|
||||||
|
&& profile.arguments.is_none()
|
||||||
|
&& profile.minecraft_arguments.is_none()
|
||||||
|
&& profile.game_arguments.is_some();
|
||||||
|
if !is_legacy {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some(loader_version) = config.loader_version.as_deref() else {
|
||||||
|
return Err(LaunchError::Parse(format!(
|
||||||
|
"Loader profile at {} is in an outdated format and the instance config has no \
|
||||||
|
loader_version recorded. Reinstall {} for this instance.",
|
||||||
|
profile_path.display(),
|
||||||
|
config.loader
|
||||||
|
)));
|
||||||
|
};
|
||||||
|
let Some(version_dir) =
|
||||||
|
installer_version_dir_name(config.loader, &config.game_version, loader_version)
|
||||||
|
else {
|
||||||
|
// unreachable today: only Vanilla/Fabric/Quilt return None, and
|
||||||
|
// Vanilla doesn't pass this code path (no loader profile to
|
||||||
|
// migrate) while Fabric/Quilt are filtered above.
|
||||||
|
return Err(LaunchError::Parse(format!(
|
||||||
|
"Loader profile at {} is in an outdated format. Reinstall {} for this instance.",
|
||||||
|
profile_path.display(),
|
||||||
|
config.loader
|
||||||
|
)));
|
||||||
|
};
|
||||||
|
|
||||||
|
let installer_json_path = instance_dir
|
||||||
|
.join(".minecraft")
|
||||||
|
.join("versions")
|
||||||
|
.join(&version_dir)
|
||||||
|
.join(format!("{version_dir}.json"));
|
||||||
|
|
||||||
|
if !installer_json_path.exists() {
|
||||||
|
return Err(LaunchError::Parse(format!(
|
||||||
|
"Loader profile at {} is in an outdated format and the installer JSON at {} \
|
||||||
|
is missing. Reinstall {} for this instance.",
|
||||||
|
profile_path.display(),
|
||||||
|
installer_json_path.display(),
|
||||||
|
config.loader
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::warn!(
|
||||||
|
"Loader profile {} is in legacy format; rebuilding from {}",
|
||||||
|
profile_path.display(),
|
||||||
|
installer_json_path.display()
|
||||||
|
);
|
||||||
|
|
||||||
|
let raw = tokio::fs::read(&installer_json_path).await?;
|
||||||
|
tokio::fs::write(profile_path, &raw).await?;
|
||||||
|
|
||||||
|
let refreshed: LaunchProfile = serde_json::from_slice(&raw).map_err(|e| {
|
||||||
|
LaunchError::Parse(format!("Failed to parse refreshed loader profile: {e}"))
|
||||||
|
})?;
|
||||||
|
Ok(Some(refreshed))
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolved auth credentials passed into the launch-invocation builder.
|
||||||
|
// keeping these as borrowed strs lets callers pass owned strings or string
|
||||||
|
// slices without forcing allocation.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct LaunchAuth<'a> {
|
||||||
|
pub username: &'a str,
|
||||||
|
pub uuid: &'a str,
|
||||||
|
pub token: &'a str,
|
||||||
|
// "msa" for Microsoft, "legacy" for offline; mirrors Mojang's user_type.
|
||||||
|
pub user_type: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
|
// everything the spawner needs to construct the java command. assembled by
|
||||||
|
// build_launch_invocation, consumed by launch(). exposed so integration tests
|
||||||
|
// can assert on the rendered invocation without spawning a real process.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct LaunchInvocation {
|
||||||
|
pub java: String,
|
||||||
|
pub jvm_args: Vec<String>,
|
||||||
|
pub classpath: Vec<PathBuf>,
|
||||||
|
pub classpath_string: String,
|
||||||
|
pub main_class: String,
|
||||||
|
pub extra_args: Vec<String>,
|
||||||
|
pub game_args: Vec<String>,
|
||||||
|
pub working_dir: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
// builds a fully-resolved java invocation for the given instance. reads
|
||||||
|
// meta.json and the loader profile from disk, migrates legacy formats if
|
||||||
|
// needed (may hit Mojang to refetch), resolves inheritsFrom, applies
|
||||||
|
// loader-specific patches, and renders all template arguments. all I/O
|
||||||
|
// except auth resolution and process spawning happens here.
|
||||||
|
pub async fn build_launch_invocation(
|
||||||
|
config: &InstanceConfig,
|
||||||
|
instances_dir: &Path,
|
||||||
|
meta_dir: &Path,
|
||||||
|
auth: &LaunchAuth<'_>,
|
||||||
|
) -> Result<LaunchInvocation, LaunchError> {
|
||||||
|
let instance_dir = instances_dir.join(&config.name);
|
||||||
|
let minecraft_dir = instance_dir.join(".minecraft");
|
||||||
|
|
||||||
|
let meta_path = meta_dir
|
||||||
|
.join("versions")
|
||||||
|
.join(&config.game_version)
|
||||||
|
.join("meta.json");
|
||||||
|
if !meta_path.exists() {
|
||||||
|
return Err(LaunchError::MetaNotFound(meta_path.display().to_string()));
|
||||||
|
}
|
||||||
|
let meta: LaunchProfile = serde_json::from_slice(&tokio::fs::read(&meta_path).await?)?;
|
||||||
|
let meta = match migrate_legacy_meta_if_needed(&meta_path, &meta, &config.game_version).await? {
|
||||||
|
Some(refreshed) => refreshed,
|
||||||
|
None => meta,
|
||||||
|
};
|
||||||
|
|
||||||
|
let current_features = FeatureSet::default();
|
||||||
|
let host_os_version = system::mojang_os_version();
|
||||||
|
let rule_ctx = RuleContext {
|
||||||
|
os_name: system::mojang_os_name(),
|
||||||
|
os_version: &host_os_version,
|
||||||
|
arch: system::mojang_arch_name(),
|
||||||
|
features: ¤t_features,
|
||||||
|
};
|
||||||
|
|
||||||
|
let asset_index_id = meta
|
||||||
|
.asset_index
|
||||||
|
.as_ref()
|
||||||
|
.map(|ai| ai.id.clone())
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let lib_dir = meta_dir.join("libraries");
|
||||||
|
|
||||||
|
let lv = config.loader_version.as_deref().unwrap_or("unknown");
|
||||||
|
let profile_filename = match config.loader {
|
||||||
|
ModLoader::Vanilla => None,
|
||||||
|
ModLoader::Fabric => Some(format!("fabric-{}-{}.json", config.game_version, lv)),
|
||||||
|
ModLoader::Quilt => Some(format!("quilt-{}-{}.json", config.game_version, lv)),
|
||||||
|
ModLoader::Forge => Some(format!("forge-{}-{}.json", config.game_version, lv)),
|
||||||
|
ModLoader::NeoForge => Some(format!("neoforge-{}.json", lv)),
|
||||||
|
};
|
||||||
|
|
||||||
|
// load the loader profile (if any), migrate from the old stripped format
|
||||||
|
// if needed, and resolve `inheritsFrom` against the vanilla parent (which
|
||||||
|
// the vanilla meta migration above ensured is fresh on disk). when no
|
||||||
|
// loader is configured we use the already-loaded vanilla meta directly.
|
||||||
|
let merged_profile: LaunchProfile = if let Some(filename) = &profile_filename {
|
||||||
|
let profile_path = meta_dir.join("loader-profiles").join(filename);
|
||||||
|
if !profile_path.exists() {
|
||||||
|
return Err(LaunchError::MetaNotFound(
|
||||||
|
profile_path.display().to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let mut loader_profile: LaunchProfile =
|
||||||
|
serde_json::from_slice(&tokio::fs::read(&profile_path).await?)?;
|
||||||
|
|
||||||
|
if let Some(refreshed) = migrate_legacy_loader_profile_if_needed(
|
||||||
|
&profile_path,
|
||||||
|
&loader_profile,
|
||||||
|
config,
|
||||||
|
&instance_dir,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
loader_profile = refreshed;
|
||||||
|
}
|
||||||
|
|
||||||
|
// legacy installer-written profiles (and any loader profile that
|
||||||
|
// omits inheritsFrom) still need to be layered over vanilla. set
|
||||||
|
// the inherit explicitly so resolve() walks the chain.
|
||||||
|
if loader_profile.inherits_from.is_none() {
|
||||||
|
loader_profile.inherits_from = Some(config.game_version.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
resolve::resolve(loader_profile, meta_dir)
|
||||||
|
.await
|
||||||
|
.map_err(|e| LaunchError::Parse(format!("Failed to resolve loader profile: {e}")))?
|
||||||
|
} else {
|
||||||
|
meta.clone()
|
||||||
|
};
|
||||||
|
|
||||||
|
let main_class = merged_profile
|
||||||
|
.main_class
|
||||||
|
.clone()
|
||||||
|
.ok_or_else(|| LaunchError::Parse("merged profile missing mainClass".into()))?;
|
||||||
|
|
||||||
|
// rebuild the classpath from the merged profile. vanilla-style libraries
|
||||||
|
// have `downloads.artifact.path` set and live in meta_dir/libraries/.
|
||||||
|
// loader-style libraries only have a maven coordinate; for forge/neoforge,
|
||||||
|
// the installer drops some of them into <instance>/.minecraft/libraries/
|
||||||
|
// so we check there first.
|
||||||
|
let has_local_libs = matches!(config.loader, ModLoader::Forge | ModLoader::NeoForge);
|
||||||
|
let local_lib_dir = minecraft_dir.join("libraries");
|
||||||
|
|
||||||
|
let mut classpath: Vec<PathBuf> = Vec::new();
|
||||||
|
for lib in &merged_profile.libraries {
|
||||||
|
if let Some(rules) = &lib.rules
|
||||||
|
&& !rules::evaluate(rules, &rule_ctx)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolve a relative path for this library. prefer downloads.artifact.path
|
||||||
|
// when present (vanilla-style), fall back to maven_coord_to_path(name)
|
||||||
|
// for loader-style entries that only have a coord.
|
||||||
|
let rel: PathBuf = match lib
|
||||||
|
.downloads
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|d| d.artifact.as_ref())
|
||||||
|
.map(|a| PathBuf::from(&a.path))
|
||||||
|
.or_else(|| crate::net::maven_coord_to_path(&lib.name).map(PathBuf::from))
|
||||||
|
{
|
||||||
|
Some(p) => p,
|
||||||
|
None => continue,
|
||||||
|
};
|
||||||
|
|
||||||
|
// for forge/neoforge, the installer drops some libs (notably the
|
||||||
|
// bootstrap library) into <instance>/.minecraft/libraries/ rather
|
||||||
|
// than the shared meta cache. check there first regardless of
|
||||||
|
// whether the lib has a downloads.artifact entry.
|
||||||
|
if has_local_libs {
|
||||||
|
let in_local = local_lib_dir.join(&rel);
|
||||||
|
if in_local.exists() {
|
||||||
|
classpath.push(in_local);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
classpath.push(lib_dir.join(rel));
|
||||||
|
}
|
||||||
|
|
||||||
|
classpath.push(
|
||||||
|
meta_dir
|
||||||
|
.join("versions")
|
||||||
|
.join(&config.game_version)
|
||||||
|
.join(format!("{}.jar", config.game_version)),
|
||||||
|
);
|
||||||
|
|
||||||
|
// apply loader-specific patches (lwjgl3ify for old forge on java 9+)
|
||||||
|
let (patch_jvm_args, main_class, extra_args) = if matches!(config.loader, ModLoader::Forge) {
|
||||||
|
match patches::apply(&minecraft_dir, &lib_dir, &mut classpath).await {
|
||||||
|
Some(p) => (p.jvm_args, p.main_class, p.extra_args),
|
||||||
|
None => (Vec::new(), main_class, Vec::new()),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
(Vec::new(), main_class, Vec::new())
|
||||||
|
};
|
||||||
|
|
||||||
|
let sep = if cfg!(windows) { ";" } else { ":" };
|
||||||
|
let cp_str = classpath
|
||||||
|
.iter()
|
||||||
|
.map(|p| p.to_string_lossy().into_owned())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(sep);
|
||||||
|
|
||||||
|
// java resolution: instance override > global setting > auto-detect
|
||||||
|
let java = config
|
||||||
|
.java_path
|
||||||
|
.clone()
|
||||||
|
.or_else(|| {
|
||||||
|
crate::config::SETTINGS
|
||||||
|
.paths
|
||||||
|
.effective_java_path()
|
||||||
|
.map(str::to_owned)
|
||||||
|
})
|
||||||
|
.unwrap_or_else(crate::net::detect_java_path);
|
||||||
|
|
||||||
|
let assets_root = meta_dir.join("assets");
|
||||||
|
let natives_dir = meta_dir
|
||||||
|
.join("versions")
|
||||||
|
.join(&config.game_version)
|
||||||
|
.join("natives");
|
||||||
|
let version_type = merged_profile.type_.as_deref().unwrap_or("release");
|
||||||
|
let template_ctx = TemplateContext {
|
||||||
|
library_directory: &lib_dir,
|
||||||
|
classpath_separator: sep,
|
||||||
|
version_name: &config.game_version,
|
||||||
|
version_type,
|
||||||
|
natives_directory: &natives_dir,
|
||||||
|
classpath: &cp_str,
|
||||||
|
game_directory: &minecraft_dir,
|
||||||
|
assets_root: &assets_root,
|
||||||
|
assets_index_name: &asset_index_id,
|
||||||
|
auth_player_name: auth.username,
|
||||||
|
auth_uuid: auth.uuid,
|
||||||
|
auth_access_token: auth.token,
|
||||||
|
auth_xuid: "0",
|
||||||
|
user_type: auth.user_type,
|
||||||
|
user_properties: "{}",
|
||||||
|
launcher_name: "rmcl",
|
||||||
|
launcher_version: env!("CARGO_PKG_VERSION"),
|
||||||
|
clientid: "0",
|
||||||
|
};
|
||||||
|
|
||||||
|
let (upstream_jvm_args, game_args) =
|
||||||
|
build_game_args(&merged_profile, &rule_ctx, &template_ctx)?;
|
||||||
|
|
||||||
|
let mut jvm_args: Vec<String> = vec![
|
||||||
|
format!("-Xms{}", config.memory_min.as_deref().unwrap_or("512M")),
|
||||||
|
format!("-Xmx{}", config.memory_max.as_deref().unwrap_or("2G")),
|
||||||
|
];
|
||||||
|
jvm_args.extend(patch_jvm_args);
|
||||||
|
jvm_args.extend(upstream_jvm_args);
|
||||||
|
jvm_args.extend(config.jvm_args.clone());
|
||||||
|
|
||||||
|
Ok(LaunchInvocation {
|
||||||
|
java,
|
||||||
|
jvm_args,
|
||||||
|
classpath,
|
||||||
|
classpath_string: cp_str,
|
||||||
|
main_class,
|
||||||
|
extra_args,
|
||||||
|
game_args,
|
||||||
|
working_dir: minecraft_dir,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolves auth credentials, then builds the launch invocation and spawns
|
||||||
|
// the java process. only thin wrapper logic lives here: token refresh,
|
||||||
|
// process spawn, child supervision. all the heavy lifting (profile loading,
|
||||||
|
// classpath assembly, template rendering) sits behind build_launch_invocation.
|
||||||
|
pub async fn launch(
|
||||||
|
config: &InstanceConfig,
|
||||||
|
instances_dir: &Path,
|
||||||
|
meta_dir: &Path,
|
||||||
|
) -> Result<(), LaunchError> {
|
||||||
|
let name = config.name.clone();
|
||||||
|
|
||||||
|
// resolve auth credentials, refreshing the microsoft token if needed.
|
||||||
|
let mut account_store = crate::auth::AccountStore::load();
|
||||||
|
let Some(acc) = account_store.active_account().cloned() else {
|
||||||
|
return Err(LaunchError::Auth("No account selected".to_owned()));
|
||||||
|
};
|
||||||
|
|
||||||
|
// offline accounts can only launch if a microsoft account exists
|
||||||
|
// (proves the user owns minecraft).
|
||||||
|
if acc.account_type != AccountType::Microsoft && !account_store.has_microsoft_account() {
|
||||||
|
return Err(LaunchError::Auth(
|
||||||
|
"Offline accounts require a Microsoft account that owns Minecraft".to_owned(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let (token, new_refresh, new_expires) = match acc.account_type {
|
||||||
|
AccountType::Microsoft => match crate::auth::refresh_and_get_token(&acc).await {
|
||||||
|
Ok(triple) => triple,
|
||||||
|
Err(e) => return Err(LaunchError::Auth(format!("Authentication failed: {e}"))),
|
||||||
|
},
|
||||||
|
AccountType::Offline => ("0".to_string(), None, None),
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(stored) = account_store
|
||||||
|
.accounts
|
||||||
|
.iter_mut()
|
||||||
|
.find(|a| a.uuid == acc.uuid)
|
||||||
|
{
|
||||||
|
let mut changed = false;
|
||||||
|
if let Some(new_rt) = new_refresh {
|
||||||
|
stored.refresh_token = Some(new_rt);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if let Some(expires) = new_expires {
|
||||||
|
stored.cached_mc_token = Some(token.clone());
|
||||||
|
stored.cached_mc_token_expires_at = Some(expires);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if changed {
|
||||||
|
account_store.save();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let user_type = match acc.account_type {
|
||||||
|
AccountType::Microsoft => "msa",
|
||||||
|
AccountType::Offline => "legacy",
|
||||||
|
};
|
||||||
|
|
||||||
|
let auth = LaunchAuth {
|
||||||
|
username: &acc.username,
|
||||||
|
uuid: &acc.uuid,
|
||||||
|
token: &token,
|
||||||
|
user_type,
|
||||||
|
};
|
||||||
|
|
||||||
|
let invocation = build_launch_invocation(config, instances_dir, meta_dir, &auth).await?;
|
||||||
|
|
||||||
|
let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>();
|
||||||
|
crate::running::register_kill(&name, kill_tx);
|
||||||
|
crate::running::set_state(&name, crate::running::RunState::Starting);
|
||||||
|
tracing::info!(
|
||||||
|
"[{}] Starting Minecraft ({} {})",
|
||||||
|
name,
|
||||||
|
config.game_version,
|
||||||
|
config.loader
|
||||||
|
);
|
||||||
|
|
||||||
|
tracing::info!("[{}] Java: {}", name, invocation.java);
|
||||||
|
tracing::info!("[{}] JVM args: {:?}", name, invocation.jvm_args);
|
||||||
|
tracing::info!(
|
||||||
|
"[{}] Classpath:\n{}",
|
||||||
|
name,
|
||||||
|
invocation
|
||||||
|
.classpath
|
||||||
|
.iter()
|
||||||
|
.map(|p| p.display().to_string())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n")
|
||||||
|
);
|
||||||
|
tracing::info!("[{}] Main class: {}", name, invocation.main_class);
|
||||||
|
|
||||||
|
let mut cmd = tokio::process::Command::new(&invocation.java);
|
||||||
|
cmd.args(&invocation.jvm_args);
|
||||||
|
cmd.arg("-cp").arg(&invocation.classpath_string);
|
||||||
|
cmd.arg(&invocation.main_class);
|
||||||
|
cmd.args(&invocation.extra_args);
|
||||||
|
cmd.args(&invocation.game_args);
|
||||||
|
cmd.current_dir(&invocation.working_dir);
|
||||||
|
cmd.stdout(std::process::Stdio::piped());
|
||||||
|
cmd.stderr(std::process::Stdio::piped());
|
||||||
|
|
||||||
|
let mut child = match cmd.spawn() {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => {
|
||||||
|
crate::running::cleanup_kill_sender(&name);
|
||||||
|
crate::running::remove(&name);
|
||||||
|
return Err(LaunchError::Io(e));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
crate::running::set_state(&name, crate::running::RunState::Running);
|
||||||
|
|
||||||
|
let log_file_path = crate::instance::log_files::create_log_file(instances_dir, &name);
|
||||||
|
|
||||||
|
let name_for_task = name.clone();
|
||||||
|
let instances_dir_owned = instances_dir.to_path_buf();
|
||||||
|
let meta_dir_owned = meta_dir.to_path_buf();
|
||||||
|
|
||||||
|
// spawn a background task to babysit the child process: capture stdout/stderr
|
||||||
|
// into both the TUI log viewer and a timestamped log file on disk
|
||||||
|
tokio::spawn(async move {
|
||||||
|
use std::io::Write;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use tokio::io::AsyncBufReadExt;
|
||||||
|
|
||||||
|
let log_writer: Arc<Mutex<Option<std::fs::File>>> = Arc::new(Mutex::new(
|
||||||
|
log_file_path.and_then(|p| std::fs::File::create(p).ok()),
|
||||||
|
));
|
||||||
|
|
||||||
|
if let Some(stdout) = child.stdout.take() {
|
||||||
|
let n = name_for_task.clone();
|
||||||
|
let w = log_writer.clone();
|
||||||
|
let mut lines = tokio::io::BufReader::new(stdout).lines();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
while let Ok(Some(line)) = lines.next_line().await {
|
||||||
|
tracing::info!(target: "mc_instance", "[{}] {}", n, line);
|
||||||
|
crate::instance_logs::push(&n, &line);
|
||||||
|
if let Ok(mut f) = w.lock()
|
||||||
|
&& let Some(f) = f.as_mut()
|
||||||
|
{
|
||||||
|
let _ = writeln!(f, "{}", line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(stderr) = child.stderr.take() {
|
||||||
|
let n = name_for_task.clone();
|
||||||
|
let w = log_writer.clone();
|
||||||
|
let mut lines = tokio::io::BufReader::new(stderr).lines();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
while let Ok(Some(line)) = lines.next_line().await {
|
||||||
|
tracing::warn!(target: "mc_instance", "[{}] {}", n, line);
|
||||||
|
crate::instance_logs::push(&n, &line);
|
||||||
|
if let Ok(mut f) = w.lock()
|
||||||
|
&& let Some(f) = f.as_mut()
|
||||||
|
{
|
||||||
|
let _ = writeln!(f, "[STDERR] {}", line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// wait for either the process to exit naturally or a kill signal from the TUI
|
||||||
|
let code = tokio::select! {
|
||||||
|
_ = kill_rx => {
|
||||||
|
tracing::info!("[{}] Kill requested, terminating process", name_for_task);
|
||||||
|
let _ = child.kill().await;
|
||||||
|
let _ = child.wait().await;
|
||||||
|
None
|
||||||
|
}
|
||||||
|
result = child.wait() => {
|
||||||
|
result.ok().and_then(|s| s.code())
|
||||||
|
}
|
||||||
|
};
|
||||||
|
tracing::info!("[{}] Exited with code {:?}", name_for_task, code);
|
||||||
|
|
||||||
|
if code == Some(0) {
|
||||||
|
crate::running::remove(&name_for_task);
|
||||||
|
} else {
|
||||||
|
crate::running::set_state(&name_for_task, crate::running::RunState::Crashed(code));
|
||||||
|
}
|
||||||
|
|
||||||
|
let manager = crate::instance::InstanceManager::new(instances_dir_owned, meta_dir_owned);
|
||||||
|
if let Err(e) = manager.touch_last_played(&name_for_task) {
|
||||||
|
tracing::warn!(
|
||||||
|
"Failed to update last_played for '{}': {}",
|
||||||
|
name_for_task,
|
||||||
|
e
|
||||||
|
);
|
||||||
|
}
|
||||||
|
crate::running::push_last_played(&name_for_task, chrono::Utc::now());
|
||||||
|
crate::running::cleanup_kill_sender(&name_for_task);
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn build_game_args_renders_upstream_arguments() {
|
||||||
|
use crate::launch_profile::model::{Argument, Arguments, LaunchProfile};
|
||||||
|
use crate::launch_profile::rules::{FeatureSet, RuleContext};
|
||||||
|
use TemplateContext;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
let lib = PathBuf::from("/m/libraries");
|
||||||
|
let nat = PathBuf::from("/m/natives");
|
||||||
|
let game_dir = PathBuf::from("/i/.minecraft");
|
||||||
|
let assets = PathBuf::from("/m/assets");
|
||||||
|
|
||||||
|
let template_ctx = TemplateContext {
|
||||||
|
library_directory: &lib,
|
||||||
|
classpath_separator: ":",
|
||||||
|
version_name: "1.20.1",
|
||||||
|
natives_directory: &nat,
|
||||||
|
classpath: "a.jar:b.jar",
|
||||||
|
game_directory: &game_dir,
|
||||||
|
assets_root: &assets,
|
||||||
|
assets_index_name: "5",
|
||||||
|
auth_player_name: "Player",
|
||||||
|
auth_uuid: "00000000-0000-0000-0000-000000000000",
|
||||||
|
auth_access_token: "token",
|
||||||
|
auth_xuid: "0",
|
||||||
|
user_type: "msa",
|
||||||
|
user_properties: "{}",
|
||||||
|
launcher_name: "rmcl",
|
||||||
|
launcher_version: "test",
|
||||||
|
clientid: "0",
|
||||||
|
version_type: "release",
|
||||||
|
};
|
||||||
|
let features = FeatureSet::default();
|
||||||
|
let rule_ctx = RuleContext {
|
||||||
|
os_name: "linux",
|
||||||
|
os_version: "6.0",
|
||||||
|
arch: "x86_64",
|
||||||
|
features: &features,
|
||||||
|
};
|
||||||
|
|
||||||
|
let profile = LaunchProfile {
|
||||||
|
id: "1.20.1".into(),
|
||||||
|
inherits_from: None,
|
||||||
|
main_class: Some("net.minecraft.client.main.Main".into()),
|
||||||
|
libraries: Vec::new(),
|
||||||
|
arguments: Some(Arguments {
|
||||||
|
game: vec![
|
||||||
|
Argument::Literal("--username".into()),
|
||||||
|
Argument::Literal("${auth_player_name}".into()),
|
||||||
|
],
|
||||||
|
jvm: vec![Argument::Literal(
|
||||||
|
"-Djava.library.path=${natives_directory}".into(),
|
||||||
|
)],
|
||||||
|
}),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
let (jvm, game_args) = build_game_args(&profile, &rule_ctx, &template_ctx).unwrap();
|
||||||
|
assert_eq!(jvm, vec!["-Djava.library.path=/m/natives"]);
|
||||||
|
assert_eq!(game_args, vec!["--username", "Player"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// exercises the early-return branch of migrate_legacy_meta_if_needed.
|
||||||
|
// a profile with either arguments or minecraftArguments is not legacy
|
||||||
|
// and must produce Ok(None) without touching the network. covers both
|
||||||
|
// shapes in one parameterised test so a regression that drops one of
|
||||||
|
// the two predicate conditions is caught.
|
||||||
|
#[rstest::rstest]
|
||||||
|
#[case::modern_arguments(true, false)]
|
||||||
|
#[case::legacy_minecraft_arguments(false, true)]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn migrate_legacy_meta_skips_when_arguments_present(
|
||||||
|
#[case] modern: bool,
|
||||||
|
#[case] legacy: bool,
|
||||||
|
) {
|
||||||
|
use crate::launch_profile::model::{Arguments, LaunchProfile};
|
||||||
|
use tempfile::TempDir;
|
||||||
|
|
||||||
|
let tmp = TempDir::new().unwrap();
|
||||||
|
let meta_path = tmp.path().join("meta.json");
|
||||||
|
std::fs::write(&meta_path, b"{}").unwrap();
|
||||||
|
|
||||||
|
let profile = LaunchProfile {
|
||||||
|
id: "1.20.1".into(),
|
||||||
|
main_class: Some("net.test.Main".into()),
|
||||||
|
arguments: modern.then(Arguments::default),
|
||||||
|
minecraft_arguments: legacy.then(|| "--username Player".into()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = migrate_legacy_meta_if_needed(&meta_path, &profile, "1.20.1").await;
|
||||||
|
assert!(
|
||||||
|
matches!(result, Ok(None)),
|
||||||
|
"expected Ok(None) for non-legacy profile, got {result:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// each loader maps to a distinct directory-naming branch. one rstest
|
||||||
|
// exercises every variant so a regression that misorders the match
|
||||||
|
// arms in installer_version_dir_name is caught.
|
||||||
|
#[rstest::rstest]
|
||||||
|
#[case::forge(ModLoader::Forge, "1.20.1", "47.2.0", Some("1.20.1-forge-47.2.0"))]
|
||||||
|
#[case::neoforge(ModLoader::NeoForge, "1.21.1", "21.1.0", Some("neoforge-21.1.0"))]
|
||||||
|
#[case::vanilla(ModLoader::Vanilla, "1.20.1", "v", None)]
|
||||||
|
#[case::fabric(ModLoader::Fabric, "1.20.1", "0.14.21", None)]
|
||||||
|
#[case::quilt(ModLoader::Quilt, "1.20.1", "0.20.0", None)]
|
||||||
|
fn installer_version_dir_name_per_loader(
|
||||||
|
#[case] loader: ModLoader,
|
||||||
|
#[case] game_version: &str,
|
||||||
|
#[case] loader_version: &str,
|
||||||
|
#[case] expected: Option<&str>,
|
||||||
|
) {
|
||||||
|
assert_eq!(
|
||||||
|
installer_version_dir_name(loader, game_version, loader_version),
|
||||||
|
expected.map(str::to_owned)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// exercises the modern-profile early-return in
|
||||||
|
// migrate_legacy_loader_profile_if_needed. any of inheritsFrom,
|
||||||
|
// arguments, minecraftArguments present (or game_arguments absent)
|
||||||
|
// means "not legacy" and the function must return Ok(None) without
|
||||||
|
// touching the installer JSON path.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn migrate_legacy_loader_profile_skips_modern_with_inherits_from() {
|
||||||
|
use LaunchProfile;
|
||||||
|
use chrono::Utc;
|
||||||
|
use tempfile::TempDir;
|
||||||
|
|
||||||
|
let tmp = TempDir::new().unwrap();
|
||||||
|
let instance_dir = tmp.path().join("instance");
|
||||||
|
std::fs::create_dir_all(&instance_dir).unwrap();
|
||||||
|
let profile_path = tmp.path().join("forge-1.20.1-47.2.0.json");
|
||||||
|
std::fs::write(&profile_path, b"{}").unwrap();
|
||||||
|
|
||||||
|
let modern = LaunchProfile {
|
||||||
|
id: "1.20.1-forge-47.2.0".into(),
|
||||||
|
inherits_from: Some("1.20.1".into()),
|
||||||
|
main_class: Some("cpw.mods.bootstraplauncher.BootstrapLauncher".into()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
let config = InstanceConfig {
|
||||||
|
name: "test".into(),
|
||||||
|
game_version: "1.20.1".into(),
|
||||||
|
loader: ModLoader::Forge,
|
||||||
|
loader_version: Some("47.2.0".into()),
|
||||||
|
created: Utc::now(),
|
||||||
|
last_played: None,
|
||||||
|
java_path: None,
|
||||||
|
memory_max: None,
|
||||||
|
memory_min: None,
|
||||||
|
jvm_args: Vec::new(),
|
||||||
|
resolution: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
let result =
|
||||||
|
migrate_legacy_loader_profile_if_needed(&profile_path, &modern, &config, &instance_dir)
|
||||||
|
.await;
|
||||||
|
assert!(matches!(result, Ok(None)), "expected Ok(None), got {result:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn migrate_legacy_loader_profile_skips_fabric() {
|
||||||
|
// a fresh upstream Fabric profile happens to match the "legacy"
|
||||||
|
// shape (no inheritsFrom, no arguments, no minecraftArguments).
|
||||||
|
// make sure the migration helper recognises this is Fabric and
|
||||||
|
// returns Ok(None) instead of erroring with "reinstall Fabric".
|
||||||
|
use LaunchProfile;
|
||||||
|
use chrono::Utc;
|
||||||
|
use tempfile::TempDir;
|
||||||
|
|
||||||
|
let tmp = TempDir::new().unwrap();
|
||||||
|
let instance_dir = tmp.path().join("instance");
|
||||||
|
std::fs::create_dir_all(&instance_dir).unwrap();
|
||||||
|
let profile_path = tmp.path().join("fabric-1.20.1-0.14.21.json");
|
||||||
|
std::fs::write(&profile_path, b"{}").unwrap();
|
||||||
|
|
||||||
|
let upstream_fabric_shape = LaunchProfile {
|
||||||
|
id: "fabric-loader-0.14.21-1.20.1".into(),
|
||||||
|
inherits_from: None,
|
||||||
|
main_class: Some("net.fabricmc.loader.impl.launch.knot.KnotClient".into()),
|
||||||
|
libraries: Vec::new(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
let config = InstanceConfig {
|
||||||
|
name: "test".into(),
|
||||||
|
game_version: "1.20.1".into(),
|
||||||
|
loader: ModLoader::Fabric,
|
||||||
|
loader_version: Some("0.14.21".into()),
|
||||||
|
created: Utc::now(),
|
||||||
|
last_played: None,
|
||||||
|
java_path: None,
|
||||||
|
memory_max: None,
|
||||||
|
memory_min: None,
|
||||||
|
jvm_args: Vec::new(),
|
||||||
|
resolution: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = migrate_legacy_loader_profile_if_needed(
|
||||||
|
&profile_path,
|
||||||
|
&upstream_fabric_shape,
|
||||||
|
&config,
|
||||||
|
&instance_dir,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
matches!(result, Ok(None)),
|
||||||
|
"expected Ok(None), got {result:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,460 @@
|
|||||||
|
// classpath and jvm patches for legacy forge on java 9+.
|
||||||
|
// lwjgl3ify ships a patched launchwrapper and retrofuturabootstrap that
|
||||||
|
// replace the old URLClassLoader-based launcher with one that works on
|
||||||
|
// modern java. this module handles extracting those patches, building
|
||||||
|
// the right --add-opens flags, and swapping out the broken log4j jars.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
const LOG4J_FIXED_BASE: &str = "https://files.prismlauncher.org/maven/org/apache/logging/log4j";
|
||||||
|
|
||||||
|
pub struct LwjglifyPatches {
|
||||||
|
pub jvm_args: Vec<String>,
|
||||||
|
pub main_class: String,
|
||||||
|
// extra args inserted before game args (used by the shim to pass
|
||||||
|
// the real main class name)
|
||||||
|
pub extra_args: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// checks if lwjgl3ify is present in the mods folder, and if so:
|
||||||
|
// 1. extracts forge patches from the lwjgl3ify jar
|
||||||
|
// 2. prepends them to the classpath so they shadow vanilla launchwrapper
|
||||||
|
// 3. parses --add-opens from the patches manifest
|
||||||
|
// 4. replaces log4j 2.0-beta9 with prism's patched builds
|
||||||
|
// 5. returns the jvm args and overridden main class
|
||||||
|
pub async fn apply(
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
lib_dir: &Path,
|
||||||
|
classpath: &mut Vec<PathBuf>,
|
||||||
|
) -> Option<LwjglifyPatches> {
|
||||||
|
let mods_dir = minecraft_dir.join("mods");
|
||||||
|
let lwjgl3ify_jar = find_lwjgl3ify_jar(&mods_dir)?;
|
||||||
|
|
||||||
|
// rfb only scans jars for plugin metadata. keeping the extracted
|
||||||
|
// forgePatches payload as a zip makes it skip rfb-asm-safety and
|
||||||
|
// rfb-modern-java, which GTNH needs on modern Java.
|
||||||
|
let patches_dest = minecraft_dir.join(".forge-patches.jar");
|
||||||
|
|
||||||
|
if let Err(e) = extract_forge_patches(&lwjgl3ify_jar, &patches_dest) {
|
||||||
|
tracing::warn!("Failed to extract lwjgl3ify forge patches: {e}");
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// prepend so patched classes shadow vanilla launchwrapper
|
||||||
|
classpath.insert(0, patches_dest.clone());
|
||||||
|
|
||||||
|
let mut jvm_args = parse_add_opens(&patches_dest).unwrap_or_default();
|
||||||
|
|
||||||
|
// RFB requires its own classloader to be the system classloader, and
|
||||||
|
// its Main class handles bootstrapping into launchwrapper.
|
||||||
|
// the other flags match lwjgl3ify's java9args.txt.
|
||||||
|
jvm_args.extend([
|
||||||
|
"-Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader"
|
||||||
|
.to_string(),
|
||||||
|
"-Dfile.encoding=UTF-8".to_string(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// forge patches replace launchwrapper, asm, and old lwjgl2.
|
||||||
|
// lwjgl3ify redirects lwjgl2 calls to lwjgl3 at runtime, so lwjgl3
|
||||||
|
// must be on the classpath (matching what prism does).
|
||||||
|
strip_replaced_libs(classpath);
|
||||||
|
add_lwjgl3(lib_dir, classpath);
|
||||||
|
|
||||||
|
replace_log4j_fixed(lib_dir, classpath).await;
|
||||||
|
|
||||||
|
// on java 24+, SecurityManager.getClassContext() was reimplemented to use
|
||||||
|
// StackWalker. log4j 2.0-beta9's ThrowableProxy calls getClassContext() to
|
||||||
|
// resolve stack frames, but StackWalker triggers class loading through
|
||||||
|
// LaunchClassLoader, which debug-logs failures, which creates another
|
||||||
|
// ThrowableProxy... infinite recursion. we break the loop by providing a
|
||||||
|
// log4j config that sets the root level to INFO, so the debug() call in
|
||||||
|
// LaunchClassLoader is a no-op and never creates a ThrowableProxy.
|
||||||
|
write_log4j_config(minecraft_dir, &mut jvm_args);
|
||||||
|
|
||||||
|
// RfbSystemClassLoader discovers plugins differently depending on whether
|
||||||
|
// the main class is loaded by the JVM directly or through the system
|
||||||
|
// classloader's loadClass(). direct invocation misses the rfb-asm-safety
|
||||||
|
// and rfb-modern-java plugins from forgePatches, causing
|
||||||
|
// ClassCircularityErrors. we use a tiny shim jar that loads the real main
|
||||||
|
// class through ClassLoader.getSystemClassLoader().loadClass(), matching
|
||||||
|
// how prism's EntryPoint does it.
|
||||||
|
let shim_path = deploy_shim(minecraft_dir);
|
||||||
|
classpath.insert(0, shim_path);
|
||||||
|
|
||||||
|
Some(LwjglifyPatches {
|
||||||
|
jvm_args,
|
||||||
|
main_class: "RmclShim".to_string(),
|
||||||
|
extra_args: vec!["com.gtnewhorizons.retrofuturabootstrap.Main".to_string()],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const SHIM_JAR: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/rmcl-shim.jar"));
|
||||||
|
|
||||||
|
fn deploy_shim(minecraft_dir: &Path) -> PathBuf {
|
||||||
|
let dest = minecraft_dir.join(".rmcl-shim.jar");
|
||||||
|
if let Err(e) = std::fs::write(&dest, SHIM_JAR) {
|
||||||
|
tracing::warn!("Failed to write rmcl-shim.jar: {e}");
|
||||||
|
}
|
||||||
|
dest
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_lwjgl3ify_jar(mods_dir: &Path) -> Option<PathBuf> {
|
||||||
|
let entries = std::fs::read_dir(mods_dir).ok()?;
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let name = entry.file_name();
|
||||||
|
let name = name.to_string_lossy();
|
||||||
|
if name.starts_with("lwjgl3ify") && name.ends_with(".jar") {
|
||||||
|
return Some(entry.path());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extract_forge_patches(lwjgl3ify_jar: &Path, dest: &Path) -> Result<(), std::io::Error> {
|
||||||
|
use std::io::Read;
|
||||||
|
|
||||||
|
let file = std::fs::File::open(lwjgl3ify_jar)?;
|
||||||
|
let mut archive = zip::ZipArchive::new(file)
|
||||||
|
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
|
||||||
|
let mut entry = archive
|
||||||
|
.by_name("me/eigenraven/lwjgl3ify/relauncher/forgePatches.zip")
|
||||||
|
.map_err(|e| std::io::Error::new(std::io::ErrorKind::NotFound, e))?;
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
entry.read_to_end(&mut buf)?;
|
||||||
|
std::fs::write(dest, &buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_add_opens(patches_archive: &Path) -> Option<Vec<String>> {
|
||||||
|
use std::io::Read;
|
||||||
|
|
||||||
|
let file = std::fs::File::open(patches_archive).ok()?;
|
||||||
|
let mut archive = zip::ZipArchive::new(file).ok()?;
|
||||||
|
let mut entry = archive.by_name("META-INF/MANIFEST.MF").ok()?;
|
||||||
|
let mut manifest = String::new();
|
||||||
|
entry.read_to_string(&mut manifest).ok()?;
|
||||||
|
|
||||||
|
// manifest continuation lines start with a single space
|
||||||
|
let manifest = manifest.replace("\r\n ", "").replace("\n ", "");
|
||||||
|
|
||||||
|
let mut args = Vec::new();
|
||||||
|
for line in manifest.lines() {
|
||||||
|
if let Some(value) = line.strip_prefix("Add-Opens: ") {
|
||||||
|
for module_package in value.split_whitespace() {
|
||||||
|
args.push("--add-opens".to_string());
|
||||||
|
args.push(format!("{module_package}=ALL-UNNAMED"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(args)
|
||||||
|
}
|
||||||
|
|
||||||
|
// strips libraries from the classpath that are replaced by forge patches
|
||||||
|
// or not needed with lwjgl3ify. matches what prism's component system does:
|
||||||
|
// no old lwjgl2, no vanilla launchwrapper/asm, no extra vanilla-only libs.
|
||||||
|
fn strip_replaced_libs(classpath: &mut Vec<PathBuf>) {
|
||||||
|
let replaced = [
|
||||||
|
"launchwrapper-",
|
||||||
|
"asm-all-",
|
||||||
|
"lwjgl-2.",
|
||||||
|
"lwjgl_util-",
|
||||||
|
"commons-compress-",
|
||||||
|
"commons-io-",
|
||||||
|
"guava-15.",
|
||||||
|
];
|
||||||
|
|
||||||
|
classpath.retain(|entry| {
|
||||||
|
let name = entry
|
||||||
|
.file_name()
|
||||||
|
.map(|n| n.to_string_lossy())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let dominated = replaced.iter().any(|prefix| name.starts_with(prefix));
|
||||||
|
if dominated {
|
||||||
|
tracing::info!("Stripping {name} from classpath (replaced by forge-patches)");
|
||||||
|
}
|
||||||
|
!dominated
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// adds lwjgl 3.3.3 to the classpath. lwjgl3ify redirects old lwjgl2 calls
|
||||||
|
// to lwjgl3 at runtime, but the lwjgl3 jars need to be on the system
|
||||||
|
// classpath for this to work. prism includes these via its org.lwjgl3
|
||||||
|
// component; we add them from the meta library cache.
|
||||||
|
fn add_lwjgl3(lib_dir: &Path, classpath: &mut Vec<PathBuf>) {
|
||||||
|
let lwjgl3_modules = [
|
||||||
|
"lwjgl",
|
||||||
|
"lwjgl-freetype",
|
||||||
|
"lwjgl-glfw",
|
||||||
|
"lwjgl-jemalloc",
|
||||||
|
"lwjgl-openal",
|
||||||
|
"lwjgl-opengl",
|
||||||
|
"lwjgl-stb",
|
||||||
|
"lwjgl-tinyfd",
|
||||||
|
];
|
||||||
|
|
||||||
|
let os_classifier = match std::env::consts::OS {
|
||||||
|
"macos" => "natives-macos",
|
||||||
|
"windows" => "natives-windows",
|
||||||
|
_ => "natives-linux",
|
||||||
|
};
|
||||||
|
|
||||||
|
// insert lwjgl3 jars right after forge patches (position 1+)
|
||||||
|
let mut insert_pos = 1.min(classpath.len());
|
||||||
|
for module in &lwjgl3_modules {
|
||||||
|
let base = if *module == "lwjgl" {
|
||||||
|
lib_dir.join("org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3.jar")
|
||||||
|
} else {
|
||||||
|
lib_dir.join(format!("org/lwjgl/{0}/3.3.3/{0}-3.3.3.jar", module))
|
||||||
|
};
|
||||||
|
if base.exists() {
|
||||||
|
classpath.insert(insert_pos, base);
|
||||||
|
insert_pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// natives
|
||||||
|
let natives = if *module == "lwjgl" {
|
||||||
|
lib_dir.join(format!(
|
||||||
|
"org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3-{os_classifier}.jar"
|
||||||
|
))
|
||||||
|
} else {
|
||||||
|
lib_dir.join(format!(
|
||||||
|
"org/lwjgl/{0}/3.3.3/{0}-3.3.3-{1}.jar",
|
||||||
|
module, os_classifier
|
||||||
|
))
|
||||||
|
};
|
||||||
|
if natives.exists() {
|
||||||
|
classpath.insert(insert_pos, natives);
|
||||||
|
insert_pos += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::info!("Added {} LWJGL 3.3.3 jars to classpath", insert_pos - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// writes a log4j2.xml config that sets the root logger to INFO. this
|
||||||
|
// prevents LaunchClassLoader's debug() call from ever firing, which
|
||||||
|
// avoids the ThrowableProxy -> SecurityManager -> StackWalker infinite
|
||||||
|
// recursion on java 24+. the config is written to .minecraft/ and
|
||||||
|
// pointed to via -Dlog4j.configurationFile.
|
||||||
|
fn write_log4j_config(minecraft_dir: &Path, jvm_args: &mut Vec<String>) {
|
||||||
|
let config_path = minecraft_dir.join(".rmcl-log4j2.xml");
|
||||||
|
let config = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Configuration status="WARN">
|
||||||
|
<Appenders>
|
||||||
|
<Console name="SysOut" target="SYSTEM_OUT">
|
||||||
|
<PatternLayout pattern="[%d{HH:mm:ss}] [%t/%level] [%logger]: %msg%n"/>
|
||||||
|
</Console>
|
||||||
|
<Queue name="ServerGuiConsole">
|
||||||
|
<PatternLayout pattern="[%d{HH:mm:ss} %level]: %msg%n"/>
|
||||||
|
</Queue>
|
||||||
|
<RollingRandomAccessFile name="File" fileName="logs/latest.log"
|
||||||
|
filePattern="logs/%d{yyyy-MM-dd}-%i.log.gz">
|
||||||
|
<PatternLayout pattern="[%d{HH:mm:ss}] [%t/%level]: %msg%n"/>
|
||||||
|
<Policies>
|
||||||
|
<TimeBasedTriggeringPolicy/>
|
||||||
|
<OnStartupTriggeringPolicy/>
|
||||||
|
</Policies>
|
||||||
|
</RollingRandomAccessFile>
|
||||||
|
</Appenders>
|
||||||
|
<Loggers>
|
||||||
|
<Root level="info">
|
||||||
|
<AppenderRef ref="SysOut"/>
|
||||||
|
<AppenderRef ref="File"/>
|
||||||
|
</Root>
|
||||||
|
</Loggers>
|
||||||
|
</Configuration>
|
||||||
|
"#;
|
||||||
|
|
||||||
|
if let Err(e) = std::fs::write(&config_path, config) {
|
||||||
|
tracing::warn!("Failed to write log4j2 config: {e}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
jvm_args.push(format!(
|
||||||
|
"-Dlog4j.configurationFile={}",
|
||||||
|
config_path.display()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// replaces log4j-api and log4j-core 2.0-beta9 in the classpath with
|
||||||
|
// prism's patched "-fixed" builds. the vanilla 2.0-beta9 has a bug
|
||||||
|
// where ThrowableProxy calls SecurityManager.getClassContext() which
|
||||||
|
// on java 24+ uses StackWalker internally, triggering class loading
|
||||||
|
// through LaunchClassLoader, which triggers more logging, infinite
|
||||||
|
// recursion, stack overflow. the fixed builds patch this out.
|
||||||
|
async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) {
|
||||||
|
let replacements = [
|
||||||
|
(
|
||||||
|
"log4j-api-2.0-beta9.jar",
|
||||||
|
"org/apache/logging/log4j/log4j-api/2.0-beta9-fixed/log4j-api-2.0-beta9-fixed.jar",
|
||||||
|
format!("{LOG4J_FIXED_BASE}/log4j-api/2.0-beta9-fixed/log4j-api-2.0-beta9-fixed.jar"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"log4j-core-2.0-beta9.jar",
|
||||||
|
"org/apache/logging/log4j/log4j-core/2.0-beta9-fixed/log4j-core-2.0-beta9-fixed.jar",
|
||||||
|
format!("{LOG4J_FIXED_BASE}/log4j-core/2.0-beta9-fixed/log4j-core-2.0-beta9-fixed.jar"),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (old_name, fixed_rel, url) in &replacements {
|
||||||
|
let fixed_path = lib_dir.join(fixed_rel);
|
||||||
|
|
||||||
|
if !fixed_path.exists() {
|
||||||
|
tracing::info!("Downloading patched {old_name}...");
|
||||||
|
if let Some(parent) = fixed_path.parent() {
|
||||||
|
let _ = tokio::fs::create_dir_all(parent).await;
|
||||||
|
}
|
||||||
|
let client = crate::net::HttpClient::new();
|
||||||
|
if let Err(e) = crate::net::download_file(&client, url, &fixed_path, |_, _| {}).await {
|
||||||
|
tracing::error!(
|
||||||
|
"Failed to download patched {old_name}: {e}, continuing with unpatched version"
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for entry in classpath.iter_mut() {
|
||||||
|
if entry
|
||||||
|
.file_name()
|
||||||
|
.is_some_and(|n| n.to_string_lossy() == *old_name)
|
||||||
|
{
|
||||||
|
tracing::info!("Replacing {old_name} with patched version");
|
||||||
|
*entry = fixed_path.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
// builds an in-memory zip with the given entries, writes it to tmp, and
|
||||||
|
// returns the path. shared by parse_add_opens tests.
|
||||||
|
fn make_zip(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> PathBuf {
|
||||||
|
let path = tmp.join(name);
|
||||||
|
let file = std::fs::File::create(&path).unwrap();
|
||||||
|
let mut zip = zip::ZipWriter::new(file);
|
||||||
|
let opts: zip::write::SimpleFileOptions = Default::default();
|
||||||
|
for (filename, bytes) in entries {
|
||||||
|
zip.start_file(*filename, opts).unwrap();
|
||||||
|
zip.write_all(bytes).unwrap();
|
||||||
|
}
|
||||||
|
zip.finish().unwrap();
|
||||||
|
path
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn strip_replaced_libs_removes_dominated_prefixes() {
|
||||||
|
let mut classpath = vec![
|
||||||
|
PathBuf::from("/libs/launchwrapper-1.12.jar"),
|
||||||
|
PathBuf::from("/libs/asm-all-5.0.3.jar"),
|
||||||
|
PathBuf::from("/libs/lwjgl-2.9.4.jar"),
|
||||||
|
PathBuf::from("/libs/lwjgl_util-2.9.4.jar"),
|
||||||
|
PathBuf::from("/libs/commons-compress-1.4.1.jar"),
|
||||||
|
PathBuf::from("/libs/commons-io-2.4.jar"),
|
||||||
|
PathBuf::from("/libs/guava-15.0.jar"),
|
||||||
|
// these stay
|
||||||
|
PathBuf::from("/libs/log4j-core-2.0.jar"),
|
||||||
|
PathBuf::from("/libs/guava-21.0.jar"),
|
||||||
|
];
|
||||||
|
strip_replaced_libs(&mut classpath);
|
||||||
|
assert_eq!(
|
||||||
|
classpath,
|
||||||
|
vec![
|
||||||
|
PathBuf::from("/libs/log4j-core-2.0.jar"),
|
||||||
|
PathBuf::from("/libs/guava-21.0.jar"),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn strip_replaced_libs_keeps_unrelated_entries() {
|
||||||
|
let mut classpath = vec![
|
||||||
|
PathBuf::from("/libs/log4j-core-2.0.jar"),
|
||||||
|
PathBuf::from("/libs/mixin-0.8.5.jar"),
|
||||||
|
];
|
||||||
|
let original = classpath.clone();
|
||||||
|
strip_replaced_libs(&mut classpath);
|
||||||
|
assert_eq!(classpath, original);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_add_opens_extracts_module_args() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let manifest = b"Manifest-Version: 1.0\nAdd-Opens: java.base/java.lang java.base/java.util\n";
|
||||||
|
let zip_path = make_zip(tmp.path(), "patches.zip", &[("META-INF/MANIFEST.MF", manifest)]);
|
||||||
|
let args = parse_add_opens(&zip_path).expect("parsed");
|
||||||
|
assert_eq!(
|
||||||
|
args,
|
||||||
|
vec![
|
||||||
|
"--add-opens",
|
||||||
|
"java.base/java.lang=ALL-UNNAMED",
|
||||||
|
"--add-opens",
|
||||||
|
"java.base/java.util=ALL-UNNAMED",
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_add_opens_handles_continuation_lines() {
|
||||||
|
// jar manifests wrap long lines: the line ends with a trailing space,
|
||||||
|
// then the next physical line starts with a leading space marker.
|
||||||
|
// when joined per the MANIFEST.MF spec, the trailing space remains
|
||||||
|
// and the leading space marker is consumed, so the two values stay
|
||||||
|
// separated by exactly one space when split_whitespace runs.
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let manifest =
|
||||||
|
b"Manifest-Version: 1.0\nAdd-Opens: java.base/java.lang \n java.base/sun.security.util\n";
|
||||||
|
let zip_path = make_zip(
|
||||||
|
tmp.path(),
|
||||||
|
"patches-continuation.zip",
|
||||||
|
&[("META-INF/MANIFEST.MF", manifest)],
|
||||||
|
);
|
||||||
|
let args = parse_add_opens(&zip_path).expect("parsed");
|
||||||
|
assert_eq!(
|
||||||
|
args,
|
||||||
|
vec![
|
||||||
|
"--add-opens",
|
||||||
|
"java.base/java.lang=ALL-UNNAMED",
|
||||||
|
"--add-opens",
|
||||||
|
"java.base/sun.security.util=ALL-UNNAMED",
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_add_opens_returns_none_when_manifest_missing() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let zip_path = make_zip(tmp.path(), "no-manifest.zip", &[("other.txt", b"x")]);
|
||||||
|
assert!(parse_add_opens(&zip_path).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_add_opens_returns_none_for_missing_file() {
|
||||||
|
assert!(parse_add_opens(Path::new("/nonexistent/x.zip")).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn add_lwjgl3_inserts_only_jars_that_exist() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let lib_dir = tmp.path();
|
||||||
|
|
||||||
|
// pre-create only the lwjgl core jar; everything else absent so the
|
||||||
|
// function should skip them silently. proves we don't insert paths
|
||||||
|
// for jars that aren't there.
|
||||||
|
let core_jar = lib_dir.join("org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3.jar");
|
||||||
|
std::fs::create_dir_all(core_jar.parent().unwrap()).unwrap();
|
||||||
|
std::fs::write(&core_jar, b"jar").unwrap();
|
||||||
|
|
||||||
|
let mut classpath = vec![PathBuf::from("/leading/forge-patches.jar")];
|
||||||
|
add_lwjgl3(lib_dir, &mut classpath);
|
||||||
|
|
||||||
|
// forge-patches stays at index 0; lwjgl core is inserted at index 1.
|
||||||
|
// none of the other modules existed so nothing else was added.
|
||||||
|
assert_eq!(classpath[0], PathBuf::from("/leading/forge-patches.jar"));
|
||||||
|
assert_eq!(classpath[1], core_jar);
|
||||||
|
assert_eq!(classpath.len(), 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,7 +7,7 @@ use async_trait::async_trait;
|
|||||||
|
|
||||||
use super::{GameVersion, ModLoaderInstaller};
|
use super::{GameVersion, ModLoaderInstaller};
|
||||||
use crate::instance::models::ModLoader;
|
use crate::instance::models::ModLoader;
|
||||||
use crate::net::{fabric as fabric_api, HttpClient, NetError};
|
use crate::net::{HttpClient, NetError, fabric as fabric_api};
|
||||||
|
|
||||||
pub struct FabricInstaller;
|
pub struct FabricInstaller;
|
||||||
|
|
||||||
@@ -41,16 +41,14 @@ impl ModLoaderInstaller for FabricInstaller {
|
|||||||
_instance_dir: &Path,
|
_instance_dir: &Path,
|
||||||
meta_dir: &Path,
|
meta_dir: &Path,
|
||||||
) -> Result<(), NetError> {
|
) -> Result<(), NetError> {
|
||||||
let profile =
|
let (profile, raw_bytes) =
|
||||||
fabric_api::fetch_fabric_profile(client, game_version, loader_version).await?;
|
fabric_api::fetch_fabric_profile_with_raw(client, game_version, loader_version).await?;
|
||||||
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,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
// forge installation. unlike fabric/quilt, forge ships a java-based installer
|
// forge installation. modern forge runs a java installer, old forge (pre-1.13)
|
||||||
// that has to be downloaded and executed. yes, a jvm is needed just to install
|
// can't run headless so we extract the profile and libraries from the jar
|
||||||
// the thing that runs on a jvm. the installer jar gets cleaned up afterward.
|
// directly. the installer jar gets cleaned up either way.
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
@@ -8,7 +8,7 @@ use async_trait::async_trait;
|
|||||||
|
|
||||||
use super::{GameVersion, ModLoaderInstaller};
|
use super::{GameVersion, ModLoaderInstaller};
|
||||||
use crate::instance::models::ModLoader;
|
use crate::instance::models::ModLoader;
|
||||||
use crate::net::{forge as forge_api, HttpClient, NetError};
|
use crate::net::{HttpClient, NetError, forge as forge_api};
|
||||||
|
|
||||||
pub struct ForgeInstaller;
|
pub struct ForgeInstaller;
|
||||||
|
|
||||||
@@ -43,7 +43,23 @@ impl ModLoaderInstaller for ForgeInstaller {
|
|||||||
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?;
|
||||||
|
|
||||||
// use configured java or try to find one on PATH
|
let profile_filename = format!("forge-{game_version}-{loader_version}.json");
|
||||||
|
|
||||||
|
if forge_api::has_legacy_install_profile(&installer_jar) {
|
||||||
|
// old forge: no --installClient support, extract directly from jar
|
||||||
|
if let Err(e) = forge_api::install_forge_from_profile(
|
||||||
|
client,
|
||||||
|
&installer_jar,
|
||||||
|
meta_dir,
|
||||||
|
&profile_filename,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
let _ = tokio::fs::remove_file(&installer_jar).await;
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// modern forge: run the java installer
|
||||||
let java_path = crate::config::SETTINGS
|
let java_path = crate::config::SETTINGS
|
||||||
.paths
|
.paths
|
||||||
.effective_java_path()
|
.effective_java_path()
|
||||||
@@ -52,18 +68,18 @@ impl ModLoaderInstaller for ForgeInstaller {
|
|||||||
if let Err(e) =
|
if let Err(e) =
|
||||||
forge_api::run_forge_installer(&installer_jar, instance_dir, &java_path).await
|
forge_api::run_forge_installer(&installer_jar, instance_dir, &java_path).await
|
||||||
{
|
{
|
||||||
// still clean up even if installation failed
|
|
||||||
let _ = tokio::fs::remove_file(&installer_jar).await;
|
let _ = tokio::fs::remove_file(&installer_jar).await;
|
||||||
return Err(e);
|
return Err(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// extract the profile from what the installer just wrote to disk
|
||||||
|
save_forge_profile(instance_dir, meta_dir, game_version, loader_version)?;
|
||||||
|
}
|
||||||
|
|
||||||
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
// extract the profile from what the installer just wrote to disk
|
|
||||||
save_forge_profile(instance_dir, meta_dir, game_version, loader_version)?;
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+159
-64
@@ -46,23 +46,26 @@ pub trait ModLoaderInstaller: Send + Sync {
|
|||||||
) -> Result<(), NetError>;
|
) -> Result<(), NetError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
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 = meta_dir.join("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,
|
||||||
@@ -82,37 +85,13 @@ pub(crate) fn save_installer_profile(
|
|||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
struct InstallerVersionJson {
|
|
||||||
main_class: String,
|
|
||||||
#[serde(default)]
|
|
||||||
libraries: Vec<InstallerLib>,
|
|
||||||
}
|
|
||||||
#[derive(serde::Deserialize)]
|
|
||||||
struct InstallerLib {
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
let raw = std::fs::read(&ver_json_path)?;
|
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()
|
|
||||||
))
|
|
||||||
})?;
|
|
||||||
|
|
||||||
let libs: Vec<serde_json::Value> = ver
|
let profiles_dir = meta_dir.join("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();
|
Ok(())
|
||||||
let json_val = serde_json::json!({
|
|
||||||
"mainClass": ver.main_class,
|
|
||||||
"libraries": libs
|
|
||||||
});
|
|
||||||
|
|
||||||
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> {
|
||||||
@@ -129,31 +108,18 @@ pub fn get_installer(loader: ModLoader) -> Box<dyn ModLoaderInstaller + Send + S
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
// the factory maps every ModLoader variant to its concrete installer.
|
||||||
fn test_vanilla_factory() {
|
// covering all five arms catches a misordered match or a copy-paste typo
|
||||||
let installer = get_installer(ModLoader::Vanilla);
|
// that would route, say, NeoForge to the Forge installer.
|
||||||
assert_eq!(installer.loader_type(), ModLoader::Vanilla);
|
#[rstest::rstest]
|
||||||
}
|
#[case::vanilla(ModLoader::Vanilla)]
|
||||||
|
#[case::forge(ModLoader::Forge)]
|
||||||
#[tokio::test]
|
#[case::neoforge(ModLoader::NeoForge)]
|
||||||
async fn test_vanilla_get_versions() {
|
#[case::fabric(ModLoader::Fabric)]
|
||||||
let client = HttpClient::new();
|
#[case::quilt(ModLoader::Quilt)]
|
||||||
let installer = VanillaInstaller;
|
fn get_installer_returns_matching_loader_type(#[case] loader: ModLoader) {
|
||||||
let versions = installer.get_versions(&client, "1.20.1").await.unwrap();
|
let installer = get_installer(loader);
|
||||||
assert!(!versions.is_empty());
|
assert_eq!(installer.loader_type(), loader);
|
||||||
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("mcl_test_vanilla_install");
|
|
||||||
let meta = std::env::temp_dir().join("mcl_test_meta");
|
|
||||||
installer
|
|
||||||
.install(&client, "1.20.1", "vanilla", &tmp, &meta)
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -165,4 +131,133 @@ mod tests {
|
|||||||
assert!(!versions.is_empty());
|
assert!(!versions.is_empty());
|
||||||
assert!(versions.iter().any(|v| v.id == "1.20.1"));
|
assert!(versions.iter().any(|v| v.id == "1.20.1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn save_installer_profile_copies_raw_bytes_verbatim() {
|
||||||
|
use tempfile::TempDir;
|
||||||
|
let tmp = TempDir::new().unwrap();
|
||||||
|
let instance_dir = tmp.path().join("instance");
|
||||||
|
let meta_dir = tmp.path().join("meta");
|
||||||
|
|
||||||
|
// a synthetic installer version JSON with the modern arguments
|
||||||
|
// object - exactly the shape we used to strip.
|
||||||
|
let installer_json = br#"{
|
||||||
|
"id": "1.20.1-forge-47.2.0",
|
||||||
|
"inheritsFrom": "1.20.1",
|
||||||
|
"mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher",
|
||||||
|
"libraries": [{ "name": "net.minecraftforge:forge:47.2.0" }],
|
||||||
|
"arguments": {
|
||||||
|
"game": ["--launchTarget", "forge_client"],
|
||||||
|
"jvm": ["--add-opens", "java.base/sun.security.util=cpw.mods.securejarhandler"]
|
||||||
|
}
|
||||||
|
}"#;
|
||||||
|
|
||||||
|
let ver_dir = instance_dir
|
||||||
|
.join(".minecraft")
|
||||||
|
.join("versions")
|
||||||
|
.join("1.20.1-forge-47.2.0");
|
||||||
|
std::fs::create_dir_all(&ver_dir).unwrap();
|
||||||
|
let ver_json_path = ver_dir.join("1.20.1-forge-47.2.0.json");
|
||||||
|
std::fs::write(&ver_json_path, installer_json).unwrap();
|
||||||
|
|
||||||
|
save_installer_profile(
|
||||||
|
&instance_dir,
|
||||||
|
&meta_dir,
|
||||||
|
"1.20.1-forge-47.2.0",
|
||||||
|
"forge-1.20.1-47.2.0.json",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let saved = std::fs::read(
|
||||||
|
meta_dir
|
||||||
|
.join("loader-profiles")
|
||||||
|
.join("forge-1.20.1-47.2.0.json"),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
saved,
|
||||||
|
installer_json.to_vec(),
|
||||||
|
"saved profile should be byte-for-byte identical to installer output"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// shape-pinning test: a synthetic versionInfo from a 1.7.10 forge
|
||||||
|
// install_profile.json must deserialise as a LaunchProfile so the
|
||||||
|
// launch flow's render_args + resolve pipeline can consume it. no
|
||||||
|
// filesystem round-trip; serde_json directly on the literal bytes.
|
||||||
|
#[test]
|
||||||
|
fn legacy_forge_version_info_deserialises_as_launch_profile() {
|
||||||
|
let bytes = br#"{
|
||||||
|
"id": "1.7.10-Forge10.13.4.1614-1.7.10",
|
||||||
|
"mainClass": "net.minecraft.launchwrapper.Launch",
|
||||||
|
"minecraftArguments": "--username ${auth_player_name} --tweakClass cpw.mods.fml.common.launcher.FMLTweaker",
|
||||||
|
"libraries": [
|
||||||
|
{ "name": "net.minecraftforge:forge:10.13.4.1614", "url": "http://files.minecraftforge.net/maven/" },
|
||||||
|
{ "name": "net.minecraft:launchwrapper:1.9" }
|
||||||
|
]
|
||||||
|
}"#;
|
||||||
|
|
||||||
|
let profile: crate::launch_profile::model::LaunchProfile =
|
||||||
|
serde_json::from_slice(bytes).unwrap();
|
||||||
|
assert_eq!(profile.id, "1.7.10-Forge10.13.4.1614-1.7.10");
|
||||||
|
assert_eq!(
|
||||||
|
profile.main_class.as_deref(),
|
||||||
|
Some("net.minecraft.launchwrapper.Launch")
|
||||||
|
);
|
||||||
|
// legacy forge profiles omit inheritsFrom; the launch flow's
|
||||||
|
// implicit fallback adds it before resolve.
|
||||||
|
assert!(profile.inherits_from.is_none());
|
||||||
|
assert!(
|
||||||
|
profile
|
||||||
|
.minecraft_arguments
|
||||||
|
.as_deref()
|
||||||
|
.unwrap()
|
||||||
|
.contains("--tweakClass")
|
||||||
|
);
|
||||||
|
assert_eq!(profile.libraries.len(), 2);
|
||||||
|
assert_eq!(
|
||||||
|
profile.libraries[0].name,
|
||||||
|
"net.minecraftforge:forge:10.13.4.1614"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
profile.libraries[0].url.as_deref(),
|
||||||
|
Some("http://files.minecraftforge.net/maven/")
|
||||||
|
);
|
||||||
|
// legacy libs typically have no downloads.artifact; they resolve
|
||||||
|
// at launch time via maven_coord_to_path(name).
|
||||||
|
assert!(profile.libraries[0].downloads.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
// shape-pinning test: a synthetic upstream fabric profile (no
|
||||||
|
// inheritsFrom, no arguments, libraries with name+url) must
|
||||||
|
// deserialise as a LaunchProfile so the install path can write it
|
||||||
|
// through to disk and the launch flow can read it back.
|
||||||
|
#[test]
|
||||||
|
fn raw_fabric_profile_bytes_parse_as_launch_profile() {
|
||||||
|
let bytes = br#"{
|
||||||
|
"id": "fabric-loader-0.14.21-1.20.1",
|
||||||
|
"mainClass": "net.fabricmc.loader.impl.launch.knot.KnotClient",
|
||||||
|
"libraries": [
|
||||||
|
{ "name": "net.fabricmc:fabric-loader:0.14.21", "url": "https://maven.fabricmc.net/" },
|
||||||
|
{ "name": "net.fabricmc:intermediary:1.20.1", "url": "https://maven.fabricmc.net/" }
|
||||||
|
]
|
||||||
|
}"#;
|
||||||
|
|
||||||
|
let parsed: crate::launch_profile::model::LaunchProfile =
|
||||||
|
serde_json::from_slice(bytes).unwrap();
|
||||||
|
assert_eq!(parsed.id, "fabric-loader-0.14.21-1.20.1");
|
||||||
|
assert_eq!(
|
||||||
|
parsed.main_class.as_deref(),
|
||||||
|
Some("net.fabricmc.loader.impl.launch.knot.KnotClient")
|
||||||
|
);
|
||||||
|
// upstream Fabric profiles omit inheritsFrom; the launch flow's
|
||||||
|
// implicit fallback handles it before resolve.
|
||||||
|
assert!(parsed.inherits_from.is_none());
|
||||||
|
assert!(parsed.arguments.is_none());
|
||||||
|
assert_eq!(parsed.libraries.len(), 2);
|
||||||
|
assert_eq!(
|
||||||
|
parsed.libraries[0].url.as_deref(),
|
||||||
|
Some("https://maven.fabricmc.net/")
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,7 @@ use async_trait::async_trait;
|
|||||||
|
|
||||||
use super::{GameVersion, ModLoaderInstaller};
|
use super::{GameVersion, ModLoaderInstaller};
|
||||||
use crate::instance::models::ModLoader;
|
use crate::instance::models::ModLoader;
|
||||||
use crate::net::{neoforge as neoforge_api, HttpClient, NetError};
|
use crate::net::{HttpClient, NetError, neoforge as neoforge_api};
|
||||||
|
|
||||||
pub struct NeoForgeInstaller;
|
pub struct NeoForgeInstaller;
|
||||||
|
|
||||||
@@ -65,7 +65,11 @@ impl ModLoaderInstaller for NeoForgeInstaller {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn save_neoforge_profile(instance_dir: &Path, meta_dir: &Path, loader_version: &str) -> Result<(), NetError> {
|
fn save_neoforge_profile(
|
||||||
|
instance_dir: &Path,
|
||||||
|
meta_dir: &Path,
|
||||||
|
loader_version: &str,
|
||||||
|
) -> Result<(), NetError> {
|
||||||
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)
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use async_trait::async_trait;
|
|||||||
|
|
||||||
use super::{GameVersion, ModLoaderInstaller};
|
use super::{GameVersion, ModLoaderInstaller};
|
||||||
use crate::instance::models::ModLoader;
|
use crate::instance::models::ModLoader;
|
||||||
use crate::net::{quilt as quilt_api, HttpClient, NetError};
|
use crate::net::{HttpClient, NetError, quilt as quilt_api};
|
||||||
|
|
||||||
pub struct QuiltInstaller;
|
pub struct QuiltInstaller;
|
||||||
|
|
||||||
@@ -41,16 +41,14 @@ impl ModLoaderInstaller for QuiltInstaller {
|
|||||||
_instance_dir: &Path,
|
_instance_dir: &Path,
|
||||||
meta_dir: &Path,
|
meta_dir: &Path,
|
||||||
) -> Result<(), NetError> {
|
) -> Result<(), NetError> {
|
||||||
let profile =
|
let (profile, raw_bytes) =
|
||||||
quilt_api::fetch_quilt_profile(client, game_version, loader_version).await?;
|
quilt_api::fetch_quilt_profile_with_raw(client, game_version, loader_version).await?;
|
||||||
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,
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -8,7 +8,7 @@ use async_trait::async_trait;
|
|||||||
|
|
||||||
use super::{GameVersion, ModLoaderInstaller};
|
use super::{GameVersion, ModLoaderInstaller};
|
||||||
use crate::instance::models::ModLoader;
|
use crate::instance::models::ModLoader;
|
||||||
use crate::net::{mojang, HttpClient, NetError};
|
use crate::net::{HttpClient, NetError, mojang};
|
||||||
|
|
||||||
pub struct VanillaInstaller;
|
pub struct VanillaInstaller;
|
||||||
|
|
||||||
|
|||||||
@@ -61,12 +61,6 @@ pub fn read_log_file(path: &Path) -> Vec<String> {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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]
|
#[test]
|
||||||
fn log_dir_builds_correct_path() {
|
fn log_dir_builds_correct_path() {
|
||||||
let p = log_dir(Path::new("/instances"), "my-world");
|
let p = log_dir(Path::new("/instances"), "my-world");
|
||||||
@@ -75,67 +69,4 @@ mod tests {
|
|||||||
PathBuf::from("/instances/my-world/.minecraft/logs/launches")
|
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());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
+146
-65
@@ -115,8 +115,8 @@ impl InstanceManager {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
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?;
|
||||||
|
|
||||||
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?;
|
||||||
@@ -126,19 +126,16 @@ impl InstanceManager {
|
|||||||
.join("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 ensure meta dir exists: {}", e);
|
||||||
|
}
|
||||||
|
if let Err(e) = std::fs::write(&meta_json_path, &raw_meta_bytes) {
|
||||||
tracing::warn!("Failed to save version meta: {}", e);
|
tracing::warn!("Failed to save version meta: {}", e);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
tracing::warn!("Failed to serialize version meta: {}", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir)
|
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?;
|
||||||
.await?;
|
|
||||||
|
|
||||||
crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await?;
|
crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await?;
|
||||||
|
|
||||||
@@ -217,7 +214,8 @@ impl InstanceManager {
|
|||||||
|
|
||||||
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)
|
||||||
&& let Ok(mut config) = serde_json::from_str::<InstanceConfig>(&data) {
|
&& let Ok(mut config) = serde_json::from_str::<InstanceConfig>(&data)
|
||||||
|
{
|
||||||
config.name = new_name.to_string();
|
config.name = new_name.to_string();
|
||||||
if let Ok(json) = serde_json::to_string_pretty(&config) {
|
if let Ok(json) = serde_json::to_string_pretty(&config) {
|
||||||
let _ = std::fs::write(&config_path, json);
|
let _ = std::fs::write(&config_path, json);
|
||||||
@@ -316,55 +314,21 @@ fn validate_name(name: &str) -> Result<(), InstanceError> {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::instance::models::ModLoader;
|
use crate::instance::models::ModLoader;
|
||||||
use std::path::PathBuf;
|
use tempfile::TempDir;
|
||||||
|
|
||||||
fn test_manager() -> (InstanceManager, PathBuf) {
|
// tmp owns the temp directory; its Drop impl cleans up everything when
|
||||||
let tmp = std::env::temp_dir().join(format!("mcl_test_{}", uuid_like()));
|
// the test ends. the returned InstanceManager points at tmp.path() so
|
||||||
let meta = std::env::temp_dir().join(format!("mcl_meta_test_{}", uuid_like()));
|
// tests can join("name") off of either to refer to the same locations.
|
||||||
std::fs::create_dir_all(&tmp).ok();
|
fn test_manager() -> (InstanceManager, TempDir) {
|
||||||
std::fs::create_dir_all(&meta).ok();
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
(InstanceManager::new(tmp.clone(), meta), tmp)
|
let meta = tmp.path().join("meta");
|
||||||
|
std::fs::create_dir_all(&meta).unwrap();
|
||||||
|
(InstanceManager::new(tmp.path().to_path_buf(), meta), tmp)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn uuid_like() -> String {
|
fn dummy_config(name: &str) -> InstanceConfig {
|
||||||
format!(
|
InstanceConfig {
|
||||||
"{:x}",
|
name: name.to_string(),
|
||||||
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(),
|
game_version: "1.20.1".to_string(),
|
||||||
loader: ModLoader::Vanilla,
|
loader: ModLoader::Vanilla,
|
||||||
loader_version: None,
|
loader_version: None,
|
||||||
@@ -375,23 +339,140 @@ mod tests {
|
|||||||
memory_min: None,
|
memory_min: None,
|
||||||
jvm_args: vec![],
|
jvm_args: vec![],
|
||||||
resolution: None,
|
resolution: None,
|
||||||
};
|
}
|
||||||
|
}
|
||||||
|
|
||||||
manager.save(&config).expect("save failed");
|
#[test]
|
||||||
|
fn validate_name_accepts_safe_names() {
|
||||||
|
assert!(validate_name("my-instance").is_ok());
|
||||||
|
assert!(validate_name("test_world").is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn validate_name_rejects_empty_traversal_and_hidden() {
|
||||||
|
assert!(validate_name("").is_err());
|
||||||
|
assert!(validate_name("path/traversal").is_err());
|
||||||
|
assert!(validate_name(".hidden").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn delete_missing_instance_returns_not_found() {
|
||||||
|
let (manager, _tmp) = test_manager();
|
||||||
|
let result = manager.delete("ghost-instance");
|
||||||
|
assert!(matches!(result, Err(InstanceError::NotFound(_))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn save_then_load_all_round_trips_config() {
|
||||||
|
let (manager, tmp) = test_manager();
|
||||||
|
std::fs::create_dir_all(tmp.path().join("test-save")).unwrap();
|
||||||
|
manager.save(&dummy_config("test-save")).expect("save");
|
||||||
|
|
||||||
let all = manager.load_all();
|
let all = manager.load_all();
|
||||||
assert_eq!(all.len(), 1);
|
assert_eq!(all.len(), 1);
|
||||||
assert_eq!(all[0].name, "test-save");
|
assert_eq!(all[0].name, "test-save");
|
||||||
assert_eq!(all[0].game_version, "1.20.1");
|
assert_eq!(all[0].game_version, "1.20.1");
|
||||||
|
|
||||||
std::fs::remove_dir_all(&tmp).ok();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_load_one_not_found() {
|
fn load_all_accepts_numeric_memory() {
|
||||||
let (manager, tmp) = test_manager();
|
let (manager, tmp) = test_manager();
|
||||||
|
let instance_dir = tmp.path().join("test-memory");
|
||||||
|
std::fs::create_dir_all(&instance_dir).unwrap();
|
||||||
|
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"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_one_missing_returns_not_found() {
|
||||||
|
let (manager, _tmp) = test_manager();
|
||||||
let result = manager.load_one("ghost-instance");
|
let result = manager.load_one("ghost-instance");
|
||||||
assert!(matches!(result, Err(InstanceError::NotFound(_))));
|
assert!(matches!(result, Err(InstanceError::NotFound(_))));
|
||||||
std::fs::remove_dir_all(&tmp).ok();
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rename_moves_dir_and_updates_config_name() {
|
||||||
|
let (manager, tmp) = test_manager();
|
||||||
|
let old_dir = tmp.path().join("old-name");
|
||||||
|
std::fs::create_dir_all(&old_dir).unwrap();
|
||||||
|
manager.save(&dummy_config("old-name")).expect("save");
|
||||||
|
|
||||||
|
manager.rename("old-name", "new-name").expect("rename");
|
||||||
|
|
||||||
|
assert!(!old_dir.exists(), "old dir should be gone");
|
||||||
|
let new_dir = tmp.path().join("new-name");
|
||||||
|
assert!(new_dir.exists(), "new dir should exist");
|
||||||
|
let reloaded = manager.load_one("new-name").expect("load_one new-name");
|
||||||
|
assert_eq!(reloaded.name, "new-name");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rename_to_same_name_is_noop() {
|
||||||
|
let (manager, tmp) = test_manager();
|
||||||
|
let dir = tmp.path().join("same");
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
manager.save(&dummy_config("same")).expect("save");
|
||||||
|
manager.rename("same", "same").expect("noop rename");
|
||||||
|
assert!(dir.exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rename_empty_target_rejects() {
|
||||||
|
let (manager, tmp) = test_manager();
|
||||||
|
std::fs::create_dir_all(tmp.path().join("orig")).unwrap();
|
||||||
|
manager.save(&dummy_config("orig")).expect("save");
|
||||||
|
let err = manager.rename("orig", " ").unwrap_err();
|
||||||
|
assert!(matches!(err, InstanceError::InvalidName(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rename_missing_source_errors() {
|
||||||
|
let (manager, _tmp) = test_manager();
|
||||||
|
let err = manager.rename("ghost", "anything").unwrap_err();
|
||||||
|
assert!(matches!(err, InstanceError::NotFound(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rename_target_exists_errors() {
|
||||||
|
let (manager, tmp) = test_manager();
|
||||||
|
std::fs::create_dir_all(tmp.path().join("source")).unwrap();
|
||||||
|
std::fs::create_dir_all(tmp.path().join("collision")).unwrap();
|
||||||
|
manager.save(&dummy_config("source")).expect("save src");
|
||||||
|
manager.save(&dummy_config("collision")).expect("save dst");
|
||||||
|
let err = manager.rename("source", "collision").unwrap_err();
|
||||||
|
assert!(matches!(err, InstanceError::AlreadyExists(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn touch_last_played_updates_field() {
|
||||||
|
let (manager, tmp) = test_manager();
|
||||||
|
std::fs::create_dir_all(tmp.path().join("ticker")).unwrap();
|
||||||
|
manager.save(&dummy_config("ticker")).expect("save");
|
||||||
|
assert!(manager.load_one("ticker").unwrap().last_played.is_none());
|
||||||
|
|
||||||
|
manager.touch_last_played("ticker").expect("touch");
|
||||||
|
let reloaded = manager.load_one("ticker").unwrap();
|
||||||
|
let stamp = reloaded.last_played.expect("last_played should be Some now");
|
||||||
|
let age = chrono::Utc::now() - stamp;
|
||||||
|
assert!(
|
||||||
|
age.num_seconds().abs() < 5,
|
||||||
|
"last_played should be roughly now, got age {age:?}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+9
-3
@@ -10,8 +10,14 @@ pub mod manager;
|
|||||||
pub mod models;
|
pub mod models;
|
||||||
pub mod screenshots;
|
pub mod screenshots;
|
||||||
|
|
||||||
pub use content::{scan_mods, toggle_entry, ContentEntry, scan_resource_packs, scan_shaders, scan_worlds};
|
pub use content::{
|
||||||
|
ContentEntry, toggle_entry,
|
||||||
|
scan_mods, scan_one_mod,
|
||||||
|
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::{get_installer, GameVersion, ModLoaderInstaller, VanillaInstaller};
|
pub use loader::{GameVersion, ModLoaderInstaller, VanillaInstaller, get_installer};
|
||||||
pub use manager::{InstanceError, InstanceManager};
|
pub use manager::{InstanceError, InstanceManager};
|
||||||
pub use models::{InstanceConfig, ModLoader};
|
pub use models::{InstanceConfig, ModLoader, normalize_memory_value};
|
||||||
+132
-1
@@ -3,6 +3,7 @@
|
|||||||
|
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_json::Value;
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
@@ -34,20 +35,96 @@ pub struct InstanceConfig {
|
|||||||
pub loader: ModLoader,
|
pub loader: ModLoader,
|
||||||
pub loader_version: Option<String>,
|
pub loader_version: Option<String>,
|
||||||
pub created: DateTime<Utc>,
|
pub created: DateTime<Utc>,
|
||||||
|
#[serde(default)]
|
||||||
pub last_played: Option<DateTime<Utc>>,
|
pub last_played: Option<DateTime<Utc>>,
|
||||||
|
#[serde(default)]
|
||||||
pub java_path: Option<String>,
|
pub java_path: Option<String>,
|
||||||
|
#[serde(default, deserialize_with = "deserialize_optional_memory")]
|
||||||
pub memory_max: Option<String>,
|
pub memory_max: Option<String>,
|
||||||
|
#[serde(default, deserialize_with = "deserialize_optional_memory")]
|
||||||
pub memory_min: Option<String>,
|
pub memory_min: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
pub jvm_args: Vec<String>,
|
pub jvm_args: Vec<String>,
|
||||||
|
#[serde(default)]
|
||||||
pub resolution: Option<(u32, u32)>,
|
pub resolution: Option<(u32, u32)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn normalize_memory_value(raw: &str) -> Option<String> {
|
||||||
|
let trimmed = raw.trim();
|
||||||
|
if trimmed.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let (digits, suffix) = match trimmed.chars().last() {
|
||||||
|
Some(c) if c.is_ascii_alphabetic() => (&trimmed[..trimmed.len() - c.len_utf8()], Some(c)),
|
||||||
|
Some(_) => (trimmed, None),
|
||||||
|
None => return None,
|
||||||
|
};
|
||||||
|
|
||||||
|
if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let value = digits.parse::<u64>().ok()?;
|
||||||
|
if value == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
match suffix.map(|c| c.to_ascii_uppercase()) {
|
||||||
|
Some(unit @ ('K' | 'M' | 'G')) => Some(format!("{value}{unit}")),
|
||||||
|
Some(_) => None,
|
||||||
|
None => memory_number_to_string(value),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize_optional_memory<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
|
||||||
|
where
|
||||||
|
D: serde::Deserializer<'de>,
|
||||||
|
{
|
||||||
|
let value = Option::<Value>::deserialize(deserializer)?;
|
||||||
|
match value {
|
||||||
|
None | Some(Value::Null) => Ok(None),
|
||||||
|
Some(Value::String(raw)) => Ok(normalize_memory_value(&raw)),
|
||||||
|
Some(Value::Number(number)) => {
|
||||||
|
let number = if let Some(value) = number.as_u64() {
|
||||||
|
value
|
||||||
|
} else if let Some(value) = number.as_i64() {
|
||||||
|
let Ok(value) = u64::try_from(value) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
value
|
||||||
|
} else {
|
||||||
|
let Some(value) = number.as_f64() else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
if !value.is_finite() || value.fract() != 0.0 || value < 0.0 {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
value as u64
|
||||||
|
};
|
||||||
|
Ok(memory_number_to_string(number))
|
||||||
|
}
|
||||||
|
Some(_) => Ok(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn memory_number_to_string(value: u64) -> Option<String> {
|
||||||
|
if value == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if value < 128 {
|
||||||
|
Some(format!("{value}G"))
|
||||||
|
} else {
|
||||||
|
Some(format!("{value}M"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_instance_config_roundtrip() {
|
fn instance_config_roundtrips_through_json() {
|
||||||
let config = InstanceConfig {
|
let config = InstanceConfig {
|
||||||
name: "test".to_string(),
|
name: "test".to_string(),
|
||||||
game_version: "1.20.1".to_string(),
|
game_version: "1.20.1".to_string(),
|
||||||
@@ -68,4 +145,58 @@ mod tests {
|
|||||||
assert_eq!(parsed.loader, config.loader);
|
assert_eq!(parsed.loader, config.loader);
|
||||||
assert_eq!(parsed.resolution, config.resolution);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -46,87 +46,3 @@ pub fn scan_screenshots(instances_dir: &Path, instance_name: &str) -> Vec<Screen
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -76,9 +76,11 @@ mod tests {
|
|||||||
}
|
}
|
||||||
let lines = get_all(name);
|
let lines = get_all(name);
|
||||||
assert_eq!(lines.len(), MAX_LINES);
|
assert_eq!(lines.len(), MAX_LINES);
|
||||||
assert!(lines
|
assert!(
|
||||||
|
lines
|
||||||
.last()
|
.last()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.contains(&format!("{}", MAX_LINES + 99)));
|
.contains(&format!("{}", MAX_LINES + 99))
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
// primitives for parsing, merging, and rendering mojang-format launch
|
||||||
|
// profiles. consumed by the vanilla launcher and the loader install paths
|
||||||
|
// (forge/neoforge/fabric/quilt) - anything that reads a mojang-style
|
||||||
|
// version JSON.
|
||||||
|
|
||||||
|
pub mod model;
|
||||||
|
pub mod render;
|
||||||
|
pub mod resolve;
|
||||||
|
pub mod rules;
|
||||||
|
pub mod system;
|
||||||
|
pub mod templates;
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
// mojang-format launch profile types. mirrors the on-disk JSON schema
|
||||||
|
// used by vanilla versions, forge installer output, neoforge installer
|
||||||
|
// output, fabric profiles, and quilt profiles. parsing is lossless for
|
||||||
|
// the fields we care about; unknown fields are silently dropped (serde
|
||||||
|
// default behavior) - which is fine because we write upstream JSON
|
||||||
|
// byte-for-byte on the install side.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use super::rules::Rule;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct LaunchProfile {
|
||||||
|
pub id: String,
|
||||||
|
pub inherits_from: Option<String>,
|
||||||
|
pub main_class: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub libraries: Vec<Library>,
|
||||||
|
pub arguments: Option<Arguments>,
|
||||||
|
pub minecraft_arguments: Option<String>,
|
||||||
|
pub asset_index: Option<AssetIndex>,
|
||||||
|
pub assets: Option<String>,
|
||||||
|
pub java_version: Option<JavaVersion>,
|
||||||
|
pub downloads: Option<VersionDownloads>,
|
||||||
|
pub release_time: Option<String>,
|
||||||
|
pub time: Option<String>,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
pub type_: Option<String>,
|
||||||
|
// present only in rmcl <= 0.3.0's stripped loader-profile shape.
|
||||||
|
// we deserialize it so the launch-time legacy-detection predicate
|
||||||
|
// can confirm "this really is our old format, not an upstream
|
||||||
|
// profile that happens to omit arguments". skipped on serialize so
|
||||||
|
// we never propagate this field outward.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub game_arguments: Option<Vec<String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize)]
|
||||||
|
pub struct Arguments {
|
||||||
|
#[serde(default)]
|
||||||
|
pub game: Vec<Argument>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub jvm: Vec<Argument>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
#[serde(untagged)]
|
||||||
|
pub enum Argument {
|
||||||
|
Literal(String),
|
||||||
|
Conditional {
|
||||||
|
rules: Vec<Rule>,
|
||||||
|
value: ArgumentValue,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
#[serde(untagged)]
|
||||||
|
pub enum ArgumentValue {
|
||||||
|
Single(String),
|
||||||
|
Multiple(Vec<String>),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
pub struct Library {
|
||||||
|
pub name: String,
|
||||||
|
pub downloads: Option<LibraryDownloads>,
|
||||||
|
pub rules: Option<Vec<Rule>>,
|
||||||
|
pub url: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
pub struct LibraryDownloads {
|
||||||
|
pub artifact: Option<Artifact>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
pub struct Artifact {
|
||||||
|
pub url: String,
|
||||||
|
pub path: String,
|
||||||
|
pub sha1: String,
|
||||||
|
pub size: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
pub struct AssetIndex {
|
||||||
|
pub id: String,
|
||||||
|
pub url: String,
|
||||||
|
pub sha1: String,
|
||||||
|
pub size: Option<u64>,
|
||||||
|
pub total_size: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct JavaVersion {
|
||||||
|
pub component: Option<String>,
|
||||||
|
pub major_version: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
pub struct VersionDownloads {
|
||||||
|
pub client: Download,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
pub struct Download {
|
||||||
|
pub url: String,
|
||||||
|
pub sha1: String,
|
||||||
|
pub size: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::launch_profile::rules::RuleAction;
|
||||||
|
|
||||||
|
const MODERN_FIXTURE: &str = r#"{
|
||||||
|
"id": "1.20.1",
|
||||||
|
"type": "release",
|
||||||
|
"mainClass": "net.minecraft.client.main.Main",
|
||||||
|
"assetIndex": {
|
||||||
|
"id": "5",
|
||||||
|
"url": "https://example.invalid/5.json",
|
||||||
|
"sha1": "0000000000000000000000000000000000000000"
|
||||||
|
},
|
||||||
|
"javaVersion": {
|
||||||
|
"component": "java-runtime-gamma",
|
||||||
|
"majorVersion": 17
|
||||||
|
},
|
||||||
|
"libraries": [
|
||||||
|
{
|
||||||
|
"name": "org.lwjgl:lwjgl:3.3.1",
|
||||||
|
"downloads": {
|
||||||
|
"artifact": {
|
||||||
|
"url": "https://example.invalid/lwjgl.jar",
|
||||||
|
"path": "org/lwjgl/lwjgl/3.3.1/lwjgl-3.3.1.jar",
|
||||||
|
"sha1": "1111111111111111111111111111111111111111",
|
||||||
|
"size": 100
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"rules": [
|
||||||
|
{ "action": "allow", "os": { "name": "linux" } }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"arguments": {
|
||||||
|
"game": [
|
||||||
|
"--username", "${auth_player_name}",
|
||||||
|
{
|
||||||
|
"rules": [{ "action": "allow", "features": { "is_demo_user": true } }],
|
||||||
|
"value": "--demo"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"jvm": [
|
||||||
|
"-Djava.library.path=${natives_directory}",
|
||||||
|
{
|
||||||
|
"rules": [{ "action": "allow", "os": { "name": "osx" } }],
|
||||||
|
"value": ["-XstartOnFirstThread"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}"#;
|
||||||
|
|
||||||
|
const LEGACY_FIXTURE: &str = r#"{
|
||||||
|
"id": "1.7.10",
|
||||||
|
"type": "release",
|
||||||
|
"mainClass": "net.minecraft.client.main.Main",
|
||||||
|
"minecraftArguments": "--username ${auth_player_name} --version ${version_name} --gameDir ${game_directory}",
|
||||||
|
"assetIndex": {
|
||||||
|
"id": "1.7.10",
|
||||||
|
"url": "https://example.invalid/1.7.10.json",
|
||||||
|
"sha1": "0000000000000000000000000000000000000000"
|
||||||
|
},
|
||||||
|
"libraries": []
|
||||||
|
}"#;
|
||||||
|
|
||||||
|
const LOADER_FIXTURE: &str = r#"{
|
||||||
|
"id": "1.20.1-forge-47.2.0",
|
||||||
|
"inheritsFrom": "1.20.1",
|
||||||
|
"mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher",
|
||||||
|
"libraries": [
|
||||||
|
{ "name": "net.minecraftforge:forge:47.2.0" }
|
||||||
|
],
|
||||||
|
"arguments": {
|
||||||
|
"game": ["--launchTarget", "forge_client"],
|
||||||
|
"jvm": [
|
||||||
|
"--add-opens", "java.base/sun.security.util=cpw.mods.securejarhandler",
|
||||||
|
"-DlibraryDirectory=${library_directory}"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}"#;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_modern_arguments_object() {
|
||||||
|
let profile: LaunchProfile = serde_json::from_str(MODERN_FIXTURE).unwrap();
|
||||||
|
assert_eq!(profile.id, "1.20.1");
|
||||||
|
assert_eq!(
|
||||||
|
profile.main_class.as_deref(),
|
||||||
|
Some("net.minecraft.client.main.Main")
|
||||||
|
);
|
||||||
|
assert!(profile.inherits_from.is_none());
|
||||||
|
assert!(profile.minecraft_arguments.is_none());
|
||||||
|
|
||||||
|
let args = profile.arguments.as_ref().expect("arguments present");
|
||||||
|
assert_eq!(args.game.len(), 3);
|
||||||
|
assert_eq!(args.jvm.len(), 2);
|
||||||
|
|
||||||
|
// first game arg should be a literal "--username"
|
||||||
|
match &args.game[0] {
|
||||||
|
Argument::Literal(s) => assert_eq!(s, "--username"),
|
||||||
|
_ => panic!("expected literal"),
|
||||||
|
}
|
||||||
|
// third game arg should be a conditional with a single-string value
|
||||||
|
match &args.game[2] {
|
||||||
|
Argument::Conditional { rules, value } => {
|
||||||
|
assert_eq!(rules.len(), 1);
|
||||||
|
assert_eq!(rules[0].action, RuleAction::Allow);
|
||||||
|
assert!(matches!(value, ArgumentValue::Single(_)));
|
||||||
|
}
|
||||||
|
_ => panic!("expected conditional"),
|
||||||
|
}
|
||||||
|
// second jvm arg should be a conditional with a multi-string value
|
||||||
|
match &args.jvm[1] {
|
||||||
|
Argument::Conditional { value, .. } => {
|
||||||
|
assert!(matches!(value, ArgumentValue::Multiple(_)));
|
||||||
|
}
|
||||||
|
_ => panic!("expected conditional"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_legacy_minecraft_arguments_string() {
|
||||||
|
let profile: LaunchProfile = serde_json::from_str(LEGACY_FIXTURE).unwrap();
|
||||||
|
assert_eq!(profile.id, "1.7.10");
|
||||||
|
assert!(profile.arguments.is_none());
|
||||||
|
assert!(
|
||||||
|
profile
|
||||||
|
.minecraft_arguments
|
||||||
|
.as_deref()
|
||||||
|
.unwrap()
|
||||||
|
.contains("${version_name}")
|
||||||
|
);
|
||||||
|
assert!(profile.libraries.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_loader_profile_with_inherits_from() {
|
||||||
|
let profile: LaunchProfile = serde_json::from_str(LOADER_FIXTURE).unwrap();
|
||||||
|
assert_eq!(profile.id, "1.20.1-forge-47.2.0");
|
||||||
|
assert_eq!(profile.inherits_from.as_deref(), Some("1.20.1"));
|
||||||
|
assert!(profile.asset_index.is_none()); // inherited from parent
|
||||||
|
let args = profile.arguments.as_ref().unwrap();
|
||||||
|
assert_eq!(args.game.len(), 2);
|
||||||
|
assert_eq!(args.jvm.len(), 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn modern_profile_round_trips() {
|
||||||
|
let original: LaunchProfile = serde_json::from_str(MODERN_FIXTURE).unwrap();
|
||||||
|
let serialized = serde_json::to_string(&original).unwrap();
|
||||||
|
let reparsed: LaunchProfile = serde_json::from_str(&serialized).unwrap();
|
||||||
|
assert_eq!(original, reparsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn loader_profile_round_trips() {
|
||||||
|
let original: LaunchProfile = serde_json::from_str(LOADER_FIXTURE).unwrap();
|
||||||
|
let serialized = serde_json::to_string(&original).unwrap();
|
||||||
|
let reparsed: LaunchProfile = serde_json::from_str(&serialized).unwrap();
|
||||||
|
assert_eq!(original, reparsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_profile_round_trips() {
|
||||||
|
let original: LaunchProfile = serde_json::from_str(LEGACY_FIXTURE).unwrap();
|
||||||
|
let serialized = serde_json::to_string(&original).unwrap();
|
||||||
|
let reparsed: LaunchProfile = serde_json::from_str(&serialized).unwrap();
|
||||||
|
assert_eq!(original, reparsed);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,357 @@
|
|||||||
|
// renders a parsed launch profile into final argv-style lists for the JVM
|
||||||
|
// and the game. resolves conditional argument shapes (`{rules, value}`),
|
||||||
|
// filters them through the rule evaluator, and substitutes mojang template
|
||||||
|
// variables. legacy `minecraftArguments` strings are tokenised on whitespace
|
||||||
|
// and treated as a list of game args. pure function; no I/O.
|
||||||
|
|
||||||
|
use super::model::{Argument, ArgumentValue, LaunchProfile};
|
||||||
|
use super::rules::{RuleContext, evaluate};
|
||||||
|
use super::templates::{TemplateContext, substitute};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct RenderedArgs {
|
||||||
|
pub jvm: Vec<String>,
|
||||||
|
pub main_class: String,
|
||||||
|
pub game: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum RenderError {
|
||||||
|
#[error("launch profile is missing a main class")]
|
||||||
|
MissingMainClass,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn render_args(
|
||||||
|
profile: &LaunchProfile,
|
||||||
|
rule_ctx: &RuleContext,
|
||||||
|
template_ctx: &TemplateContext,
|
||||||
|
) -> Result<RenderedArgs, RenderError> {
|
||||||
|
let main_class = profile
|
||||||
|
.main_class
|
||||||
|
.clone()
|
||||||
|
.ok_or(RenderError::MissingMainClass)?;
|
||||||
|
|
||||||
|
let mut jvm = Vec::new();
|
||||||
|
let mut game = Vec::new();
|
||||||
|
|
||||||
|
if let Some(args) = &profile.arguments {
|
||||||
|
for arg in &args.jvm {
|
||||||
|
push_argument(arg, rule_ctx, template_ctx, &mut jvm);
|
||||||
|
}
|
||||||
|
for arg in &args.game {
|
||||||
|
push_argument(arg, rule_ctx, template_ctx, &mut game);
|
||||||
|
}
|
||||||
|
} else if let Some(legacy) = &profile.minecraft_arguments {
|
||||||
|
for token in legacy.split_whitespace() {
|
||||||
|
game.push(substitute(token, template_ctx));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(RenderedArgs {
|
||||||
|
jvm,
|
||||||
|
main_class,
|
||||||
|
game,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_argument(
|
||||||
|
arg: &Argument,
|
||||||
|
rule_ctx: &RuleContext,
|
||||||
|
template_ctx: &TemplateContext,
|
||||||
|
out: &mut Vec<String>,
|
||||||
|
) {
|
||||||
|
match arg {
|
||||||
|
Argument::Literal(s) => out.push(substitute(s, template_ctx)),
|
||||||
|
Argument::Conditional { rules, value } => {
|
||||||
|
if !evaluate(rules, rule_ctx) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match value {
|
||||||
|
ArgumentValue::Single(s) => out.push(substitute(s, template_ctx)),
|
||||||
|
ArgumentValue::Multiple(items) => {
|
||||||
|
for s in items {
|
||||||
|
out.push(substitute(s, template_ctx));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::launch_profile::model::Arguments;
|
||||||
|
use crate::launch_profile::rules::{FeatureSet, OsCondition, Rule, RuleAction};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
// owns the path buffers + FeatureSet so each test just calls
|
||||||
|
// fx.template_ctx() and fx.rule_ctx() instead of declaring four PathBufs
|
||||||
|
// and a RuleContext inline. all tests use linux/x86_64; if a test needs
|
||||||
|
// a different OS it sets it explicitly.
|
||||||
|
struct Fixture {
|
||||||
|
lib: PathBuf,
|
||||||
|
nat: PathBuf,
|
||||||
|
game: PathBuf,
|
||||||
|
assets: PathBuf,
|
||||||
|
features: FeatureSet,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Fixture {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
lib: PathBuf::from("/m/libraries"),
|
||||||
|
nat: PathBuf::from("/m/natives"),
|
||||||
|
game: PathBuf::from("/i/.minecraft"),
|
||||||
|
assets: PathBuf::from("/m/assets"),
|
||||||
|
features: FeatureSet::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn template_ctx(&self) -> TemplateContext<'_> {
|
||||||
|
TemplateContext {
|
||||||
|
library_directory: &self.lib,
|
||||||
|
classpath_separator: ":",
|
||||||
|
version_name: "1.20.1",
|
||||||
|
version_type: "release",
|
||||||
|
natives_directory: &self.nat,
|
||||||
|
classpath: "a.jar:b.jar",
|
||||||
|
game_directory: &self.game,
|
||||||
|
assets_root: &self.assets,
|
||||||
|
assets_index_name: "5",
|
||||||
|
auth_player_name: "Player",
|
||||||
|
auth_uuid: "00000000-0000-0000-0000-000000000000",
|
||||||
|
auth_access_token: "token",
|
||||||
|
auth_xuid: "0",
|
||||||
|
user_type: "msa",
|
||||||
|
user_properties: "{}",
|
||||||
|
launcher_name: "rmcl",
|
||||||
|
launcher_version: "0.3.0",
|
||||||
|
clientid: "0",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rule_ctx(&self) -> RuleContext<'_> {
|
||||||
|
RuleContext {
|
||||||
|
os_name: "linux",
|
||||||
|
os_version: "6.0",
|
||||||
|
arch: "x86_64",
|
||||||
|
features: &self.features,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn minimal_profile() -> LaunchProfile {
|
||||||
|
LaunchProfile {
|
||||||
|
id: "test".into(),
|
||||||
|
main_class: Some("net.test.Main".into()),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_minecraft_arguments_render_into_game() {
|
||||||
|
let fx = Fixture::new();
|
||||||
|
let mut profile = minimal_profile();
|
||||||
|
profile.minecraft_arguments =
|
||||||
|
Some("--username ${auth_player_name} --version ${version_name}".into());
|
||||||
|
|
||||||
|
let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap();
|
||||||
|
assert_eq!(rendered.main_class, "net.test.Main");
|
||||||
|
assert!(rendered.jvm.is_empty());
|
||||||
|
assert_eq!(
|
||||||
|
rendered.game,
|
||||||
|
vec!["--username", "Player", "--version", "1.20.1"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn modern_arguments_render_with_literals_and_substitutions() {
|
||||||
|
let fx = Fixture::new();
|
||||||
|
let mut profile = minimal_profile();
|
||||||
|
profile.arguments = Some(Arguments {
|
||||||
|
game: vec![
|
||||||
|
Argument::Literal("--username".into()),
|
||||||
|
Argument::Literal("${auth_player_name}".into()),
|
||||||
|
],
|
||||||
|
jvm: vec![Argument::Literal(
|
||||||
|
"-Djava.library.path=${natives_directory}".into(),
|
||||||
|
)],
|
||||||
|
});
|
||||||
|
|
||||||
|
let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap();
|
||||||
|
assert_eq!(rendered.game, vec!["--username", "Player"]);
|
||||||
|
assert_eq!(rendered.jvm, vec!["-Djava.library.path=/m/natives"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn conditional_argument_with_single_value_is_filtered_by_os_rule() {
|
||||||
|
let fx = Fixture::new();
|
||||||
|
let osx_only = Argument::Conditional {
|
||||||
|
rules: vec![Rule {
|
||||||
|
action: RuleAction::Allow,
|
||||||
|
os: Some(OsCondition {
|
||||||
|
name: Some("osx".into()),
|
||||||
|
arch: None,
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
features: None,
|
||||||
|
}],
|
||||||
|
value: ArgumentValue::Single("-XstartOnFirstThread".into()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut profile = minimal_profile();
|
||||||
|
profile.arguments = Some(Arguments {
|
||||||
|
game: Vec::new(),
|
||||||
|
jvm: vec![osx_only],
|
||||||
|
});
|
||||||
|
|
||||||
|
let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap();
|
||||||
|
assert!(
|
||||||
|
rendered.jvm.is_empty(),
|
||||||
|
"osx-only arg should be skipped on linux"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn conditional_argument_with_multiple_value_pushes_all() {
|
||||||
|
let fx = Fixture::new();
|
||||||
|
let linux_arg = Argument::Conditional {
|
||||||
|
rules: vec![Rule {
|
||||||
|
action: RuleAction::Allow,
|
||||||
|
os: Some(OsCondition {
|
||||||
|
name: Some("linux".into()),
|
||||||
|
arch: None,
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
features: None,
|
||||||
|
}],
|
||||||
|
value: ArgumentValue::Multiple(vec![
|
||||||
|
"--add-opens".into(),
|
||||||
|
"java.base/sun.security.util=ALL-UNNAMED".into(),
|
||||||
|
]),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut profile = minimal_profile();
|
||||||
|
profile.arguments = Some(Arguments {
|
||||||
|
game: Vec::new(),
|
||||||
|
jvm: vec![linux_arg],
|
||||||
|
});
|
||||||
|
|
||||||
|
let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
rendered.jvm,
|
||||||
|
vec!["--add-opens", "java.base/sun.security.util=ALL-UNNAMED"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_main_class_returns_error() {
|
||||||
|
let fx = Fixture::new();
|
||||||
|
let mut profile = minimal_profile();
|
||||||
|
profile.main_class = None;
|
||||||
|
|
||||||
|
let result = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx());
|
||||||
|
assert!(matches!(result, Err(RenderError::MissingMainClass)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn end_to_end_resolve_then_render_modern_forge_shape() {
|
||||||
|
// exercises the full pipeline: load a synthetic vanilla profile
|
||||||
|
// from disk, load a synthetic loader profile with inheritsFrom,
|
||||||
|
// resolve the chain, then render args. catches integration bugs
|
||||||
|
// that unit tests of each layer would miss.
|
||||||
|
use crate::launch_profile::resolve;
|
||||||
|
use tempfile::TempDir;
|
||||||
|
|
||||||
|
let tmp = TempDir::new().unwrap();
|
||||||
|
let vanilla_path = tmp.path().join("versions").join("1.20.1").join("meta.json");
|
||||||
|
std::fs::create_dir_all(vanilla_path.parent().unwrap()).unwrap();
|
||||||
|
let vanilla_json = br#"{
|
||||||
|
"id": "1.20.1",
|
||||||
|
"mainClass": "net.minecraft.client.main.Main",
|
||||||
|
"libraries": [
|
||||||
|
{
|
||||||
|
"name": "org.lwjgl:lwjgl:3.3.1",
|
||||||
|
"downloads": {
|
||||||
|
"artifact": {
|
||||||
|
"url": "https://example.invalid/lwjgl.jar",
|
||||||
|
"path": "org/lwjgl/lwjgl/3.3.1/lwjgl-3.3.1.jar",
|
||||||
|
"sha1": "1111111111111111111111111111111111111111",
|
||||||
|
"size": 100
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"arguments": {
|
||||||
|
"game": ["--username", "${auth_player_name}", "--version", "${version_name}"],
|
||||||
|
"jvm": ["-Djava.library.path=${natives_directory}"]
|
||||||
|
}
|
||||||
|
}"#;
|
||||||
|
std::fs::write(&vanilla_path, vanilla_json).unwrap();
|
||||||
|
|
||||||
|
let loader_json = r#"{
|
||||||
|
"id": "1.20.1-forge-47.2.0",
|
||||||
|
"inheritsFrom": "1.20.1",
|
||||||
|
"mainClass": "cpw.mods.bootstraplauncher.BootstrapLauncher",
|
||||||
|
"libraries": [
|
||||||
|
{ "name": "net.minecraftforge:forge:47.2.0" }
|
||||||
|
],
|
||||||
|
"arguments": {
|
||||||
|
"game": ["--launchTarget", "forge_client"],
|
||||||
|
"jvm": [
|
||||||
|
"--add-opens", "java.base/sun.security.util=cpw.mods.securejarhandler"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}"#;
|
||||||
|
let loader_profile: LaunchProfile = serde_json::from_str(loader_json).unwrap();
|
||||||
|
|
||||||
|
let merged = resolve::resolve(loader_profile, tmp.path()).await.unwrap();
|
||||||
|
|
||||||
|
let fx = Fixture::new();
|
||||||
|
let rendered = render_args(&merged, &fx.rule_ctx(), &fx.template_ctx()).unwrap();
|
||||||
|
|
||||||
|
// child main_class wins after merge
|
||||||
|
assert_eq!(
|
||||||
|
rendered.main_class,
|
||||||
|
"cpw.mods.bootstraplauncher.BootstrapLauncher"
|
||||||
|
);
|
||||||
|
// game args: parent first then child
|
||||||
|
assert_eq!(
|
||||||
|
rendered.game,
|
||||||
|
vec![
|
||||||
|
"--username",
|
||||||
|
"Player",
|
||||||
|
"--version",
|
||||||
|
"1.20.1",
|
||||||
|
"--launchTarget",
|
||||||
|
"forge_client"
|
||||||
|
]
|
||||||
|
);
|
||||||
|
// jvm args: parent first then child
|
||||||
|
assert_eq!(
|
||||||
|
rendered.jvm,
|
||||||
|
vec![
|
||||||
|
"-Djava.library.path=/m/natives",
|
||||||
|
"--add-opens",
|
||||||
|
"java.base/sun.security.util=cpw.mods.securejarhandler"
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn modern_arguments_takes_precedence_over_legacy_field() {
|
||||||
|
// a profile that somehow has both arguments and minecraft_arguments
|
||||||
|
// should use arguments only (legacy is fallback).
|
||||||
|
let fx = Fixture::new();
|
||||||
|
let mut profile = minimal_profile();
|
||||||
|
profile.arguments = Some(Arguments {
|
||||||
|
game: vec![Argument::Literal("--from-arguments".into())],
|
||||||
|
jvm: Vec::new(),
|
||||||
|
});
|
||||||
|
profile.minecraft_arguments = Some("--from-legacy".into());
|
||||||
|
|
||||||
|
let rendered = render_args(&profile, &fx.rule_ctx(), &fx.template_ctx()).unwrap();
|
||||||
|
assert_eq!(rendered.game, vec!["--from-arguments"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,565 @@
|
|||||||
|
// resolves the `inheritsFrom` chain of a parsed `LaunchProfile`. mojang's
|
||||||
|
// version JSON allows a profile to inherit from another profile by id; the
|
||||||
|
// loaders (forge / neoforge / fabric / quilt) use this to layer their
|
||||||
|
// additions on top of a vanilla base. this module walks the chain and
|
||||||
|
// returns a single flat profile.
|
||||||
|
//
|
||||||
|
// merge semantics (per the mojang launcher and the major third-party
|
||||||
|
// launchers that interoperate with it):
|
||||||
|
// - scalar fields: child wins if Some, else parent.
|
||||||
|
// - libraries and arguments: parent ++ child (parent first). child
|
||||||
|
// entries are appended after parent's.
|
||||||
|
// - merge_into preserves parent's inherits_from so resolve() can keep
|
||||||
|
// walking; resolve() clears the final result's inherits_from after
|
||||||
|
// the loop exits.
|
||||||
|
//
|
||||||
|
// pure function `merge_into` handles the field-by-field merge math.
|
||||||
|
// async `resolve` does the chain walking with cycle detection and a depth
|
||||||
|
// cap. tests cover both layers independently.
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use super::model::{Arguments, LaunchProfile};
|
||||||
|
|
||||||
|
const MAX_INHERITANCE_DEPTH: usize = 8;
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum ResolveError {
|
||||||
|
#[error("parent profile not found at {0}")]
|
||||||
|
ParentNotFound(String),
|
||||||
|
#[error("failed to parse parent profile {0}: {1}")]
|
||||||
|
ParseError(String, String),
|
||||||
|
#[error("circular inheritance detected: {0} appears more than once in the chain")]
|
||||||
|
CircularInheritance(String),
|
||||||
|
#[error("inheritance chain exceeded {0} levels")]
|
||||||
|
DepthExceeded(usize),
|
||||||
|
#[error("I/O error reading parent profile: {0}")]
|
||||||
|
Io(#[from] std::io::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
// merges `child` on top of `parent`. child takes precedence for scalar
|
||||||
|
// fields. for libraries and arguments, child entries are appended after
|
||||||
|
// parent's. `id` is taken from child. `inherits_from` is taken from
|
||||||
|
// parent (so resolve() can keep walking the chain - resolve() clears it
|
||||||
|
// to None after the final iteration).
|
||||||
|
pub fn merge_into(child: LaunchProfile, parent: LaunchProfile) -> LaunchProfile {
|
||||||
|
LaunchProfile {
|
||||||
|
id: child.id,
|
||||||
|
inherits_from: parent.inherits_from,
|
||||||
|
main_class: child.main_class.or(parent.main_class),
|
||||||
|
libraries: merge_libraries(child.libraries, parent.libraries),
|
||||||
|
arguments: merge_arguments(child.arguments, parent.arguments),
|
||||||
|
minecraft_arguments: child.minecraft_arguments.or(parent.minecraft_arguments),
|
||||||
|
asset_index: child.asset_index.or(parent.asset_index),
|
||||||
|
assets: child.assets.or(parent.assets),
|
||||||
|
java_version: child.java_version.or(parent.java_version),
|
||||||
|
downloads: child.downloads.or(parent.downloads),
|
||||||
|
release_time: child.release_time.or(parent.release_time),
|
||||||
|
time: child.time.or(parent.time),
|
||||||
|
game_arguments: None,
|
||||||
|
type_: child.type_.or(parent.type_),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// extracts the `group:artifact` portion of a maven coordinate, dropping
|
||||||
|
// version and any classifier. used as the dedup key when merging library
|
||||||
|
// lists from a child profile on top of its parent.
|
||||||
|
fn coord_key(name: &str) -> &str {
|
||||||
|
// mojang maven coords are `group:artifact:version[:classifier]`. take
|
||||||
|
// everything up to the second colon.
|
||||||
|
let mut it = name.match_indices(':').map(|(i, _)| i);
|
||||||
|
it.next();
|
||||||
|
it.next().map_or(name, |i| &name[..i])
|
||||||
|
}
|
||||||
|
|
||||||
|
// child entries take precedence over parent entries with the same
|
||||||
|
// group:artifact. mojang and the major third-party launchers (prism,
|
||||||
|
// multimc) all dedup this way - without it, loader overrides of vanilla
|
||||||
|
// libraries (e.g. forge bumping log4j) would lose to vanilla because the
|
||||||
|
// JVM picks the first classpath match.
|
||||||
|
fn merge_libraries(
|
||||||
|
child: Vec<crate::launch_profile::model::Library>,
|
||||||
|
parent: Vec<crate::launch_profile::model::Library>,
|
||||||
|
) -> Vec<crate::launch_profile::model::Library> {
|
||||||
|
use std::collections::HashSet;
|
||||||
|
let child_keys: HashSet<&str> = child.iter().map(|l| coord_key(&l.name)).collect();
|
||||||
|
|
||||||
|
let mut out: Vec<crate::launch_profile::model::Library> = parent
|
||||||
|
.into_iter()
|
||||||
|
.filter(|l| !child_keys.contains(coord_key(&l.name)))
|
||||||
|
.collect();
|
||||||
|
out.extend(child);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn merge_arguments(child: Option<Arguments>, parent: Option<Arguments>) -> Option<Arguments> {
|
||||||
|
match (child, parent) {
|
||||||
|
(None, None) => None,
|
||||||
|
(Some(c), None) => Some(c),
|
||||||
|
(None, Some(p)) => Some(p),
|
||||||
|
(Some(c), Some(p)) => {
|
||||||
|
let mut game = p.game;
|
||||||
|
game.extend(c.game);
|
||||||
|
let mut jvm = p.jvm;
|
||||||
|
jvm.extend(c.jvm);
|
||||||
|
Some(Arguments { game, jvm })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn resolve(
|
||||||
|
profile: LaunchProfile,
|
||||||
|
meta_dir: &Path,
|
||||||
|
) -> Result<LaunchProfile, ResolveError> {
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
let mut visited: HashSet<String> = HashSet::new();
|
||||||
|
visited.insert(profile.id.clone());
|
||||||
|
|
||||||
|
let mut current = profile;
|
||||||
|
let mut depth = 0;
|
||||||
|
|
||||||
|
while let Some(parent_id) = current.inherits_from.clone() {
|
||||||
|
depth += 1;
|
||||||
|
if depth > MAX_INHERITANCE_DEPTH {
|
||||||
|
return Err(ResolveError::DepthExceeded(MAX_INHERITANCE_DEPTH));
|
||||||
|
}
|
||||||
|
if !visited.insert(parent_id.clone()) {
|
||||||
|
return Err(ResolveError::CircularInheritance(parent_id));
|
||||||
|
}
|
||||||
|
|
||||||
|
let parent_path = meta_dir.join("versions").join(&parent_id).join("meta.json");
|
||||||
|
if !parent_path.exists() {
|
||||||
|
return Err(ResolveError::ParentNotFound(
|
||||||
|
parent_path.display().to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let parent_bytes = tokio::fs::read(&parent_path).await?;
|
||||||
|
let parent: LaunchProfile = serde_json::from_slice(&parent_bytes)
|
||||||
|
.map_err(|e| ResolveError::ParseError(parent_id.clone(), e.to_string()))?;
|
||||||
|
|
||||||
|
current = merge_into(current, parent);
|
||||||
|
}
|
||||||
|
|
||||||
|
current.inherits_from = None;
|
||||||
|
Ok(current)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::launch_profile::model::{Argument, ArgumentValue, AssetIndex, JavaVersion, Library};
|
||||||
|
use crate::launch_profile::rules::{Rule, RuleAction};
|
||||||
|
|
||||||
|
fn empty_profile(id: &str) -> LaunchProfile {
|
||||||
|
LaunchProfile {
|
||||||
|
id: id.into(),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lib(name: &str) -> Library {
|
||||||
|
Library {
|
||||||
|
name: name.into(),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn allow_linux_rule() -> Rule {
|
||||||
|
Rule {
|
||||||
|
action: RuleAction::Allow,
|
||||||
|
os: Some(crate::launch_profile::rules::OsCondition {
|
||||||
|
name: Some("linux".into()),
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
features: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn child_id_wins() {
|
||||||
|
let mut child = empty_profile("child");
|
||||||
|
let parent = empty_profile("parent");
|
||||||
|
child.main_class = None;
|
||||||
|
let merged = merge_into(child, parent);
|
||||||
|
assert_eq!(merged.id, "child");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn merge_carries_parent_inherits_from() {
|
||||||
|
// merge_into preserves parent's inherits_from so resolve() can keep
|
||||||
|
// walking. resolve() itself clears the final result's inherits_from
|
||||||
|
// after the loop exits.
|
||||||
|
let mut child = empty_profile("child");
|
||||||
|
child.inherits_from = Some("parent".into());
|
||||||
|
let mut parent = empty_profile("parent");
|
||||||
|
parent.inherits_from = Some("grandparent".into());
|
||||||
|
let merged = merge_into(child, parent);
|
||||||
|
assert_eq!(merged.inherits_from.as_deref(), Some("grandparent"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn merge_with_root_parent_clears_inherits_from() {
|
||||||
|
// parent with no inherits_from means the chain ends.
|
||||||
|
let mut child = empty_profile("child");
|
||||||
|
child.inherits_from = Some("parent".into());
|
||||||
|
let parent = empty_profile("parent");
|
||||||
|
let merged = merge_into(child, parent);
|
||||||
|
assert!(merged.inherits_from.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn child_main_class_overrides_parent() {
|
||||||
|
let mut child = empty_profile("child");
|
||||||
|
let mut parent = empty_profile("parent");
|
||||||
|
child.main_class = Some("child.Main".into());
|
||||||
|
parent.main_class = Some("parent.Main".into());
|
||||||
|
let merged = merge_into(child, parent);
|
||||||
|
assert_eq!(merged.main_class.as_deref(), Some("child.Main"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parent_main_class_used_when_child_missing() {
|
||||||
|
let child = empty_profile("child");
|
||||||
|
let mut parent = empty_profile("parent");
|
||||||
|
parent.main_class = Some("parent.Main".into());
|
||||||
|
let merged = merge_into(child, parent);
|
||||||
|
assert_eq!(merged.main_class.as_deref(), Some("parent.Main"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn libraries_are_concatenated_parent_first() {
|
||||||
|
let mut child = empty_profile("child");
|
||||||
|
let mut parent = empty_profile("parent");
|
||||||
|
parent.libraries = vec![lib("p1"), lib("p2")];
|
||||||
|
child.libraries = vec![lib("c1")];
|
||||||
|
let merged = merge_into(child, parent);
|
||||||
|
let names: Vec<_> = merged.libraries.iter().map(|l| l.name.as_str()).collect();
|
||||||
|
assert_eq!(names, vec!["p1", "p2", "c1"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn child_library_supersedes_parent_with_same_group_artifact() {
|
||||||
|
// forge declares log4j 2.17.0; vanilla declared 2.0-beta9. without
|
||||||
|
// dedup, both end up on the classpath and the JVM picks the first
|
||||||
|
// (vanilla) match - defeating forge's override. dedup keeps child's.
|
||||||
|
let mut child = empty_profile("forge");
|
||||||
|
let mut parent = empty_profile("vanilla");
|
||||||
|
parent.libraries = vec![
|
||||||
|
lib("org.apache.logging.log4j:log4j-core:2.0-beta9"),
|
||||||
|
lib("org.lwjgl:lwjgl:3.3.1"),
|
||||||
|
];
|
||||||
|
child.libraries = vec![
|
||||||
|
lib("org.apache.logging.log4j:log4j-core:2.17.0"),
|
||||||
|
lib("net.minecraftforge:forge:47.2.0"),
|
||||||
|
];
|
||||||
|
let merged = merge_into(child, parent);
|
||||||
|
let names: Vec<_> = merged.libraries.iter().map(|l| l.name.as_str()).collect();
|
||||||
|
// parent's log4j-core is filtered (superseded by child); parent's
|
||||||
|
// lwjgl stays (no conflict); child's log4j and forge come last.
|
||||||
|
assert_eq!(
|
||||||
|
names,
|
||||||
|
vec![
|
||||||
|
"org.lwjgl:lwjgl:3.3.1",
|
||||||
|
"org.apache.logging.log4j:log4j-core:2.17.0",
|
||||||
|
"net.minecraftforge:forge:47.2.0",
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn coord_key_extracts_group_artifact() {
|
||||||
|
assert_eq!(coord_key("org.lwjgl:lwjgl:3.3.1"), "org.lwjgl:lwjgl");
|
||||||
|
assert_eq!(
|
||||||
|
coord_key("org.apache.logging.log4j:log4j-core:2.17.0"),
|
||||||
|
"org.apache.logging.log4j:log4j-core"
|
||||||
|
);
|
||||||
|
// with classifier
|
||||||
|
assert_eq!(
|
||||||
|
coord_key("org.lwjgl:lwjgl:3.3.1:natives-linux"),
|
||||||
|
"org.lwjgl:lwjgl"
|
||||||
|
);
|
||||||
|
// malformed (no colons) - return as-is
|
||||||
|
assert_eq!(coord_key("malformed"), "malformed");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn arguments_are_concatenated_parent_first() {
|
||||||
|
let mut child = empty_profile("child");
|
||||||
|
let mut parent = empty_profile("parent");
|
||||||
|
parent.arguments = Some(Arguments {
|
||||||
|
game: vec![Argument::Literal("--from-parent-game".into())],
|
||||||
|
jvm: vec![Argument::Literal("--from-parent-jvm".into())],
|
||||||
|
});
|
||||||
|
child.arguments = Some(Arguments {
|
||||||
|
game: vec![Argument::Literal("--from-child-game".into())],
|
||||||
|
jvm: vec![Argument::Literal("--from-child-jvm".into())],
|
||||||
|
});
|
||||||
|
let merged = merge_into(child, parent);
|
||||||
|
let args = merged.arguments.expect("arguments present");
|
||||||
|
assert_eq!(
|
||||||
|
args.game,
|
||||||
|
vec![
|
||||||
|
Argument::Literal("--from-parent-game".into()),
|
||||||
|
Argument::Literal("--from-child-game".into()),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
args.jvm,
|
||||||
|
vec![
|
||||||
|
Argument::Literal("--from-parent-jvm".into()),
|
||||||
|
Argument::Literal("--from-child-jvm".into()),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn arguments_from_child_only_carry_through() {
|
||||||
|
let mut child = empty_profile("child");
|
||||||
|
let parent = empty_profile("parent");
|
||||||
|
child.arguments = Some(Arguments {
|
||||||
|
game: vec![Argument::Literal("--child".into())],
|
||||||
|
jvm: Vec::new(),
|
||||||
|
});
|
||||||
|
let merged = merge_into(child, parent);
|
||||||
|
let args = merged.arguments.expect("arguments present");
|
||||||
|
assert_eq!(args.game.len(), 1);
|
||||||
|
assert!(args.jvm.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn arguments_from_parent_only_carry_through() {
|
||||||
|
let child = empty_profile("child");
|
||||||
|
let mut parent = empty_profile("parent");
|
||||||
|
parent.arguments = Some(Arguments {
|
||||||
|
game: Vec::new(),
|
||||||
|
jvm: vec![Argument::Literal("--parent-jvm".into())],
|
||||||
|
});
|
||||||
|
let merged = merge_into(child, parent);
|
||||||
|
let args = merged.arguments.expect("arguments present");
|
||||||
|
assert!(args.game.is_empty());
|
||||||
|
assert_eq!(args.jvm.len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn conditional_arguments_with_rules_survive_merge() {
|
||||||
|
// make sure the Argument::Conditional shape isn't accidentally
|
||||||
|
// flattened or filtered during merging - rule eval happens later
|
||||||
|
// at render time, not during merge.
|
||||||
|
let mut child = empty_profile("child");
|
||||||
|
let parent = empty_profile("parent");
|
||||||
|
child.arguments = Some(Arguments {
|
||||||
|
game: vec![Argument::Conditional {
|
||||||
|
rules: vec![allow_linux_rule()],
|
||||||
|
value: ArgumentValue::Single("--linux-only".into()),
|
||||||
|
}],
|
||||||
|
jvm: Vec::new(),
|
||||||
|
});
|
||||||
|
let merged = merge_into(child, parent);
|
||||||
|
let args = merged.arguments.expect("arguments present");
|
||||||
|
match &args.game[0] {
|
||||||
|
Argument::Conditional { rules, .. } => {
|
||||||
|
assert_eq!(rules.len(), 1);
|
||||||
|
assert_eq!(rules[0].action, RuleAction::Allow);
|
||||||
|
}
|
||||||
|
_ => panic!("expected conditional argument to survive merge"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_minecraft_arguments_child_overrides_parent() {
|
||||||
|
let mut child = empty_profile("child");
|
||||||
|
let mut parent = empty_profile("parent");
|
||||||
|
child.minecraft_arguments = Some("--child".into());
|
||||||
|
parent.minecraft_arguments = Some("--parent".into());
|
||||||
|
let merged = merge_into(child, parent);
|
||||||
|
assert_eq!(merged.minecraft_arguments.as_deref(), Some("--child"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn asset_index_inherits_from_parent_when_child_absent() {
|
||||||
|
let child = empty_profile("child");
|
||||||
|
let mut parent = empty_profile("parent");
|
||||||
|
parent.asset_index = Some(AssetIndex {
|
||||||
|
id: "5".into(),
|
||||||
|
url: "https://example.invalid/5.json".into(),
|
||||||
|
sha1: "0".repeat(40),
|
||||||
|
size: None,
|
||||||
|
total_size: None,
|
||||||
|
});
|
||||||
|
let merged = merge_into(child, parent);
|
||||||
|
assert!(merged.asset_index.is_some());
|
||||||
|
assert_eq!(merged.asset_index.unwrap().id, "5");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn java_version_inherits_from_parent_when_child_absent() {
|
||||||
|
let child = empty_profile("child");
|
||||||
|
let mut parent = empty_profile("parent");
|
||||||
|
parent.java_version = Some(JavaVersion {
|
||||||
|
component: Some("java-runtime-gamma".into()),
|
||||||
|
major_version: 17,
|
||||||
|
});
|
||||||
|
let merged = merge_into(child, parent);
|
||||||
|
assert_eq!(
|
||||||
|
merged.java_version.as_ref().map(|j| j.major_version),
|
||||||
|
Some(17)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
use tempfile::TempDir;
|
||||||
|
|
||||||
|
fn write_profile(meta_dir: &Path, profile: &LaunchProfile) {
|
||||||
|
let path = meta_dir
|
||||||
|
.join("versions")
|
||||||
|
.join(&profile.id)
|
||||||
|
.join("meta.json");
|
||||||
|
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||||
|
let json = serde_json::to_string_pretty(profile).unwrap();
|
||||||
|
std::fs::write(&path, json).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn resolve_returns_unchanged_when_no_inherits_from() {
|
||||||
|
let tmp = TempDir::new().unwrap();
|
||||||
|
let profile = empty_profile("standalone");
|
||||||
|
let resolved = resolve(profile, tmp.path()).await.unwrap();
|
||||||
|
assert_eq!(resolved.id, "standalone");
|
||||||
|
assert!(resolved.inherits_from.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn resolve_single_level_inheritance_merges_parent() {
|
||||||
|
let tmp = TempDir::new().unwrap();
|
||||||
|
|
||||||
|
let mut parent = empty_profile("1.20.1");
|
||||||
|
parent.main_class = Some("net.minecraft.client.main.Main".into());
|
||||||
|
parent.libraries = vec![lib("vanilla-lib")];
|
||||||
|
write_profile(tmp.path(), &parent);
|
||||||
|
|
||||||
|
let mut child = empty_profile("1.20.1-forge-47.2.0");
|
||||||
|
child.inherits_from = Some("1.20.1".into());
|
||||||
|
child.libraries = vec![lib("forge-lib")];
|
||||||
|
|
||||||
|
let resolved = resolve(child, tmp.path()).await.unwrap();
|
||||||
|
assert_eq!(resolved.id, "1.20.1-forge-47.2.0");
|
||||||
|
assert!(resolved.inherits_from.is_none());
|
||||||
|
assert_eq!(
|
||||||
|
resolved.main_class.as_deref(),
|
||||||
|
Some("net.minecraft.client.main.Main")
|
||||||
|
);
|
||||||
|
let names: Vec<_> = resolved.libraries.iter().map(|l| l.name.as_str()).collect();
|
||||||
|
assert_eq!(names, vec!["vanilla-lib", "forge-lib"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn resolve_errors_when_parent_missing() {
|
||||||
|
let tmp = TempDir::new().unwrap();
|
||||||
|
|
||||||
|
let mut child = empty_profile("1.20.1-forge-47.2.0");
|
||||||
|
child.inherits_from = Some("1.20.1".into());
|
||||||
|
|
||||||
|
let err = resolve(child, tmp.path()).await.unwrap_err();
|
||||||
|
assert!(
|
||||||
|
matches!(err, ResolveError::ParentNotFound(_)),
|
||||||
|
"expected ParentNotFound, got {err:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn resolve_errors_when_parent_is_invalid_json() {
|
||||||
|
let tmp = TempDir::new().unwrap();
|
||||||
|
|
||||||
|
let parent_path = tmp.path().join("versions").join("1.20.1").join("meta.json");
|
||||||
|
std::fs::create_dir_all(parent_path.parent().unwrap()).unwrap();
|
||||||
|
std::fs::write(&parent_path, "{ not valid json").unwrap();
|
||||||
|
|
||||||
|
let mut child = empty_profile("1.20.1-forge-47.2.0");
|
||||||
|
child.inherits_from = Some("1.20.1".into());
|
||||||
|
|
||||||
|
let err = resolve(child, tmp.path()).await.unwrap_err();
|
||||||
|
assert!(
|
||||||
|
matches!(err, ResolveError::ParseError(_, _)),
|
||||||
|
"expected ParseError, got {err:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn resolve_multi_level_chain_merges_all_parents() {
|
||||||
|
let tmp = TempDir::new().unwrap();
|
||||||
|
|
||||||
|
// chain: grandchild -> child -> root (vanilla).
|
||||||
|
let mut root = empty_profile("1.20.1");
|
||||||
|
root.main_class = Some("net.minecraft.client.main.Main".into());
|
||||||
|
root.libraries = vec![lib("vanilla-lib")];
|
||||||
|
write_profile(tmp.path(), &root);
|
||||||
|
|
||||||
|
let mut child = empty_profile("1.20.1-forge-47.2.0");
|
||||||
|
child.inherits_from = Some("1.20.1".into());
|
||||||
|
child.libraries = vec![lib("forge-lib")];
|
||||||
|
write_profile(tmp.path(), &child);
|
||||||
|
|
||||||
|
let mut grandchild = empty_profile("1.20.1-forge-47.2.0-modpack");
|
||||||
|
grandchild.inherits_from = Some("1.20.1-forge-47.2.0".into());
|
||||||
|
grandchild.libraries = vec![lib("modpack-lib")];
|
||||||
|
|
||||||
|
let resolved = resolve(grandchild, tmp.path()).await.unwrap();
|
||||||
|
assert_eq!(resolved.id, "1.20.1-forge-47.2.0-modpack");
|
||||||
|
assert!(resolved.inherits_from.is_none());
|
||||||
|
assert_eq!(
|
||||||
|
resolved.main_class.as_deref(),
|
||||||
|
Some("net.minecraft.client.main.Main")
|
||||||
|
);
|
||||||
|
// libs: root ++ child ++ grandchild (each parent prepended)
|
||||||
|
let names: Vec<_> = resolved.libraries.iter().map(|l| l.name.as_str()).collect();
|
||||||
|
assert_eq!(names, vec!["vanilla-lib", "forge-lib", "modpack-lib"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn resolve_detects_circular_chain() {
|
||||||
|
let tmp = TempDir::new().unwrap();
|
||||||
|
|
||||||
|
// a -> b -> a (cycle)
|
||||||
|
let mut a = empty_profile("a");
|
||||||
|
a.inherits_from = Some("b".into());
|
||||||
|
write_profile(tmp.path(), &a);
|
||||||
|
|
||||||
|
let mut b = empty_profile("b");
|
||||||
|
b.inherits_from = Some("a".into());
|
||||||
|
write_profile(tmp.path(), &b);
|
||||||
|
|
||||||
|
// start from a fresh "a" profile that asks to inherit from b
|
||||||
|
let mut entry = empty_profile("a");
|
||||||
|
entry.inherits_from = Some("b".into());
|
||||||
|
|
||||||
|
let err = resolve(entry, tmp.path()).await.unwrap_err();
|
||||||
|
assert!(
|
||||||
|
matches!(err, ResolveError::CircularInheritance(ref s) if s == "a"),
|
||||||
|
"expected CircularInheritance(a), got {err:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn resolve_caps_depth() {
|
||||||
|
let tmp = TempDir::new().unwrap();
|
||||||
|
|
||||||
|
// build a chain 0 -> 1 -> 2 -> ... -> 10. with cap of 8, hitting 10
|
||||||
|
// should fail with DepthExceeded.
|
||||||
|
for i in 0..=10 {
|
||||||
|
let mut p = empty_profile(&format!("v{i}"));
|
||||||
|
if i < 10 {
|
||||||
|
p.inherits_from = Some(format!("v{}", i + 1));
|
||||||
|
}
|
||||||
|
write_profile(tmp.path(), &p);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut entry = empty_profile("entry");
|
||||||
|
entry.inherits_from = Some("v0".into());
|
||||||
|
|
||||||
|
let err = resolve(entry, tmp.path()).await.unwrap_err();
|
||||||
|
assert!(
|
||||||
|
matches!(err, ResolveError::DepthExceeded(_)),
|
||||||
|
"expected DepthExceeded, got {err:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,408 @@
|
|||||||
|
// mojang rule evaluation. profiles, libraries, and argument entries can
|
||||||
|
// carry conditional rules that filter them by OS, architecture, or feature
|
||||||
|
// flags. this module is the single source of truth for that semantics -
|
||||||
|
// see `evaluate` below for the exact rules.
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum RuleAction {
|
||||||
|
Allow,
|
||||||
|
Disallow,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize)]
|
||||||
|
pub struct OsCondition {
|
||||||
|
pub name: Option<String>,
|
||||||
|
pub arch: Option<String>,
|
||||||
|
// mojang occasionally constrains natives selection on os.version with a
|
||||||
|
// regex. rare in practice - when present, it's a substring/anchor match
|
||||||
|
// against the host OS version reported by `system::mojang_os_version`.
|
||||||
|
pub version: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub struct FeatureSet {
|
||||||
|
pub is_demo_user: Option<bool>,
|
||||||
|
pub has_custom_resolution: Option<bool>,
|
||||||
|
// quick-play feature flags (1.20+). rmcl never sets these, so any rule
|
||||||
|
// gated on them is filtered out by features_match. listing them
|
||||||
|
// explicitly is what makes that filter work: without the fields,
|
||||||
|
// serde would silently drop them during deserialization, leaving a
|
||||||
|
// FeatureSet::default that matches everything.
|
||||||
|
pub has_quick_plays_support: Option<bool>,
|
||||||
|
pub is_quick_play_singleplayer: Option<bool>,
|
||||||
|
pub is_quick_play_multiplayer: Option<bool>,
|
||||||
|
pub is_quick_play_realms: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||||
|
pub struct Rule {
|
||||||
|
pub action: RuleAction,
|
||||||
|
pub os: Option<OsCondition>,
|
||||||
|
pub features: Option<FeatureSet>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct RuleContext<'a> {
|
||||||
|
pub os_name: &'a str,
|
||||||
|
pub os_version: &'a str,
|
||||||
|
pub arch: &'a str,
|
||||||
|
pub features: &'a FeatureSet,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn evaluate(rules: &[Rule], ctx: &RuleContext) -> bool {
|
||||||
|
if rules.is_empty() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
let mut allowed = false;
|
||||||
|
for rule in rules {
|
||||||
|
if rule_matches(rule, ctx) {
|
||||||
|
allowed = matches!(rule.action, RuleAction::Allow);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
allowed
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rule_matches(rule: &Rule, ctx: &RuleContext) -> bool {
|
||||||
|
if let Some(os) = &rule.os {
|
||||||
|
if let Some(name) = &os.name
|
||||||
|
&& name != ctx.os_name
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if let Some(arch) = &os.arch
|
||||||
|
&& arch != ctx.arch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if let Some(pattern) = &os.version
|
||||||
|
&& !os_version_matches(pattern, ctx.os_version)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(required) = &rule.features
|
||||||
|
&& !features_match(required, ctx.features)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
// mojang's os.version constraints are typically anchored regex patterns
|
||||||
|
// (e.g. `^10\\.`). we do a substring containment check as a defensive
|
||||||
|
// approximation that doesn't pull in the `regex` crate. when the host
|
||||||
|
// os_version is empty (Windows fallback path returns ""), version-gated
|
||||||
|
// rules don't match - which is the conservative default.
|
||||||
|
fn os_version_matches(pattern: &str, host_version: &str) -> bool {
|
||||||
|
if host_version.is_empty() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// strip common regex anchors and metacharacters for substring lookup.
|
||||||
|
// good enough for the rare profile that uses os.version.
|
||||||
|
let needle = pattern
|
||||||
|
.trim_start_matches('^')
|
||||||
|
.trim_end_matches('$')
|
||||||
|
.trim_end_matches('.')
|
||||||
|
.trim_end_matches('\\');
|
||||||
|
host_version.contains(needle)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn features_match(required: &FeatureSet, current: &FeatureSet) -> bool {
|
||||||
|
let pairs = [
|
||||||
|
(required.is_demo_user, current.is_demo_user),
|
||||||
|
(required.has_custom_resolution, current.has_custom_resolution),
|
||||||
|
(
|
||||||
|
required.has_quick_plays_support,
|
||||||
|
current.has_quick_plays_support,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
required.is_quick_play_singleplayer,
|
||||||
|
current.is_quick_play_singleplayer,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
required.is_quick_play_multiplayer,
|
||||||
|
current.is_quick_play_multiplayer,
|
||||||
|
),
|
||||||
|
(required.is_quick_play_realms, current.is_quick_play_realms),
|
||||||
|
];
|
||||||
|
pairs.iter().all(|(req, cur)| match req {
|
||||||
|
Some(want) => cur.unwrap_or(false) == *want,
|
||||||
|
None => true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn linux_ctx<'a>(features: &'a FeatureSet) -> RuleContext<'a> {
|
||||||
|
RuleContext {
|
||||||
|
os_name: "linux",
|
||||||
|
os_version: "6.0",
|
||||||
|
arch: "x86_64",
|
||||||
|
features,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_rules_allow() {
|
||||||
|
let features = FeatureSet::default();
|
||||||
|
let ctx = linux_ctx(&features);
|
||||||
|
assert!(evaluate(&[], &ctx));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn single_allow_matching_os_allows() {
|
||||||
|
let rules = vec![Rule {
|
||||||
|
action: RuleAction::Allow,
|
||||||
|
os: Some(OsCondition {
|
||||||
|
name: Some("linux".into()),
|
||||||
|
arch: None,
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
features: None,
|
||||||
|
}];
|
||||||
|
let features = FeatureSet::default();
|
||||||
|
let ctx = linux_ctx(&features);
|
||||||
|
assert!(evaluate(&rules, &ctx));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn single_disallow_matching_os_disallows() {
|
||||||
|
let rules = vec![Rule {
|
||||||
|
action: RuleAction::Disallow,
|
||||||
|
os: Some(OsCondition {
|
||||||
|
name: Some("linux".into()),
|
||||||
|
arch: None,
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
features: None,
|
||||||
|
}];
|
||||||
|
let features = FeatureSet::default();
|
||||||
|
let ctx = linux_ctx(&features);
|
||||||
|
assert!(!evaluate(&rules, &ctx));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn allow_without_os_match_disallows_by_default() {
|
||||||
|
// explicit allow for windows; we are on linux; nothing matches;
|
||||||
|
// default state remains disallow.
|
||||||
|
let rules = vec![Rule {
|
||||||
|
action: RuleAction::Allow,
|
||||||
|
os: Some(OsCondition {
|
||||||
|
name: Some("windows".into()),
|
||||||
|
arch: None,
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
features: None,
|
||||||
|
}];
|
||||||
|
let features = FeatureSet::default();
|
||||||
|
let ctx = linux_ctx(&features);
|
||||||
|
assert!(!evaluate(&rules, &ctx));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn last_matching_rule_wins_when_allow_then_disallow() {
|
||||||
|
let rules = vec![
|
||||||
|
Rule {
|
||||||
|
action: RuleAction::Allow,
|
||||||
|
os: None,
|
||||||
|
features: None,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
action: RuleAction::Disallow,
|
||||||
|
os: Some(OsCondition {
|
||||||
|
name: Some("osx".into()),
|
||||||
|
arch: None,
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
features: None,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
let features = FeatureSet::default();
|
||||||
|
let osx_ctx = RuleContext {
|
||||||
|
os_name: "osx",
|
||||||
|
os_version: "6.0",
|
||||||
|
arch: "x86_64",
|
||||||
|
features: &features,
|
||||||
|
};
|
||||||
|
assert!(!evaluate(&rules, &osx_ctx));
|
||||||
|
// and on linux: only the first rule matches → still allow.
|
||||||
|
let lin = linux_ctx(&features);
|
||||||
|
assert!(evaluate(&rules, &lin));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn last_matching_rule_wins_when_disallow_then_allow() {
|
||||||
|
let rules = vec![
|
||||||
|
Rule {
|
||||||
|
action: RuleAction::Disallow,
|
||||||
|
os: None,
|
||||||
|
features: None,
|
||||||
|
},
|
||||||
|
Rule {
|
||||||
|
action: RuleAction::Allow,
|
||||||
|
os: Some(OsCondition {
|
||||||
|
name: Some("linux".into()),
|
||||||
|
arch: None,
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
features: None,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
let features = FeatureSet::default();
|
||||||
|
let ctx = linux_ctx(&features);
|
||||||
|
assert!(evaluate(&rules, &ctx));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn arch_mismatch_blocks_rule() {
|
||||||
|
let rules = vec![Rule {
|
||||||
|
action: RuleAction::Allow,
|
||||||
|
os: Some(OsCondition {
|
||||||
|
name: Some("linux".into()),
|
||||||
|
arch: Some("arm64".into()),
|
||||||
|
version: None,
|
||||||
|
}),
|
||||||
|
features: None,
|
||||||
|
}];
|
||||||
|
let features = FeatureSet::default();
|
||||||
|
let ctx = linux_ctx(&features);
|
||||||
|
// we are on linux but x86_64, not arm64 → rule does not match.
|
||||||
|
assert!(!evaluate(&rules, &ctx));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn feature_required_true_matches_when_ctx_true() {
|
||||||
|
let rules = vec![Rule {
|
||||||
|
action: RuleAction::Allow,
|
||||||
|
os: None,
|
||||||
|
features: Some(FeatureSet {
|
||||||
|
is_demo_user: Some(true),
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
}];
|
||||||
|
let demo_features = FeatureSet {
|
||||||
|
is_demo_user: Some(true),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let ctx = RuleContext {
|
||||||
|
os_name: "linux",
|
||||||
|
os_version: "6.0",
|
||||||
|
arch: "x86_64",
|
||||||
|
features: &demo_features,
|
||||||
|
};
|
||||||
|
assert!(evaluate(&rules, &ctx));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn feature_required_true_blocks_when_ctx_false() {
|
||||||
|
let rules = vec![Rule {
|
||||||
|
action: RuleAction::Allow,
|
||||||
|
os: None,
|
||||||
|
features: Some(FeatureSet {
|
||||||
|
is_demo_user: Some(true),
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
}];
|
||||||
|
let features = FeatureSet::default();
|
||||||
|
let ctx = linux_ctx(&features);
|
||||||
|
assert!(!evaluate(&rules, &ctx));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_os_no_features_rule_always_matches() {
|
||||||
|
let rules = vec![Rule {
|
||||||
|
action: RuleAction::Allow,
|
||||||
|
os: None,
|
||||||
|
features: None,
|
||||||
|
}];
|
||||||
|
let features = FeatureSet::default();
|
||||||
|
let ctx = linux_ctx(&features);
|
||||||
|
assert!(evaluate(&rules, &ctx));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn os_version_pattern_matches_against_host() {
|
||||||
|
let rules = vec![Rule {
|
||||||
|
action: RuleAction::Allow,
|
||||||
|
os: Some(OsCondition {
|
||||||
|
name: Some("osx".into()),
|
||||||
|
arch: None,
|
||||||
|
version: Some("^10\\.".into()),
|
||||||
|
}),
|
||||||
|
features: None,
|
||||||
|
}];
|
||||||
|
let features = FeatureSet::default();
|
||||||
|
let ctx_match = RuleContext {
|
||||||
|
os_name: "osx",
|
||||||
|
os_version: "10.15.7",
|
||||||
|
arch: "x86_64",
|
||||||
|
features: &features,
|
||||||
|
};
|
||||||
|
assert!(evaluate(&rules, &ctx_match));
|
||||||
|
let ctx_mismatch = RuleContext {
|
||||||
|
os_name: "osx",
|
||||||
|
os_version: "13.2.1",
|
||||||
|
arch: "x86_64",
|
||||||
|
features: &features,
|
||||||
|
};
|
||||||
|
assert!(!evaluate(&rules, &ctx_mismatch));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn os_version_pattern_does_not_match_when_host_unknown() {
|
||||||
|
let rules = vec![Rule {
|
||||||
|
action: RuleAction::Allow,
|
||||||
|
os: Some(OsCondition {
|
||||||
|
name: Some("windows".into()),
|
||||||
|
arch: None,
|
||||||
|
version: Some("^10\\.".into()),
|
||||||
|
}),
|
||||||
|
features: None,
|
||||||
|
}];
|
||||||
|
let features = FeatureSet::default();
|
||||||
|
let ctx = RuleContext {
|
||||||
|
os_name: "windows",
|
||||||
|
os_version: "",
|
||||||
|
arch: "x86_64",
|
||||||
|
features: &features,
|
||||||
|
};
|
||||||
|
assert!(!evaluate(&rules, &ctx));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rule_deserializes_from_mojang_json() {
|
||||||
|
// shape lifted from real mojang library rules.
|
||||||
|
let json = r#"{
|
||||||
|
"action": "allow",
|
||||||
|
"os": { "name": "osx" }
|
||||||
|
}"#;
|
||||||
|
let rule: Rule = serde_json::from_str(json).unwrap();
|
||||||
|
assert_eq!(rule.action, RuleAction::Allow);
|
||||||
|
assert_eq!(
|
||||||
|
rule.os.as_ref().and_then(|o| o.name.as_deref()),
|
||||||
|
Some("osx")
|
||||||
|
);
|
||||||
|
assert!(rule.os.as_ref().and_then(|o| o.arch.as_ref()).is_none());
|
||||||
|
assert!(rule.features.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rule_deserializes_with_features() {
|
||||||
|
let json = r#"{
|
||||||
|
"action": "allow",
|
||||||
|
"features": { "is_demo_user": true }
|
||||||
|
}"#;
|
||||||
|
let rule: Rule = serde_json::from_str(json).unwrap();
|
||||||
|
assert_eq!(rule.action, RuleAction::Allow);
|
||||||
|
assert!(rule.os.is_none());
|
||||||
|
assert_eq!(
|
||||||
|
rule.features.as_ref().and_then(|f| f.is_demo_user),
|
||||||
|
Some(true)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
// system-detection helpers shared by launch and install paths. mojang
|
||||||
|
// names some things differently from rust's std::env::consts (e.g. macOS
|
||||||
|
// is "osx" in mojang profile rules), so this module is the single source
|
||||||
|
// of truth for translating.
|
||||||
|
|
||||||
|
pub fn mojang_os_name() -> &'static str {
|
||||||
|
match std::env::consts::OS {
|
||||||
|
"macos" => "osx",
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mojang_arch_name() -> &'static str {
|
||||||
|
match std::env::consts::ARCH {
|
||||||
|
"x86" => "x86",
|
||||||
|
"x86_64" => "x86_64",
|
||||||
|
"aarch64" => "arm64",
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// the host OS version string. mojang rules occasionally constrain natives
|
||||||
|
// selection on os.version with a regex (e.g. macOS 10.x-only natives).
|
||||||
|
// rust's stdlib doesn't expose this, so we read it where it's cheap and
|
||||||
|
// reliable: linux via /proc/sys/kernel/osrelease, other platforms return
|
||||||
|
// empty. when the host string is empty, version-gated rules don't match
|
||||||
|
// (conservative default in the rule evaluator) - which is fine because
|
||||||
|
// real-world profiles using os.version are vanishingly rare.
|
||||||
|
pub fn mojang_os_version() -> String {
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
{
|
||||||
|
if let Ok(s) = std::fs::read_to_string("/proc/sys/kernel/osrelease") {
|
||||||
|
return s.trim().to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String::new()
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
// template substitution for mojang-style launch arguments. profiles use
|
||||||
|
// `${variable_name}` placeholders that the launcher fills in at launch
|
||||||
|
// time from the active session: paths, the user's account info, the
|
||||||
|
// classpath, the resolved natives directory, and so on.
|
||||||
|
//
|
||||||
|
// the full set of variables is documented in `TemplateContext`. unknown
|
||||||
|
// placeholders are left as-is and logged at `warn` level - that way if
|
||||||
|
// mojang adds a new variable in the future, the launcher fails open
|
||||||
|
// rather than silently swallowing it.
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
pub struct TemplateContext<'a> {
|
||||||
|
pub library_directory: &'a Path,
|
||||||
|
pub classpath_separator: &'a str,
|
||||||
|
pub version_name: &'a str,
|
||||||
|
pub version_type: &'a str,
|
||||||
|
pub natives_directory: &'a Path,
|
||||||
|
pub classpath: &'a str,
|
||||||
|
pub game_directory: &'a Path,
|
||||||
|
pub assets_root: &'a Path,
|
||||||
|
pub assets_index_name: &'a str,
|
||||||
|
pub auth_player_name: &'a str,
|
||||||
|
pub auth_uuid: &'a str,
|
||||||
|
pub auth_access_token: &'a str,
|
||||||
|
pub auth_xuid: &'a str,
|
||||||
|
pub user_type: &'a str,
|
||||||
|
pub user_properties: &'a str,
|
||||||
|
pub launcher_name: &'a str,
|
||||||
|
pub launcher_version: &'a str,
|
||||||
|
pub clientid: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn substitute(input: &str, ctx: &TemplateContext) -> String {
|
||||||
|
let mut out = String::with_capacity(input.len());
|
||||||
|
let mut rest = input;
|
||||||
|
while let Some(open) = rest.find("${") {
|
||||||
|
out.push_str(&rest[..open]);
|
||||||
|
let after_open = &rest[open + 2..];
|
||||||
|
match after_open.find('}') {
|
||||||
|
Some(close_rel) => {
|
||||||
|
let name = &after_open[..close_rel];
|
||||||
|
match lookup(name, ctx) {
|
||||||
|
Some(value) => out.push_str(&value),
|
||||||
|
None => {
|
||||||
|
tracing::warn!("unknown launch template variable: ${{{}}}", name);
|
||||||
|
out.push_str("${");
|
||||||
|
out.push_str(name);
|
||||||
|
out.push('}');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rest = &after_open[close_rel + 1..];
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
// unclosed `${...` - emit the rest literally and stop.
|
||||||
|
out.push_str("${");
|
||||||
|
out.push_str(after_open);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push_str(rest);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
// quick-play templates (`${quickPlayPath}`, `${quickPlaySingleplayer}`,
|
||||||
|
// `${quickPlayMultiplayer}`, `${quickPlayRealms}`) are intentionally not
|
||||||
|
// listed here. they only appear in `arguments.game` entries gated on
|
||||||
|
// `is_quick_play_*` feature flags; since rmcl never sets those flags
|
||||||
|
// (FeatureSet defaults to None across the board), the surrounding
|
||||||
|
// conditional argument is filtered out by the rule evaluator before
|
||||||
|
// template substitution even runs. if we ever expose quick-play to users,
|
||||||
|
// add the variables here AND set the corresponding feature flags in
|
||||||
|
// RuleContext at launch.
|
||||||
|
fn lookup(name: &str, ctx: &TemplateContext) -> Option<String> {
|
||||||
|
Some(match name {
|
||||||
|
"library_directory" => ctx.library_directory.display().to_string(),
|
||||||
|
"classpath_separator" => ctx.classpath_separator.to_string(),
|
||||||
|
"version_name" => ctx.version_name.to_string(),
|
||||||
|
"version_type" => ctx.version_type.to_string(),
|
||||||
|
"natives_directory" => ctx.natives_directory.display().to_string(),
|
||||||
|
"classpath" => ctx.classpath.to_string(),
|
||||||
|
"game_directory" => ctx.game_directory.display().to_string(),
|
||||||
|
"assets_root" => ctx.assets_root.display().to_string(),
|
||||||
|
"assets_index_name" => ctx.assets_index_name.to_string(),
|
||||||
|
"auth_player_name" => ctx.auth_player_name.to_string(),
|
||||||
|
"auth_uuid" => ctx.auth_uuid.to_string(),
|
||||||
|
"auth_access_token" => ctx.auth_access_token.to_string(),
|
||||||
|
"auth_xuid" => ctx.auth_xuid.to_string(),
|
||||||
|
"user_type" => ctx.user_type.to_string(),
|
||||||
|
"user_properties" => ctx.user_properties.to_string(),
|
||||||
|
"launcher_name" => ctx.launcher_name.to_string(),
|
||||||
|
"launcher_version" => ctx.launcher_version.to_string(),
|
||||||
|
"clientid" => ctx.clientid.to_string(),
|
||||||
|
_ => return None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
// owns the path buffers so tests don't have to declare them inline; the
|
||||||
|
// ctx() method borrows from self to build a TemplateContext with the
|
||||||
|
// standard set of values. windows() returns a fixture with backslash
|
||||||
|
// paths so the OS-independence test stays self-contained.
|
||||||
|
struct Fixture {
|
||||||
|
lib: PathBuf,
|
||||||
|
nat: PathBuf,
|
||||||
|
game: PathBuf,
|
||||||
|
assets: PathBuf,
|
||||||
|
user_properties: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Fixture {
|
||||||
|
fn unix() -> Self {
|
||||||
|
Self {
|
||||||
|
lib: PathBuf::from("/m/libraries"),
|
||||||
|
nat: PathBuf::from("/m/natives"),
|
||||||
|
game: PathBuf::from("/i/.minecraft"),
|
||||||
|
assets: PathBuf::from("/m/assets"),
|
||||||
|
user_properties: "{}".to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn windows() -> Self {
|
||||||
|
Self {
|
||||||
|
lib: PathBuf::from(r"C:\Users\test\.minecraft\libraries"),
|
||||||
|
nat: PathBuf::from(r"C:\Users\test\.minecraft\natives"),
|
||||||
|
game: PathBuf::from(r"C:\Users\test\.minecraft"),
|
||||||
|
assets: PathBuf::from(r"C:\Users\test\.minecraft\assets"),
|
||||||
|
user_properties: "{}".to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ctx(&self) -> TemplateContext<'_> {
|
||||||
|
TemplateContext {
|
||||||
|
library_directory: &self.lib,
|
||||||
|
classpath_separator: ":",
|
||||||
|
version_name: "1.20.1",
|
||||||
|
version_type: "release",
|
||||||
|
natives_directory: &self.nat,
|
||||||
|
classpath: "a.jar:b.jar",
|
||||||
|
game_directory: &self.game,
|
||||||
|
assets_root: &self.assets,
|
||||||
|
assets_index_name: "5",
|
||||||
|
auth_player_name: "Player",
|
||||||
|
auth_uuid: "00000000-0000-0000-0000-000000000000",
|
||||||
|
auth_access_token: "token",
|
||||||
|
auth_xuid: "0",
|
||||||
|
user_type: "msa",
|
||||||
|
user_properties: &self.user_properties,
|
||||||
|
launcher_name: "rmcl",
|
||||||
|
launcher_version: "0.3.0",
|
||||||
|
clientid: "0",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[rstest::rstest]
|
||||||
|
#[case::no_placeholders("--add-modules ALL-MODULE-PATH", "--add-modules ALL-MODULE-PATH")]
|
||||||
|
#[case::single_known("v=${version_name}", "v=1.20.1")]
|
||||||
|
#[case::unknown_placeholder("x=${not_a_real_var}y", "x=${not_a_real_var}y")]
|
||||||
|
#[case::unclosed_placeholder("--prefix ${unclosed", "--prefix ${unclosed")]
|
||||||
|
#[case::dollar_without_brace("$$ literal $5 $", "$$ literal $5 $")]
|
||||||
|
#[case::multiple("${version_name}-${auth_player_name}", "1.20.1-Player")]
|
||||||
|
#[case::path("-DlibraryDirectory=${library_directory}", "-DlibraryDirectory=/m/libraries")]
|
||||||
|
#[case::empty_input("", "")]
|
||||||
|
fn substitute_handles(#[case] input: &str, #[case] expected: &str) {
|
||||||
|
let fx = Fixture::unix();
|
||||||
|
assert_eq!(substitute(input, &fx.ctx()), expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn substituted_value_is_not_recursively_substituted() {
|
||||||
|
// simulate a user_properties value that happens to contain a ${...}
|
||||||
|
// pattern. it should NOT trigger another substitution pass.
|
||||||
|
let mut fx = Fixture::unix();
|
||||||
|
fx.user_properties = "${version_name}".to_string();
|
||||||
|
assert_eq!(substitute("${user_properties}", &fx.ctx()), "${version_name}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn windows_style_backslashes_in_value_pass_through() {
|
||||||
|
// simulate a Windows install where library_directory is a path with
|
||||||
|
// backslashes. the substitution must not interpret backslashes as
|
||||||
|
// escape sequences or do anything else clever - it just copies the
|
||||||
|
// value into the output.
|
||||||
|
let fx = Fixture::windows();
|
||||||
|
let result = substitute("-Dpath=${library_directory}", &fx.ctx());
|
||||||
|
assert!(
|
||||||
|
result.contains(r"C:\Users\test\.minecraft\libraries"),
|
||||||
|
"expected backslashes preserved, got: {result}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
// crate root. main.rs is a thin wrapper that imports the two entry points
|
||||||
|
// re-exported below; everything else stays crate-private. integration tests
|
||||||
|
// in tests/ that need to reach in deeper can use `rmcl::auth`, `rmcl::net`,
|
||||||
|
// etc. directly; cli + migrate stay private because they have nothing
|
||||||
|
// general to expose.
|
||||||
|
|
||||||
|
pub mod auth;
|
||||||
|
mod cli;
|
||||||
|
pub mod config;
|
||||||
|
pub mod instance;
|
||||||
|
pub mod instance_logs;
|
||||||
|
pub mod launch_profile;
|
||||||
|
mod migrate;
|
||||||
|
pub mod net;
|
||||||
|
pub mod running;
|
||||||
|
pub mod tui;
|
||||||
|
|
||||||
|
pub use cli::init as cli_init;
|
||||||
|
pub use migrate::run_legacy_rename as migrate_legacy_rename;
|
||||||
+4
-11
@@ -1,19 +1,12 @@
|
|||||||
pub mod auth;
|
|
||||||
mod cli;
|
|
||||||
pub mod config;
|
|
||||||
pub mod instance;
|
|
||||||
pub mod instance_logs;
|
|
||||||
pub mod net;
|
|
||||||
pub mod running;
|
|
||||||
pub mod tui;
|
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() {
|
async fn main() {
|
||||||
|
rmcl::migrate_legacy_rename();
|
||||||
|
|
||||||
// Guard must stay in scope to keep the log file writer alive
|
// Guard must stay in scope to keep the log file writer alive
|
||||||
let _guard = tui::logging::init();
|
let _guard = rmcl::tui::logging::init();
|
||||||
if let Err(e) = color_eyre::install() {
|
if let Err(e) = color_eyre::install() {
|
||||||
eprintln!("Failed to install color-eyre: {}", e);
|
eprintln!("Failed to install color-eyre: {}", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
cli::init().await
|
rmcl::cli_init().await
|
||||||
}
|
}
|
||||||
+293
@@ -0,0 +1,293 @@
|
|||||||
|
//! Legacy mcl→rmcl path migration. Runs once before any other init in main().
|
||||||
|
//! Idempotent: absence of the old dir is the sentinel.
|
||||||
|
|
||||||
|
use std::fs;
|
||||||
|
use std::io;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
const OLD_NAME: &str = "mcl";
|
||||||
|
const NEW_NAME: &str = "rmcl";
|
||||||
|
|
||||||
|
pub fn run_legacy_rename() {
|
||||||
|
if let Some(dir) = dirs_next::config_dir() {
|
||||||
|
rename_top_level(&dir.join(OLD_NAME), &dir.join(NEW_NAME));
|
||||||
|
}
|
||||||
|
if let Some(dir) = dirs_next::data_dir() {
|
||||||
|
let new_data = dir.join(NEW_NAME);
|
||||||
|
rename_top_level(&dir.join(OLD_NAME), &new_data);
|
||||||
|
cleanup_instance_leftovers(&new_data.join("instances"));
|
||||||
|
rewrite_linux_desktop_entries(&dir, &new_data.join("instances"));
|
||||||
|
}
|
||||||
|
if let Some(dir) = dirs_next::cache_dir() {
|
||||||
|
rename_top_level(&dir.join(OLD_NAME), &dir.join(NEW_NAME));
|
||||||
|
}
|
||||||
|
if let (Some(desk), Some(data)) = (dirs::desktop_dir(), dirs_next::data_dir()) {
|
||||||
|
rewrite_native_desktop_shortcuts(&desk, &data.join(NEW_NAME).join("instances"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rename_top_level(old: &Path, new: &Path) {
|
||||||
|
if !old.exists() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if new.exists() {
|
||||||
|
eprintln!(
|
||||||
|
"rmcl migration: both {} and {} exist; leaving as-is, please merge manually",
|
||||||
|
old.display(),
|
||||||
|
new.display()
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match fs::rename(old, new) {
|
||||||
|
Ok(_) => eprintln!("rmcl migration: moved {} -> {}", old.display(), new.display()),
|
||||||
|
Err(e) if e.kind() == io::ErrorKind::CrossesDevices => {
|
||||||
|
if let Err(e2) = copy_dir_recursive(old, new) {
|
||||||
|
eprintln!(
|
||||||
|
"rmcl migration: failed cross-device copy {} -> {}: {}",
|
||||||
|
old.display(),
|
||||||
|
new.display(),
|
||||||
|
e2
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let Err(e3) = fs::remove_dir_all(old) {
|
||||||
|
eprintln!(
|
||||||
|
"rmcl migration: copied but failed to remove {}: {}",
|
||||||
|
old.display(),
|
||||||
|
e3
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
eprintln!(
|
||||||
|
"rmcl migration: cross-device moved {} -> {}",
|
||||||
|
old.display(),
|
||||||
|
new.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(e) => eprintln!(
|
||||||
|
"rmcl migration: failed to rename {} -> {}: {}",
|
||||||
|
old.display(),
|
||||||
|
new.display(),
|
||||||
|
e
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn copy_dir_recursive(src: &Path, dst: &Path) -> io::Result<()> {
|
||||||
|
fs::create_dir_all(dst)?;
|
||||||
|
for entry in fs::read_dir(src)? {
|
||||||
|
let entry = entry?;
|
||||||
|
let ty = entry.file_type()?;
|
||||||
|
let dst_path = dst.join(entry.file_name());
|
||||||
|
if ty.is_dir() {
|
||||||
|
copy_dir_recursive(&entry.path(), &dst_path)?;
|
||||||
|
} else {
|
||||||
|
fs::copy(entry.path(), &dst_path)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cleanup_instance_leftovers(instances_dir: &Path) {
|
||||||
|
let Ok(entries) = fs::read_dir(instances_dir) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let mc = entry.path().join(".minecraft");
|
||||||
|
for leftover in [".mcl-shim.jar", ".mcl-log4j2.xml"] {
|
||||||
|
let p = mc.join(leftover);
|
||||||
|
if p.exists() {
|
||||||
|
let _ = fs::remove_file(&p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rewrite_linux_desktop_entries(_data_dir: &Path, _instances_dir: &Path) {
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
{
|
||||||
|
let apps_dir = _data_dir.join("applications");
|
||||||
|
let Ok(entries) = fs::read_dir(_instances_dir) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let name = entry.file_name();
|
||||||
|
let sanitized = sanitize(&name.to_string_lossy());
|
||||||
|
let old = apps_dir.join(format!("mcl-{sanitized}.desktop"));
|
||||||
|
let new = apps_dir.join(format!("rmcl-{sanitized}.desktop"));
|
||||||
|
if old.exists()
|
||||||
|
&& !new.exists()
|
||||||
|
&& let Ok(content) = fs::read_to_string(&old)
|
||||||
|
{
|
||||||
|
let new_content = content.replace("Exec=mcl ", "Exec=rmcl ");
|
||||||
|
if fs::write(&new, new_content).is_ok() {
|
||||||
|
let _ = fs::remove_file(&old);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rewrite_native_desktop_shortcuts(_desktop_dir: &Path, _instances_dir: &Path) {
|
||||||
|
#[cfg(any(target_os = "windows", target_os = "macos"))]
|
||||||
|
{
|
||||||
|
let ext = if cfg!(target_os = "windows") {
|
||||||
|
"bat"
|
||||||
|
} else {
|
||||||
|
"command"
|
||||||
|
};
|
||||||
|
let Ok(entries) = fs::read_dir(_instances_dir) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let display = entry.file_name().to_string_lossy().into_owned();
|
||||||
|
let path = _desktop_dir.join(format!("Minecraft - {display}.{ext}"));
|
||||||
|
if !path.exists() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Ok(content) = fs::read_to_string(&path) {
|
||||||
|
let new_content = content.replace("mcl instance launch", "rmcl instance launch");
|
||||||
|
if new_content != content {
|
||||||
|
let _ = fs::write(&path, new_content);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
fn sanitize(name: &str) -> String {
|
||||||
|
name.chars()
|
||||||
|
.map(|c| {
|
||||||
|
if c.is_alphanumeric() || c == '-' || c == '_' {
|
||||||
|
c
|
||||||
|
} else {
|
||||||
|
'_'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rename_top_level_moves_when_only_old_exists() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let old = tmp.path().join("mcl");
|
||||||
|
let new = tmp.path().join("rmcl");
|
||||||
|
fs::create_dir_all(old.join("sub")).unwrap();
|
||||||
|
fs::write(old.join("sub").join("f.txt"), b"hi").unwrap();
|
||||||
|
|
||||||
|
rename_top_level(&old, &new);
|
||||||
|
|
||||||
|
assert!(!old.exists());
|
||||||
|
assert!(new.exists());
|
||||||
|
assert_eq!(fs::read(new.join("sub").join("f.txt")).unwrap(), b"hi");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rename_top_level_skips_when_only_new_exists() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let old = tmp.path().join("mcl");
|
||||||
|
let new = tmp.path().join("rmcl");
|
||||||
|
fs::create_dir_all(&new).unwrap();
|
||||||
|
fs::write(new.join("marker.txt"), b"keep").unwrap();
|
||||||
|
|
||||||
|
rename_top_level(&old, &new);
|
||||||
|
|
||||||
|
assert!(!old.exists());
|
||||||
|
assert_eq!(fs::read(new.join("marker.txt")).unwrap(), b"keep");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rename_top_level_skips_when_both_exist() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let old = tmp.path().join("mcl");
|
||||||
|
let new = tmp.path().join("rmcl");
|
||||||
|
fs::create_dir_all(&old).unwrap();
|
||||||
|
fs::create_dir_all(&new).unwrap();
|
||||||
|
fs::write(old.join("a"), b"old").unwrap();
|
||||||
|
fs::write(new.join("b"), b"new").unwrap();
|
||||||
|
|
||||||
|
rename_top_level(&old, &new);
|
||||||
|
|
||||||
|
assert!(old.exists(), "old should remain when both exist");
|
||||||
|
assert!(new.exists(), "new should remain when both exist");
|
||||||
|
assert_eq!(fs::read(old.join("a")).unwrap(), b"old");
|
||||||
|
assert_eq!(fs::read(new.join("b")).unwrap(), b"new");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rename_top_level_noop_when_neither_exists() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let old = tmp.path().join("mcl");
|
||||||
|
let new = tmp.path().join("rmcl");
|
||||||
|
|
||||||
|
rename_top_level(&old, &new);
|
||||||
|
|
||||||
|
assert!(!old.exists());
|
||||||
|
assert!(!new.exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cleanup_instance_leftovers_removes_shim_and_log4j() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let instances = tmp.path().join("instances");
|
||||||
|
let mc = instances.join("Test").join(".minecraft");
|
||||||
|
fs::create_dir_all(&mc).unwrap();
|
||||||
|
fs::write(mc.join(".mcl-shim.jar"), b"jar").unwrap();
|
||||||
|
fs::write(mc.join(".mcl-log4j2.xml"), b"xml").unwrap();
|
||||||
|
fs::write(mc.join("keep.txt"), b"keep").unwrap();
|
||||||
|
|
||||||
|
cleanup_instance_leftovers(&instances);
|
||||||
|
|
||||||
|
assert!(!mc.join(".mcl-shim.jar").exists());
|
||||||
|
assert!(!mc.join(".mcl-log4j2.xml").exists());
|
||||||
|
assert!(mc.join("keep.txt").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
fn rewrite_linux_desktop_entries_renames_and_rewrites_exec() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let data = tmp.path();
|
||||||
|
let instances = data.join("rmcl").join("instances");
|
||||||
|
let apps = data.join("applications");
|
||||||
|
fs::create_dir_all(instances.join("MyPack")).unwrap();
|
||||||
|
fs::create_dir_all(&apps).unwrap();
|
||||||
|
let old_entry = apps.join("mcl-MyPack.desktop");
|
||||||
|
fs::write(
|
||||||
|
&old_entry,
|
||||||
|
"[Desktop Entry]\nName=Test\nExec=mcl instance launch \"MyPack\"\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
rewrite_linux_desktop_entries(data, &instances);
|
||||||
|
|
||||||
|
let new_entry = apps.join("rmcl-MyPack.desktop");
|
||||||
|
assert!(!old_entry.exists(), "old .desktop should be removed");
|
||||||
|
assert!(new_entry.exists(), "new .desktop should exist");
|
||||||
|
let content = fs::read_to_string(&new_entry).unwrap();
|
||||||
|
assert!(content.contains("Exec=rmcl instance launch \"MyPack\""));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn copy_dir_recursive_copies_nested_tree() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let src = tmp.path().join("a");
|
||||||
|
let dst = tmp.path().join("b");
|
||||||
|
fs::create_dir_all(src.join("nested")).unwrap();
|
||||||
|
fs::write(src.join("top.txt"), b"top").unwrap();
|
||||||
|
fs::write(src.join("nested").join("inner.txt"), b"inner").unwrap();
|
||||||
|
|
||||||
|
copy_dir_recursive(&src, &dst).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fs::read(dst.join("top.txt")).unwrap(), b"top");
|
||||||
|
assert_eq!(
|
||||||
|
fs::read(dst.join("nested").join("inner.txt")).unwrap(),
|
||||||
|
b"inner"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+57
-5
@@ -6,7 +6,7 @@ use std::path::Path;
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::instance::loader::GameVersion;
|
use crate::instance::loader::GameVersion;
|
||||||
use crate::net::{download_file, HttpClient, NetError};
|
use crate::net::{HttpClient, NetError, download_file};
|
||||||
use crate::tui::progress::set_sub_action;
|
use crate::tui::progress::set_sub_action;
|
||||||
|
|
||||||
const FABRIC_META_BASE: &str = "https://meta.fabricmc.net/v2";
|
const FABRIC_META_BASE: &str = "https://meta.fabricmc.net/v2";
|
||||||
@@ -45,7 +45,17 @@ pub struct FabricLibrary {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn fetch_fabric_game_versions(client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
|
pub async fn fetch_fabric_game_versions(client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
|
||||||
let url = format!("{}/versions/game", FABRIC_META_BASE);
|
fetch_fabric_game_versions_from(client, FABRIC_META_BASE).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// same as fetch_fabric_game_versions but lets tests point at a wiremock
|
||||||
|
// server. fabric's API is hierarchical, so we take the base URL and append
|
||||||
|
// the rest of the path inside.
|
||||||
|
pub async fn fetch_fabric_game_versions_from(
|
||||||
|
client: &HttpClient,
|
||||||
|
meta_base: &str,
|
||||||
|
) -> Result<Vec<GameVersion>, NetError> {
|
||||||
|
let url = format!("{}/versions/game", meta_base);
|
||||||
let versions: Vec<FabricGameVersion> = client.get_json(&url).await?;
|
let versions: Vec<FabricGameVersion> = client.get_json(&url).await?;
|
||||||
|
|
||||||
Ok(versions
|
Ok(versions
|
||||||
@@ -61,7 +71,15 @@ pub async fn fetch_fabric_versions(
|
|||||||
client: &HttpClient,
|
client: &HttpClient,
|
||||||
game_version: &str,
|
game_version: &str,
|
||||||
) -> Result<Vec<FabricLoaderVersion>, NetError> {
|
) -> Result<Vec<FabricLoaderVersion>, NetError> {
|
||||||
let url = format!("{}/versions/loader/{}", FABRIC_META_BASE, game_version);
|
fetch_fabric_versions_from(client, FABRIC_META_BASE, game_version).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn fetch_fabric_versions_from(
|
||||||
|
client: &HttpClient,
|
||||||
|
meta_base: &str,
|
||||||
|
game_version: &str,
|
||||||
|
) -> Result<Vec<FabricLoaderVersion>, NetError> {
|
||||||
|
let url = format!("{}/versions/loader/{}", meta_base, game_version);
|
||||||
client.get_json(&url).await
|
client.get_json(&url).await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,14 +87,49 @@ pub async fn fetch_fabric_profile(
|
|||||||
client: &HttpClient,
|
client: &HttpClient,
|
||||||
game_version: &str,
|
game_version: &str,
|
||||||
loader_version: &str,
|
loader_version: &str,
|
||||||
|
) -> Result<FabricProfile, NetError> {
|
||||||
|
fetch_fabric_profile_from(client, FABRIC_META_BASE, game_version, loader_version).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn fetch_fabric_profile_from(
|
||||||
|
client: &HttpClient,
|
||||||
|
meta_base: &str,
|
||||||
|
game_version: &str,
|
||||||
|
loader_version: &str,
|
||||||
) -> Result<FabricProfile, NetError> {
|
) -> Result<FabricProfile, NetError> {
|
||||||
let url = format!(
|
let url = format!(
|
||||||
"{}/versions/loader/{}/{}/profile/json",
|
"{}/versions/loader/{}/{}/profile/json",
|
||||||
FABRIC_META_BASE, game_version, loader_version
|
meta_base, game_version, loader_version
|
||||||
);
|
);
|
||||||
client.get_json(&url).await
|
client.get_json(&url).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// like fetch_fabric_profile but also returns the raw response bytes so the
|
||||||
|
// caller can write the upstream JSON byte-for-byte to disk. used by the
|
||||||
|
// install path so we don't lose data (e.g. any future arguments field) by
|
||||||
|
// re-serializing through our narrow FabricProfile struct.
|
||||||
|
pub async fn fetch_fabric_profile_with_raw(
|
||||||
|
client: &HttpClient,
|
||||||
|
game_version: &str,
|
||||||
|
loader_version: &str,
|
||||||
|
) -> Result<(FabricProfile, Vec<u8>), NetError> {
|
||||||
|
fetch_fabric_profile_with_raw_from(client, FABRIC_META_BASE, game_version, loader_version)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn fetch_fabric_profile_with_raw_from(
|
||||||
|
client: &HttpClient,
|
||||||
|
meta_base: &str,
|
||||||
|
game_version: &str,
|
||||||
|
loader_version: &str,
|
||||||
|
) -> Result<(FabricProfile, Vec<u8>), NetError> {
|
||||||
|
let url = format!(
|
||||||
|
"{}/versions/loader/{}/{}/profile/json",
|
||||||
|
meta_base, game_version, loader_version
|
||||||
|
);
|
||||||
|
client.get_json_with_raw(&url, "Fabric profile").await
|
||||||
|
}
|
||||||
|
|
||||||
// each fabric library entry has a maven coordinate and a base url.
|
// each fabric library entry has a maven coordinate and a base url.
|
||||||
// the coordinate gets resolved to a path and combined with the url to download.
|
// the coordinate gets resolved to a path and combined with the url to download.
|
||||||
pub async fn download_fabric_libraries(
|
pub async fn download_fabric_libraries(
|
||||||
@@ -152,5 +205,4 @@ mod tests {
|
|||||||
Err(e) => panic!("fetch_fabric_game_versions failed: {}", e),
|
Err(e) => panic!("fetch_fabric_game_versions failed: {}", e),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
+250
-17
@@ -1,6 +1,6 @@
|
|||||||
// forge mod loader: version discovery via promotions API, then download
|
// forge mod loader: version discovery via promotions API, download and
|
||||||
// and run the installer jar. forge doesn't have a nice metadata API like
|
// installation. modern forge runs a java installer, old forge (pre-1.13ish)
|
||||||
// fabric/quilt, so it shells out to java to run their installer.
|
// doesn't support headless install so we extract directly from the jar.
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
@@ -9,7 +9,7 @@ use serde::Deserialize;
|
|||||||
|
|
||||||
use crate::instance::loader::GameVersion;
|
use crate::instance::loader::GameVersion;
|
||||||
use crate::net::{HttpClient, NetError, download_file};
|
use crate::net::{HttpClient, NetError, download_file};
|
||||||
use crate::tui::progress::set_action;
|
use crate::tui::progress::{set_action, set_sub_action};
|
||||||
|
|
||||||
const FORGE_PROMOTIONS_URL: &str =
|
const FORGE_PROMOTIONS_URL: &str =
|
||||||
"https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json";
|
"https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json";
|
||||||
@@ -26,7 +26,16 @@ pub async fn fetch_forge_versions(
|
|||||||
client: &HttpClient,
|
client: &HttpClient,
|
||||||
game_version: &str,
|
game_version: &str,
|
||||||
) -> Result<Vec<String>, NetError> {
|
) -> Result<Vec<String>, NetError> {
|
||||||
let promotions: ForgePromotions = client.get_json(FORGE_PROMOTIONS_URL).await?;
|
fetch_forge_versions_from(client, FORGE_PROMOTIONS_URL, game_version).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// same as fetch_forge_versions but lets tests point at a wiremock server.
|
||||||
|
pub async fn fetch_forge_versions_from(
|
||||||
|
client: &HttpClient,
|
||||||
|
promotions_url: &str,
|
||||||
|
game_version: &str,
|
||||||
|
) -> Result<Vec<String>, NetError> {
|
||||||
|
let promotions: ForgePromotions = client.get_json(promotions_url).await?;
|
||||||
|
|
||||||
let prefix = format!("{}-", game_version);
|
let prefix = format!("{}-", game_version);
|
||||||
let mut versions: Vec<String> = promotions
|
let mut versions: Vec<String> = promotions
|
||||||
@@ -44,7 +53,14 @@ pub async fn fetch_forge_versions(
|
|||||||
// extracts unique game versions from the promotion keys by splitting off
|
// extracts unique game versions from the promotion keys by splitting off
|
||||||
// the "-recommended"/"-latest" suffix
|
// the "-recommended"/"-latest" suffix
|
||||||
pub async fn fetch_forge_game_versions(client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
|
pub async fn fetch_forge_game_versions(client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
|
||||||
let promos: ForgePromotions = client.get_json(FORGE_PROMOTIONS_URL).await?;
|
fetch_forge_game_versions_from(client, FORGE_PROMOTIONS_URL).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn fetch_forge_game_versions_from(
|
||||||
|
client: &HttpClient,
|
||||||
|
promotions_url: &str,
|
||||||
|
) -> Result<Vec<GameVersion>, NetError> {
|
||||||
|
let promos: ForgePromotions = client.get_json(promotions_url).await?;
|
||||||
|
|
||||||
let mut game_versions: Vec<String> = promos
|
let mut game_versions: Vec<String> = promos
|
||||||
.promos
|
.promos
|
||||||
@@ -64,28 +80,45 @@ pub async fn fetch_forge_game_versions(client: &HttpClient) -> Result<Vec<GameVe
|
|||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// forge has used at least three different maven naming conventions over the
|
||||||
|
// years with no clear cutoff. we just try each one until something works.
|
||||||
pub async fn download_forge_installer(
|
pub async fn download_forge_installer(
|
||||||
client: &HttpClient,
|
client: &HttpClient,
|
||||||
game_version: &str,
|
game_version: &str,
|
||||||
forge_version: &str,
|
forge_version: &str,
|
||||||
dest: &Path,
|
dest: &Path,
|
||||||
) -> Result<(), NetError> {
|
) -> Result<(), NetError> {
|
||||||
let url = format!(
|
let mc_no_dots: String = game_version.chars().filter(|c| *c != '.').collect();
|
||||||
"{}/{game_version}-{forge_version}/forge-{game_version}-{forge_version}-installer.jar",
|
|
||||||
FORGE_MAVEN_BASE,
|
let slugs = [
|
||||||
game_version = game_version,
|
format!("{game_version}-{forge_version}"),
|
||||||
forge_version = forge_version,
|
format!("{game_version}-{forge_version}-{game_version}"),
|
||||||
);
|
format!("{game_version}-{forge_version}-mc{mc_no_dots}"),
|
||||||
|
];
|
||||||
|
|
||||||
set_action(format!(
|
set_action(format!(
|
||||||
"Downloading Forge {}-{}...",
|
"Downloading Forge {}-{}...",
|
||||||
game_version, forge_version
|
game_version, forge_version
|
||||||
));
|
));
|
||||||
|
|
||||||
download_file(client, &url, dest, |downloaded, total| {
|
let mut last_err = None;
|
||||||
|
for slug in &slugs {
|
||||||
|
let url = format!("{}/{slug}/forge-{slug}-installer.jar", FORGE_MAVEN_BASE,);
|
||||||
|
match download_file(client, &url, dest, |downloaded, total| {
|
||||||
crate::tui::progress::set_progress(downloaded, total);
|
crate::tui::progress::set_progress(downloaded, total);
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
|
{
|
||||||
|
Ok(()) => return Ok(()),
|
||||||
|
Err(e) => last_err = Some(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Err(last_err.unwrap_or_else(|| {
|
||||||
|
NetError::Parse(format!(
|
||||||
|
"No Forge installer found for {game_version}-{forge_version}"
|
||||||
|
))
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn run_forge_installer(
|
pub async fn run_forge_installer(
|
||||||
@@ -112,15 +145,162 @@ pub async fn run_forge_installer(
|
|||||||
};
|
};
|
||||||
|
|
||||||
if !output.status.success() {
|
if !output.status.success() {
|
||||||
return Err(NetError::InstallerFailed(format!(
|
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||||
"Forge installer exited with {:?}",
|
let detail = if stderr.trim().is_empty() {
|
||||||
output.status.code()
|
format!("exit code {:?}", output.status.code())
|
||||||
)));
|
} else {
|
||||||
|
stderr.lines().last().unwrap_or("unknown error").to_string()
|
||||||
|
};
|
||||||
|
return Err(NetError::InstallerFailed(detail));
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
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<(), NetError> {
|
||||||
|
use std::io::Read;
|
||||||
|
|
||||||
|
set_action("Installing legacy Forge from profile...");
|
||||||
|
|
||||||
|
let file = std::fs::File::open(installer_path)?;
|
||||||
|
let mut archive = zip::ZipArchive::new(file)
|
||||||
|
.map_err(|e| NetError::Parse(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| {
|
||||||
|
NetError::Parse(format!("install_profile.json not found in installer: {e}"))
|
||||||
|
})?;
|
||||||
|
serde_json::from_reader(entry)
|
||||||
|
.map_err(|e| NetError::Parse(format!("Failed to parse install_profile.json: {e}")))?
|
||||||
|
};
|
||||||
|
|
||||||
|
let version_info = profile_data
|
||||||
|
.get("versionInfo")
|
||||||
|
.ok_or_else(|| NetError::Parse("install_profile.json missing versionInfo".into()))?;
|
||||||
|
let install_info = profile_data
|
||||||
|
.get("install")
|
||||||
|
.ok_or_else(|| NetError::Parse("install_profile.json missing install section".into()))?;
|
||||||
|
|
||||||
|
let libraries = version_info
|
||||||
|
.get("libraries")
|
||||||
|
.and_then(|v| v.as_array())
|
||||||
|
.ok_or_else(|| NetError::Parse("missing versionInfo.libraries".into()))?;
|
||||||
|
|
||||||
|
let file_path = install_info
|
||||||
|
.get("filePath")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.ok_or_else(|| NetError::Parse("missing install.filePath".into()))?;
|
||||||
|
|
||||||
|
let install_path_coord = install_info
|
||||||
|
.get("path")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.ok_or_else(|| NetError::Parse("missing install.path".into()))?;
|
||||||
|
|
||||||
|
// extract the universal jar to the correct maven location
|
||||||
|
let universal_maven_path =
|
||||||
|
crate::net::maven_coord_to_path(install_path_coord).ok_or_else(|| {
|
||||||
|
NetError::Parse(format!(
|
||||||
|
"Invalid maven coord in install.path: {install_path_coord}"
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
set_sub_action("Extracting universal JAR...");
|
||||||
|
let universal_dest = meta_dir.join("libraries").join(&universal_maven_path);
|
||||||
|
if let Some(parent) = universal_dest.parent() {
|
||||||
|
std::fs::create_dir_all(parent)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut entry = archive.by_name(file_path).map_err(|e| {
|
||||||
|
NetError::Parse(format!(
|
||||||
|
"Universal JAR '{file_path}' not found in installer: {e}"
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
entry.read_to_end(&mut buf)?;
|
||||||
|
std::fs::write(&universal_dest, &buf)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 = meta_dir.join("libraries");
|
||||||
|
for lib in libraries {
|
||||||
|
let name = lib.get("name").and_then(|v| v.as_str()).unwrap_or_default();
|
||||||
|
|
||||||
|
let maven_path = match crate::net::maven_coord_to_path(name) {
|
||||||
|
Some(p) => p,
|
||||||
|
None => {
|
||||||
|
return Err(NetError::Parse(format!("Invalid Maven coordinate: {name}")));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let dest = libraries_dir.join(&maven_path);
|
||||||
|
if dest.exists() {
|
||||||
|
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);
|
||||||
|
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| NetError::Parse(format!("Failed to serialize Forge profile: {e}")))?;
|
||||||
|
crate::instance::loader::save_profile_bytes(meta_dir, profile_filename, &serialized)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -153,4 +333,57 @@ mod tests {
|
|||||||
Err(e) => panic!("fetch_forge_game_versions failed: {}", e),
|
Err(e) => panic!("fetch_forge_game_versions failed: {}", e),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// builds an in-memory zip in a tempdir with the given json as
|
||||||
|
// install_profile.json. lets the legacy-install-profile detector be
|
||||||
|
// tested without an actual forge installer.
|
||||||
|
fn make_installer_zip(tmp: &std::path::Path, json: &serde_json::Value) -> std::path::PathBuf {
|
||||||
|
use std::io::Write;
|
||||||
|
let path = tmp.join("installer.jar");
|
||||||
|
let file = std::fs::File::create(&path).unwrap();
|
||||||
|
let mut zip = zip::ZipWriter::new(file);
|
||||||
|
let opts: zip::write::SimpleFileOptions = Default::default();
|
||||||
|
zip.start_file("install_profile.json", opts).unwrap();
|
||||||
|
zip.write_all(serde_json::to_string(json).unwrap().as_bytes())
|
||||||
|
.unwrap();
|
||||||
|
zip.finish().unwrap();
|
||||||
|
path
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn has_legacy_install_profile_true_when_version_info_present() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let jar = make_installer_zip(
|
||||||
|
tmp.path(),
|
||||||
|
&serde_json::json!({
|
||||||
|
"install": {},
|
||||||
|
"versionInfo": {
|
||||||
|
"id": "1.7.10-Forge10.13.4.1614-1.7.10",
|
||||||
|
"mainClass": "net.minecraft.launchwrapper.Launch"
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
assert!(has_legacy_install_profile(&jar));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn has_legacy_install_profile_false_when_version_info_absent() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let jar = make_installer_zip(
|
||||||
|
tmp.path(),
|
||||||
|
&serde_json::json!({
|
||||||
|
"spec": 1,
|
||||||
|
"minecraft": "1.20.1",
|
||||||
|
"data": {}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
assert!(!has_legacy_install_profile(&jar));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn has_legacy_install_profile_false_for_missing_jar() {
|
||||||
|
assert!(!has_legacy_install_profile(std::path::Path::new(
|
||||||
|
"/nonexistent/installer.jar"
|
||||||
|
)));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+109
-8
@@ -44,7 +44,7 @@ impl HttpClient {
|
|||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
let client = Client::builder()
|
let client = Client::builder()
|
||||||
.user_agent(format!(
|
.user_agent(format!(
|
||||||
"mcl/{} (Minecraft Launcher)",
|
"rmcl/{} (Minecraft Launcher)",
|
||||||
env!("CARGO_PKG_VERSION")
|
env!("CARGO_PKG_VERSION")
|
||||||
))
|
))
|
||||||
.timeout(std::time::Duration::from_secs(30))
|
.timeout(std::time::Duration::from_secs(30))
|
||||||
@@ -69,18 +69,112 @@ impl HttpClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_json<T: DeserializeOwned>(&self, url: &str) -> Result<T, NetError> {
|
pub async fn get_json<T: DeserializeOwned>(&self, url: &str) -> Result<T, NetError> {
|
||||||
Ok(self.get(url).await?.json().await?)
|
get_with_retry(self, url, |resp| async move { Ok(resp.json().await?) }).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_bytes(&self, url: &str) -> Result<Vec<u8>, NetError> {
|
||||||
|
get_with_retry(
|
||||||
|
self,
|
||||||
|
url,
|
||||||
|
|resp| async move { Ok(resp.bytes().await?.to_vec()) },
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetch JSON and also keep the raw bytes. used by install paths that
|
||||||
|
// want both the parsed shape (for downloading libraries from it) and
|
||||||
|
// the original bytes (to write byte-for-byte to the loader-profiles
|
||||||
|
// cache, so any field we don't know about survives).
|
||||||
|
pub async fn get_json_with_raw<T: DeserializeOwned>(
|
||||||
|
&self,
|
||||||
|
url: &str,
|
||||||
|
label: &str,
|
||||||
|
) -> Result<(T, Vec<u8>), NetError> {
|
||||||
|
let raw = self.get_bytes(url).await?;
|
||||||
|
let parsed: T = serde_json::from_slice(&raw)
|
||||||
|
.map_err(|e| NetError::Parse(format!("Failed to parse {label}: {e}")))?;
|
||||||
|
Ok((parsed, raw))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// shared retry envelope around `client.get(url).await? -> decode`. retries
|
||||||
|
// transient failures (timeouts, connect errors, 5xx) with exponential
|
||||||
|
// backoff. used by both get_json and get_bytes.
|
||||||
|
async fn get_with_retry<T, F, Fut>(client: &HttpClient, url: &str, decode: F) -> Result<T, NetError>
|
||||||
|
where
|
||||||
|
F: Fn(reqwest::Response) -> Fut,
|
||||||
|
Fut: std::future::Future<Output = Result<T, NetError>>,
|
||||||
|
{
|
||||||
|
let mut last_error = None;
|
||||||
|
for attempt in 0..=MAX_RETRIES {
|
||||||
|
if attempt > 0 {
|
||||||
|
let delay = RETRY_BASE_DELAY_MS * 2u64.pow(attempt - 1);
|
||||||
|
tracing::warn!(
|
||||||
|
"retrying request (attempt {}/{}): {}",
|
||||||
|
attempt + 1,
|
||||||
|
MAX_RETRIES + 1,
|
||||||
|
url
|
||||||
|
);
|
||||||
|
tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
match client.get(url).await {
|
||||||
|
Ok(resp) => match decode(resp).await {
|
||||||
|
Ok(value) => return Ok(value),
|
||||||
|
Err(e) if is_retryable(&e) => last_error = Some(e),
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
},
|
||||||
|
Err(e) if is_retryable(&e) => last_error = Some(e),
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(last_error.unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_RETRIES: u32 = 3;
|
||||||
|
const RETRY_BASE_DELAY_MS: u64 = 500;
|
||||||
|
|
||||||
// streams a file to disk in chunks, calling progress_cb(downloaded, total) along the way.
|
// streams a file to disk in chunks, calling progress_cb(downloaded, total) along the way.
|
||||||
// total will be 0 if the server doesn't send content-length, so callers
|
// total will be 0 if the server doesn't send content-length, so callers
|
||||||
// should handle that gracefully.
|
// should handle that gracefully. retries transient failures with exponential backoff.
|
||||||
pub async fn download_file(
|
pub async fn download_file(
|
||||||
client: &HttpClient,
|
client: &HttpClient,
|
||||||
url: &str,
|
url: &str,
|
||||||
dest: &Path,
|
dest: &Path,
|
||||||
progress_cb: impl Fn(u64, u64),
|
progress_cb: impl Fn(u64, u64),
|
||||||
|
) -> Result<(), NetError> {
|
||||||
|
let mut last_error = None;
|
||||||
|
|
||||||
|
for attempt in 0..=MAX_RETRIES {
|
||||||
|
if attempt > 0 {
|
||||||
|
let delay = RETRY_BASE_DELAY_MS * 2u64.pow(attempt - 1);
|
||||||
|
tracing::warn!(
|
||||||
|
"retrying download (attempt {}/{}): {}",
|
||||||
|
attempt + 1,
|
||||||
|
MAX_RETRIES + 1,
|
||||||
|
url
|
||||||
|
);
|
||||||
|
tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
match download_file_once(client, url, dest, &progress_cb).await {
|
||||||
|
Ok(()) => return Ok(()),
|
||||||
|
Err(e) if is_retryable(&e) => {
|
||||||
|
last_error = Some(e);
|
||||||
|
}
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Err(last_error.unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
// single attempt at downloading a file to disk
|
||||||
|
async fn download_file_once(
|
||||||
|
client: &HttpClient,
|
||||||
|
url: &str,
|
||||||
|
dest: &Path,
|
||||||
|
progress_cb: &impl Fn(u64, u64),
|
||||||
) -> Result<(), NetError> {
|
) -> Result<(), NetError> {
|
||||||
use tokio::io::AsyncWriteExt;
|
use tokio::io::AsyncWriteExt;
|
||||||
|
|
||||||
@@ -104,6 +198,18 @@ pub async fn download_file(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// body decode errors and timeouts are worth retrying, but a 404 or disk
|
||||||
|
// error isn't. Parse errors stay non-retryable: by the time we hit one
|
||||||
|
// the response body has fully arrived, so the failure means the upstream
|
||||||
|
// returned malformed JSON - retrying won't fix that.
|
||||||
|
fn is_retryable(err: &NetError) -> bool {
|
||||||
|
match err {
|
||||||
|
NetError::Http(e) => e.is_timeout() || e.is_body() || e.is_connect(),
|
||||||
|
NetError::StatusError { status, .. } => *status >= 500,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// tries JAVA_HOME first, then PATH, then just yolos "java" and hopes for the best
|
// tries JAVA_HOME first, then PATH, then just yolos "java" and hopes for the best
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn detect_java_path() -> String {
|
pub fn detect_java_path() -> String {
|
||||||
@@ -192,9 +298,4 @@ mod tests {
|
|||||||
assert_eq!(maven_coord_to_path(""), None);
|
assert_eq!(maven_coord_to_path(""), None);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn detect_java_falls_back_to_java() {
|
|
||||||
let result = detect_java_path();
|
|
||||||
assert!(!result.is_empty());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
+23
-93
@@ -1,5 +1,5 @@
|
|||||||
// modrinth modpack support: parses URLs/slugs, fetches project metadata,
|
// modrinth modpack support: fetches project metadata, downloads .mrpack files,
|
||||||
// downloads .mrpack files, and extracts loader info from pack manifests.
|
// and extracts loader info from pack manifests.
|
||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@@ -51,49 +51,13 @@ pub struct MrpackFile {
|
|||||||
pub file_size: u64,
|
pub file_size: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
|
||||||
pub enum ModrinthInput {
|
|
||||||
ProjectSlug(String),
|
|
||||||
VersionId { slug: String, version_id: String },
|
|
||||||
LocalFile(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
// figures out what the user gave us: a modrinth URL, a local .mrpack file,
|
|
||||||
// or just a project slug. accepts a pretty wide range of inputs so users
|
|
||||||
// don't have to think about it.
|
|
||||||
pub fn parse_input(input: &str) -> ModrinthInput {
|
|
||||||
let input = input.trim();
|
|
||||||
|
|
||||||
if input.ends_with(".mrpack")
|
|
||||||
|| input.starts_with('/')
|
|
||||||
|| input.starts_with("~/")
|
|
||||||
{
|
|
||||||
return ModrinthInput::LocalFile(input.to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(rest) = input
|
|
||||||
.strip_prefix("https://modrinth.com/modpack/")
|
|
||||||
.or_else(|| input.strip_prefix("http://modrinth.com/modpack/"))
|
|
||||||
{
|
|
||||||
let parts: Vec<&str> = rest.split('/').filter(|s| !s.is_empty()).collect();
|
|
||||||
return match parts.as_slice() {
|
|
||||||
[slug, "version", version_id, ..] => ModrinthInput::VersionId {
|
|
||||||
slug: slug.to_string(),
|
|
||||||
version_id: version_id.to_string(),
|
|
||||||
},
|
|
||||||
[slug, ..] => ModrinthInput::ProjectSlug(slug.to_string()),
|
|
||||||
[] => ModrinthInput::ProjectSlug(String::new()),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
ModrinthInput::ProjectSlug(input.to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
use crate::instance::models::ModLoader;
|
use crate::instance::models::ModLoader;
|
||||||
|
|
||||||
// mrpack dependencies use keys like "fabric-loader", "forge", etc.
|
// mrpack dependencies use keys like "fabric-loader", "forge", etc.
|
||||||
// checks in priority order and returns the first match.
|
// checks in priority order and returns the first match.
|
||||||
pub fn loader_from_dependencies(deps: &HashMap<String, String>) -> (Option<ModLoader>, Option<String>) {
|
pub fn loader_from_dependencies(
|
||||||
|
deps: &HashMap<String, String>,
|
||||||
|
) -> (Option<ModLoader>, Option<String>) {
|
||||||
let loaders = [
|
let loaders = [
|
||||||
("fabric-loader", ModLoader::Fabric),
|
("fabric-loader", ModLoader::Fabric),
|
||||||
("forge", ModLoader::Forge),
|
("forge", ModLoader::Forge),
|
||||||
@@ -146,7 +110,8 @@ pub async fn fetch_versions(
|
|||||||
) -> Result<Vec<VersionInfo>, crate::net::NetError> {
|
) -> Result<Vec<VersionInfo>, crate::net::NetError> {
|
||||||
let url = format!(
|
let url = format!(
|
||||||
"{}/project/{}/version?loaders=[\"fabric\",\"forge\",\"neoforge\",\"quilt\"]",
|
"{}/project/{}/version?loaders=[\"fabric\",\"forge\",\"neoforge\",\"quilt\"]",
|
||||||
API_BASE, url_encode(slug_or_id)
|
API_BASE,
|
||||||
|
url_encode(slug_or_id)
|
||||||
);
|
);
|
||||||
client.get_json(&url).await
|
client.get_json(&url).await
|
||||||
}
|
}
|
||||||
@@ -192,56 +157,18 @@ pub fn parse_mrpack(path: &std::path::Path) -> Result<MrpackIndex, String> {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
// covers each branch of url_encode: unreserved bytes pass through; the
|
||||||
fn parse_project_url() {
|
// reserved set + spaces + non-ascii bytes get percent-encoded. emoji
|
||||||
assert_eq!(
|
// exercises multi-byte UTF-8 since the encoder operates on bytes, not
|
||||||
parse_input("https://modrinth.com/modpack/fabulously-optimized"),
|
// chars, so each byte of the codepoint encodes separately.
|
||||||
ModrinthInput::ProjectSlug("fabulously-optimized".to_string())
|
#[rstest::rstest]
|
||||||
);
|
#[case::ascii_unreserved("abcXYZ0-9_.~", "abcXYZ0-9_.~")]
|
||||||
}
|
#[case::space("hello world", "hello%20world")]
|
||||||
|
#[case::reserved("/?&=#", "%2F%3F%26%3D%23")]
|
||||||
#[test]
|
#[case::utf8_emoji("\u{2603}", "%E2%98%83")]
|
||||||
fn parse_version_url() {
|
#[case::empty("", "")]
|
||||||
let result = parse_input("https://modrinth.com/modpack/fabulously-optimized/version/abc123");
|
fn url_encode_handles(#[case] input: &str, #[case] expected: &str) {
|
||||||
assert_eq!(
|
assert_eq!(url_encode(input), expected);
|
||||||
result,
|
|
||||||
ModrinthInput::VersionId {
|
|
||||||
slug: "fabulously-optimized".to_string(),
|
|
||||||
version_id: "abc123".to_string(),
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parse_local_mrpack() {
|
|
||||||
assert_eq!(
|
|
||||||
parse_input("/home/user/pack.mrpack"),
|
|
||||||
ModrinthInput::LocalFile("/home/user/pack.mrpack".to_string())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parse_tilde_path() {
|
|
||||||
assert_eq!(
|
|
||||||
parse_input("~/Downloads/pack.mrpack"),
|
|
||||||
ModrinthInput::LocalFile("~/Downloads/pack.mrpack".to_string())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parse_bare_slug() {
|
|
||||||
assert_eq!(
|
|
||||||
parse_input("fabulously-optimized"),
|
|
||||||
ModrinthInput::ProjectSlug("fabulously-optimized".to_string())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parse_input_trims_whitespace() {
|
|
||||||
assert_eq!(
|
|
||||||
parse_input(" fabulously-optimized "),
|
|
||||||
ModrinthInput::ProjectSlug("fabulously-optimized".to_string())
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -277,7 +204,10 @@ mod tests {
|
|||||||
fn game_version_from_deps() {
|
fn game_version_from_deps() {
|
||||||
let mut deps = HashMap::new();
|
let mut deps = HashMap::new();
|
||||||
deps.insert("minecraft".to_string(), "1.21.4".to_string());
|
deps.insert("minecraft".to_string(), "1.21.4".to_string());
|
||||||
assert_eq!(game_version_from_dependencies(&deps), Some("1.21.4".to_string()));
|
assert_eq!(
|
||||||
|
game_version_from_dependencies(&deps),
|
||||||
|
Some("1.21.4".to_string())
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
+43
-63
@@ -76,7 +76,7 @@ pub struct Download {
|
|||||||
pub struct Library {
|
pub struct Library {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub downloads: LibraryDownloads,
|
pub downloads: LibraryDownloads,
|
||||||
pub rules: Option<Vec<Rule>>,
|
pub rules: Option<Vec<crate::launch_profile::rules::Rule>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
@@ -92,17 +92,6 @@ pub struct Artifact {
|
|||||||
pub size: u64,
|
pub size: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
||||||
pub struct Rule {
|
|
||||||
pub action: String,
|
|
||||||
pub os: Option<OsRule>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
||||||
pub struct OsRule {
|
|
||||||
pub name: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct JavaVersion {
|
pub struct JavaVersion {
|
||||||
@@ -121,14 +110,28 @@ pub struct AssetObject {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn fetch_version_manifest(client: &HttpClient) -> Result<VersionManifest, NetError> {
|
pub async fn fetch_version_manifest(client: &HttpClient) -> Result<VersionManifest, NetError> {
|
||||||
client.get_json(MANIFEST_URL).await
|
fetch_version_manifest_from(client, MANIFEST_URL).await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn fetch_version_meta(
|
// same as fetch_version_manifest but lets the caller pick the URL. exists so
|
||||||
|
// integration tests can point at a wiremock server; production callers go
|
||||||
|
// through fetch_version_manifest with the upstream Mojang URL.
|
||||||
|
pub async fn fetch_version_manifest_from(
|
||||||
|
client: &HttpClient,
|
||||||
|
url: &str,
|
||||||
|
) -> Result<VersionManifest, NetError> {
|
||||||
|
client.get_json(url).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetches and parses a version's metadata. also returns the raw response
|
||||||
|
// bytes so the caller can write the upstream JSON byte-for-byte to disk
|
||||||
|
// - used by the install path so we don't lose data (e.g. arguments.jvm)
|
||||||
|
// by re-serializing through our narrow VersionMeta struct.
|
||||||
|
pub async fn fetch_version_meta_with_raw(
|
||||||
client: &HttpClient,
|
client: &HttpClient,
|
||||||
entry: &VersionEntry,
|
entry: &VersionEntry,
|
||||||
) -> Result<VersionMeta, NetError> {
|
) -> Result<(VersionMeta, Vec<u8>), NetError> {
|
||||||
client.get_json(&entry.url).await
|
client.get_json_with_raw(&entry.url, "version meta").await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn download_client_jar(
|
pub async fn download_client_jar(
|
||||||
@@ -169,9 +172,20 @@ pub async fn download_libraries(
|
|||||||
) -> Result<(), NetError> {
|
) -> Result<(), NetError> {
|
||||||
set_action("Downloading libraries...");
|
set_action("Downloading libraries...");
|
||||||
|
|
||||||
|
let features = crate::launch_profile::rules::FeatureSet::default();
|
||||||
|
let host_os_version = crate::launch_profile::system::mojang_os_version();
|
||||||
|
let rule_ctx = crate::launch_profile::rules::RuleContext {
|
||||||
|
os_name: crate::launch_profile::system::mojang_os_name(),
|
||||||
|
os_version: &host_os_version,
|
||||||
|
arch: crate::launch_profile::system::mojang_arch_name(),
|
||||||
|
features: &features,
|
||||||
|
};
|
||||||
|
|
||||||
let mut downloads = Vec::new();
|
let mut downloads = Vec::new();
|
||||||
for library in &meta.libraries {
|
for library in &meta.libraries {
|
||||||
if !library_allowed_for_current_os(library) {
|
if let Some(rules) = &library.rules
|
||||||
|
&& !crate::launch_profile::rules::evaluate(rules, &rule_ctx)
|
||||||
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -204,6 +218,17 @@ pub async fn download_assets(
|
|||||||
client: &HttpClient,
|
client: &HttpClient,
|
||||||
meta: &VersionMeta,
|
meta: &VersionMeta,
|
||||||
meta_dir: &Path,
|
meta_dir: &Path,
|
||||||
|
) -> Result<(), NetError> {
|
||||||
|
download_assets_from(client, meta, meta_dir, ASSETS_BASE_URL).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// same as download_assets but lets tests point at a wiremock server for the
|
||||||
|
// per-asset CDN downloads. the asset index URL still comes from meta.
|
||||||
|
pub async fn download_assets_from(
|
||||||
|
client: &HttpClient,
|
||||||
|
meta: &VersionMeta,
|
||||||
|
meta_dir: &Path,
|
||||||
|
assets_base: &str,
|
||||||
) -> Result<(), NetError> {
|
) -> Result<(), NetError> {
|
||||||
set_action("Downloading assets...");
|
set_action("Downloading assets...");
|
||||||
|
|
||||||
@@ -256,7 +281,7 @@ pub async fn download_assets(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let prefix = &object.hash[..2];
|
let prefix = &object.hash[..2];
|
||||||
let url = format!("{}/{}/{}", ASSETS_BASE_URL, prefix, object.hash);
|
let url = format!("{}/{}/{}", assets_base, prefix, object.hash);
|
||||||
let destination = meta_dir
|
let destination = meta_dir
|
||||||
.join("assets")
|
.join("assets")
|
||||||
.join("objects")
|
.join("objects")
|
||||||
@@ -281,51 +306,6 @@ pub async fn download_assets(
|
|||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
// mojang's rule system is a bit quirky: no rules means "allow everywhere",
|
|
||||||
// and rules are evaluated in order where the last matching rule wins.
|
|
||||||
// a "disallow" for the current OS is an immediate reject though.
|
|
||||||
fn library_allowed_for_current_os(library: &Library) -> bool {
|
|
||||||
let rules = match &library.rules {
|
|
||||||
Some(rules) => rules,
|
|
||||||
None => return true,
|
|
||||||
};
|
|
||||||
|
|
||||||
let current_os = mojang_os_name();
|
|
||||||
let mut allowed = false;
|
|
||||||
|
|
||||||
for rule in rules {
|
|
||||||
let matches_os = match &rule.os {
|
|
||||||
Some(os_rule) => match &os_rule.name {
|
|
||||||
Some(name) => name == current_os,
|
|
||||||
None => true,
|
|
||||||
},
|
|
||||||
None => true,
|
|
||||||
};
|
|
||||||
|
|
||||||
if !matches_os {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if rule.action == "disallow" {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if rule.action == "allow" {
|
|
||||||
allowed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
allowed
|
|
||||||
}
|
|
||||||
|
|
||||||
// mojang calls macOS "osx" because apparently it's still 2012
|
|
||||||
fn mojang_os_name() -> &'static str {
|
|
||||||
match std::env::consts::OS {
|
|
||||||
"macos" => "osx",
|
|
||||||
other => other,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// bounded parallel downloader. spawns up to MAX_CONCURRENT_DOWNLOADS tasks
|
// bounded parallel downloader. spawns up to MAX_CONCURRENT_DOWNLOADS tasks
|
||||||
// and feeds new ones in as each completes. collects errors but keeps going
|
// and feeds new ones in as each completes. collects errors but keeps going
|
||||||
// so it downloads as much as possible before reporting the first failure.
|
// so it downloads as much as possible before reporting the first failure.
|
||||||
|
|||||||
+18
-2
@@ -36,6 +36,15 @@ fn game_version_to_neoforge_prefix(game_version: &str) -> Option<String> {
|
|||||||
pub async fn fetch_neoforge_versions(
|
pub async fn fetch_neoforge_versions(
|
||||||
client: &HttpClient,
|
client: &HttpClient,
|
||||||
game_version: &str,
|
game_version: &str,
|
||||||
|
) -> Result<Vec<String>, NetError> {
|
||||||
|
fetch_neoforge_versions_from(client, NEOFORGE_API_BASE, game_version).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// same as fetch_neoforge_versions but lets tests point at a wiremock server.
|
||||||
|
pub async fn fetch_neoforge_versions_from(
|
||||||
|
client: &HttpClient,
|
||||||
|
api_url: &str,
|
||||||
|
game_version: &str,
|
||||||
) -> Result<Vec<String>, NetError> {
|
) -> Result<Vec<String>, NetError> {
|
||||||
let prefix = match game_version_to_neoforge_prefix(game_version) {
|
let prefix = match game_version_to_neoforge_prefix(game_version) {
|
||||||
Some(p) => p,
|
Some(p) => p,
|
||||||
@@ -47,7 +56,7 @@ pub async fn fetch_neoforge_versions(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let maven_versions: NeoForgeMavenVersions = client.get_json(NEOFORGE_API_BASE).await?;
|
let maven_versions: NeoForgeMavenVersions = client.get_json(api_url).await?;
|
||||||
|
|
||||||
let versions: Vec<String> = maven_versions
|
let versions: Vec<String> = maven_versions
|
||||||
.versions
|
.versions
|
||||||
@@ -63,7 +72,14 @@ pub async fn fetch_neoforge_versions(
|
|||||||
pub async fn fetch_neoforge_game_versions(
|
pub async fn fetch_neoforge_game_versions(
|
||||||
client: &HttpClient,
|
client: &HttpClient,
|
||||||
) -> Result<Vec<GameVersion>, NetError> {
|
) -> Result<Vec<GameVersion>, NetError> {
|
||||||
let maven: NeoForgeMavenVersions = client.get_json(NEOFORGE_API_BASE).await?;
|
fetch_neoforge_game_versions_from(client, NEOFORGE_API_BASE).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn fetch_neoforge_game_versions_from(
|
||||||
|
client: &HttpClient,
|
||||||
|
api_url: &str,
|
||||||
|
) -> Result<Vec<GameVersion>, NetError> {
|
||||||
|
let maven: NeoForgeMavenVersions = client.get_json(api_url).await?;
|
||||||
|
|
||||||
let mut game_versions: Vec<String> = Vec::new();
|
let mut game_versions: Vec<String> = Vec::new();
|
||||||
for version in &maven.versions {
|
for version in &maven.versions {
|
||||||
|
|||||||
+54
-3
@@ -42,7 +42,16 @@ pub struct QuiltLibrary {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn fetch_quilt_game_versions(client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
|
pub async fn fetch_quilt_game_versions(client: &HttpClient) -> Result<Vec<GameVersion>, NetError> {
|
||||||
let url = format!("{}/versions/game", QUILT_META_BASE);
|
fetch_quilt_game_versions_from(client, QUILT_META_BASE).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// same as fetch_quilt_game_versions but lets tests point at a wiremock
|
||||||
|
// server. quilt mirrors the fabric API shape.
|
||||||
|
pub async fn fetch_quilt_game_versions_from(
|
||||||
|
client: &HttpClient,
|
||||||
|
meta_base: &str,
|
||||||
|
) -> Result<Vec<GameVersion>, NetError> {
|
||||||
|
let url = format!("{}/versions/game", meta_base);
|
||||||
let versions: Vec<QuiltGameVersion> = client.get_json(&url).await?;
|
let versions: Vec<QuiltGameVersion> = client.get_json(&url).await?;
|
||||||
|
|
||||||
Ok(versions
|
Ok(versions
|
||||||
@@ -58,7 +67,15 @@ pub async fn fetch_quilt_versions(
|
|||||||
client: &HttpClient,
|
client: &HttpClient,
|
||||||
game_version: &str,
|
game_version: &str,
|
||||||
) -> Result<Vec<QuiltLoaderVersion>, NetError> {
|
) -> Result<Vec<QuiltLoaderVersion>, NetError> {
|
||||||
let url = format!("{}/versions/loader/{}", QUILT_META_BASE, game_version);
|
fetch_quilt_versions_from(client, QUILT_META_BASE, game_version).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn fetch_quilt_versions_from(
|
||||||
|
client: &HttpClient,
|
||||||
|
meta_base: &str,
|
||||||
|
game_version: &str,
|
||||||
|
) -> Result<Vec<QuiltLoaderVersion>, NetError> {
|
||||||
|
let url = format!("{}/versions/loader/{}", meta_base, game_version);
|
||||||
client.get_json(&url).await
|
client.get_json(&url).await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,14 +83,48 @@ pub async fn fetch_quilt_profile(
|
|||||||
client: &HttpClient,
|
client: &HttpClient,
|
||||||
game_version: &str,
|
game_version: &str,
|
||||||
loader_version: &str,
|
loader_version: &str,
|
||||||
|
) -> Result<QuiltProfile, NetError> {
|
||||||
|
fetch_quilt_profile_from(client, QUILT_META_BASE, game_version, loader_version).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn fetch_quilt_profile_from(
|
||||||
|
client: &HttpClient,
|
||||||
|
meta_base: &str,
|
||||||
|
game_version: &str,
|
||||||
|
loader_version: &str,
|
||||||
) -> Result<QuiltProfile, NetError> {
|
) -> Result<QuiltProfile, NetError> {
|
||||||
let url = format!(
|
let url = format!(
|
||||||
"{}/versions/loader/{}/{}/profile/json",
|
"{}/versions/loader/{}/{}/profile/json",
|
||||||
QUILT_META_BASE, game_version, loader_version
|
meta_base, game_version, loader_version
|
||||||
);
|
);
|
||||||
client.get_json(&url).await
|
client.get_json(&url).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// like fetch_quilt_profile but also returns the raw response bytes so the
|
||||||
|
// caller can write the upstream JSON byte-for-byte to disk. used by the
|
||||||
|
// install path so we don't lose data (e.g. any future arguments field) by
|
||||||
|
// re-serializing through our narrow QuiltProfile struct.
|
||||||
|
pub async fn fetch_quilt_profile_with_raw(
|
||||||
|
client: &HttpClient,
|
||||||
|
game_version: &str,
|
||||||
|
loader_version: &str,
|
||||||
|
) -> Result<(QuiltProfile, Vec<u8>), NetError> {
|
||||||
|
fetch_quilt_profile_with_raw_from(client, QUILT_META_BASE, game_version, loader_version).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn fetch_quilt_profile_with_raw_from(
|
||||||
|
client: &HttpClient,
|
||||||
|
meta_base: &str,
|
||||||
|
game_version: &str,
|
||||||
|
loader_version: &str,
|
||||||
|
) -> Result<(QuiltProfile, Vec<u8>), NetError> {
|
||||||
|
let url = format!(
|
||||||
|
"{}/versions/loader/{}/{}/profile/json",
|
||||||
|
meta_base, game_version, loader_version
|
||||||
|
);
|
||||||
|
client.get_json_with_raw(&url, "Quilt profile").await
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn download_quilt_libraries(
|
pub async fn download_quilt_libraries(
|
||||||
client: &HttpClient,
|
client: &HttpClient,
|
||||||
profile: &QuiltProfile,
|
profile: &QuiltProfile,
|
||||||
|
|||||||
+8
-7
@@ -78,7 +78,8 @@ pub fn register_kill(name: &str, tx: tokio::sync::oneshot::Sender<()>) {
|
|||||||
|
|
||||||
pub fn send_kill(name: &str) -> bool {
|
pub fn send_kill(name: &str) -> bool {
|
||||||
if let Ok(mut map) = KILL_SENDERS.lock()
|
if let Ok(mut map) = KILL_SENDERS.lock()
|
||||||
&& let Some(tx) = map.remove(name) {
|
&& let Some(tx) = map.remove(name)
|
||||||
|
{
|
||||||
let _ = tx.send(());
|
let _ = tx.send(());
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -141,12 +142,12 @@ mod tests {
|
|||||||
assert!(drained.iter().any(|(k, _)| k == "run_test_lp"));
|
assert!(drained.iter().any(|(k, _)| k == "run_test_lp"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
// Removed drain_empty_returns_empty: it relied on no other test pushing
|
||||||
fn drain_empty_returns_empty() {
|
// to LAST_PLAYED between the two drain calls, which races with the
|
||||||
let _ = drain_last_played();
|
// parallel push_and_drain_last_played test. The drain semantics are
|
||||||
let drained = drain_last_played();
|
// already covered by push_and_drain_last_played, which asserts a
|
||||||
assert!(drained.is_empty());
|
// specific entry is present, and the empty-result path is exercised
|
||||||
}
|
// implicitly any time drain runs after that test's cleanup.
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn send_kill_returns_false_for_missing() {
|
fn send_kill_returns_false_for_missing() {
|
||||||
|
|||||||
+57
-32
@@ -32,7 +32,9 @@ 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();
|
||||||
}
|
}
|
||||||
@@ -79,6 +81,13 @@ pub fn peek_all_errors() -> Vec<ErrorEvent> {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
static TEST_LOCK: Mutex<()> = Mutex::new(());
|
||||||
|
|
||||||
|
fn clear_errors_for_test() {
|
||||||
|
ERROR_EVENTS.lock().unwrap().clear();
|
||||||
|
}
|
||||||
|
|
||||||
fn make_event(msg: &str) -> ErrorEvent {
|
fn make_event(msg: &str) -> ErrorEvent {
|
||||||
ErrorEvent {
|
ErrorEvent {
|
||||||
@@ -89,57 +98,73 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[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]
|
#[test]
|
||||||
fn peek_does_not_remove() {
|
fn peek_does_not_remove() {
|
||||||
push_error(make_event("err_peek"));
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
let before = peek_error();
|
clear_errors_for_test();
|
||||||
assert!(before.is_some());
|
|
||||||
assert!(has_errors());
|
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]
|
#[test]
|
||||||
fn peek_all_returns_newest_first() {
|
fn peek_all_returns_newest_first() {
|
||||||
push_error(make_event("err_all_a"));
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
push_error(make_event("err_all_b"));
|
clear_errors_for_test();
|
||||||
|
|
||||||
|
push_error(make_event("newest_a"));
|
||||||
|
push_error(make_event("newest_b"));
|
||||||
|
|
||||||
let all = peek_all_errors();
|
let all = peek_all_errors();
|
||||||
assert!(all.len() >= 2);
|
|
||||||
if all.len() >= 2 {
|
assert_eq!(all.len(), 2);
|
||||||
assert!(all[0].id >= all[1].id);
|
assert!(all[0].message.ends_with("_b"));
|
||||||
}
|
assert!(all[1].message.ends_with("_a"));
|
||||||
|
assert!(all[0].id > all[1].id);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn auto_assigned_ids_are_unique() {
|
fn auto_assigned_ids_are_unique() {
|
||||||
push_error(make_event("err_id_1"));
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
push_error(make_event("err_id_2"));
|
clear_errors_for_test();
|
||||||
|
|
||||||
|
push_error(make_event("unique_1"));
|
||||||
|
push_error(make_event("unique_2"));
|
||||||
|
|
||||||
let all = peek_all_errors();
|
let all = peek_all_errors();
|
||||||
if all.len() >= 2 {
|
|
||||||
let ids: Vec<u64> = all.iter().map(|e| e.id).collect();
|
assert_eq!(all.len(), 2);
|
||||||
let unique: std::collections::HashSet<u64> = ids.iter().copied().collect();
|
assert_ne!(all[0].id, all[1].id);
|
||||||
assert_eq!(ids.len(), unique.len());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn overflow_drops_oldest() {
|
fn overflow_drops_oldest() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear_errors_for_test();
|
||||||
|
|
||||||
for i in 0..(MAX_ERROR_EVENTS + 10) {
|
for i in 0..(MAX_ERROR_EVENTS + 10) {
|
||||||
push_error(make_event(&format!("overflow_{i}")));
|
push_error(make_event(&format!("overflow_{i}")));
|
||||||
}
|
}
|
||||||
|
|
||||||
let all = peek_all_errors();
|
let all = peek_all_errors();
|
||||||
assert!(all.len() <= MAX_ERROR_EVENTS);
|
|
||||||
|
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"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+66
-14
@@ -3,9 +3,9 @@ use crossterm::event::{self, Event};
|
|||||||
use ratatui::crossterm::event::KeyEventKind;
|
use ratatui::crossterm::event::KeyEventKind;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use super::Tui;
|
||||||
use super::app::{App, PENDING_INSTANCES};
|
use super::app::{App, PENDING_INSTANCES};
|
||||||
use super::widgets::{self, popups::import_modpack, popups::new_instance};
|
use super::widgets::{self, popups::import_modpack, popups::new_instance};
|
||||||
use super::Tui;
|
|
||||||
use crate::instance::InstanceManager;
|
use crate::instance::InstanceManager;
|
||||||
use crate::tui::error_buffer;
|
use crate::tui::error_buffer;
|
||||||
use crate::tui::progress;
|
use crate::tui::progress;
|
||||||
@@ -31,13 +31,13 @@ impl App {
|
|||||||
self.drain_pending_instances();
|
self.drain_pending_instances();
|
||||||
self.drain_pending_last_played();
|
self.drain_pending_last_played();
|
||||||
self.mods_state.drain_pending();
|
self.mods_state.drain_pending();
|
||||||
self.mods_state.try_rescan();
|
self.mods_state.drain_watcher();
|
||||||
self.resource_packs_state.drain_pending();
|
self.resource_packs_state.drain_pending();
|
||||||
self.resource_packs_state.try_rescan();
|
self.resource_packs_state.drain_watcher();
|
||||||
self.shaders_state.drain_pending();
|
self.shaders_state.drain_pending();
|
||||||
self.shaders_state.try_rescan();
|
self.shaders_state.drain_watcher();
|
||||||
self.worlds_state.drain_pending();
|
self.worlds_state.drain_pending();
|
||||||
self.worlds_state.try_rescan();
|
self.worlds_state.drain_watcher();
|
||||||
self.logs_state.drain_pending();
|
self.logs_state.drain_pending();
|
||||||
self.logs_state.try_rescan();
|
self.logs_state.try_rescan();
|
||||||
self.account_state.drain_auth_result();
|
self.account_state.drain_auth_result();
|
||||||
@@ -54,8 +54,10 @@ impl App {
|
|||||||
terminal.draw(|frame| self.render_frame(frame))?;
|
terminal.draw(|frame| self.render_frame(frame))?;
|
||||||
self.handle_events().wrap_err("handle events failed")?;
|
self.handle_events().wrap_err("handle events failed")?;
|
||||||
|
|
||||||
if let Some(path) = self.pending_editor.take() {
|
if let Some(path) = self.pending_editor.take()
|
||||||
Self::run_editor(terminal, &path);
|
&& Self::run_editor(terminal, &path)
|
||||||
|
{
|
||||||
|
self.reload_edited_config(&path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -149,12 +151,12 @@ impl App {
|
|||||||
// spawns $EDITOR/$VISUAL to edit a file. for terminal editors (vim, nano, etc)
|
// spawns $EDITOR/$VISUAL to edit a file. for terminal editors (vim, nano, etc)
|
||||||
// gotta leave the alternate screen and restore it after, otherwise the
|
// gotta leave the alternate screen and restore it after, otherwise the
|
||||||
// editor fights with ratatui for the terminal. GUI editors just get spawned detached.
|
// editor fights with ratatui for the terminal. GUI editors just get spawned detached.
|
||||||
fn run_editor(terminal: &mut ratatui::DefaultTerminal, path: &std::path::Path) {
|
fn run_editor(terminal: &mut ratatui::DefaultTerminal, path: &std::path::Path) -> bool {
|
||||||
use ratatui::crossterm::{
|
use ratatui::crossterm::{
|
||||||
terminal::{
|
|
||||||
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
|
|
||||||
},
|
|
||||||
ExecutableCommand,
|
ExecutableCommand,
|
||||||
|
terminal::{
|
||||||
|
EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
use std::io::stdout;
|
use std::io::stdout;
|
||||||
|
|
||||||
@@ -199,20 +201,70 @@ impl App {
|
|||||||
|
|
||||||
if let Err(e) = result {
|
if let Err(e) = result {
|
||||||
tracing::error!("Failed to open editor: {}", e);
|
tracing::error!("Failed to open editor: {}", e);
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
} else { if let Err(e) = std::process::Command::new(&editor)
|
true
|
||||||
|
} else {
|
||||||
|
if let Err(e) = std::process::Command::new(&editor)
|
||||||
.arg(path)
|
.arg(path)
|
||||||
.stdout(std::process::Stdio::null())
|
.stdout(std::process::Stdio::null())
|
||||||
.stderr(std::process::Stdio::null())
|
.stderr(std::process::Stdio::null())
|
||||||
.spawn() {
|
.spawn()
|
||||||
|
{
|
||||||
tracing::error!("Failed to open editor: {}", e);
|
tracing::error!("Failed to open editor: {}", e);
|
||||||
}}
|
return false;
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reload_edited_config(&mut self, path: &std::path::Path) {
|
||||||
|
if path.file_name().and_then(|n| n.to_str()) != Some("instance.json") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some(name) = path
|
||||||
|
.parent()
|
||||||
|
.and_then(|p| p.file_name())
|
||||||
|
.and_then(|n| n.to_str())
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
match self.instance_manager.load_one(name) {
|
||||||
|
Ok(config) => {
|
||||||
|
self.instances_state.replace_instance(name, config);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Failed to reload edited instance '{}': {}", name, e);
|
||||||
|
error_buffer::push_error(error_buffer::ErrorEvent {
|
||||||
|
id: 0,
|
||||||
|
level: tracing::Level::ERROR,
|
||||||
|
message: format!("Failed to reload edited instance '{name}': {e}"),
|
||||||
|
pushed_at: std::time::Instant::now(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn spawn_launch(&self, instance: crate::instance::InstanceConfig) {
|
pub(super) fn spawn_launch(&self, instance: crate::instance::InstanceConfig) {
|
||||||
use crate::instance::launch;
|
use crate::instance::launch;
|
||||||
use crate::running;
|
use crate::running;
|
||||||
|
|
||||||
|
let instance = match self.instance_manager.load_one(&instance.name) {
|
||||||
|
Ok(config) => config,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Failed to load instance '{}': {}", instance.name, e);
|
||||||
|
error_buffer::push_error(error_buffer::ErrorEvent {
|
||||||
|
id: 0,
|
||||||
|
level: tracing::Level::ERROR,
|
||||||
|
message: format!("Failed to load instance '{}': {e}", instance.name),
|
||||||
|
pushed_at: std::time::Instant::now(),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
running::set_state(&instance.name, running::RunState::Authenticating);
|
running::set_state(&instance.name, running::RunState::Authenticating);
|
||||||
|
|
||||||
let instances_dir = self.instance_manager.instances_dir.clone();
|
let instances_dir = self.instance_manager.instances_dir.clone();
|
||||||
|
|||||||
+18
-10
@@ -6,7 +6,9 @@
|
|||||||
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||||
|
|
||||||
use super::app::{App, FocusedArea};
|
use super::app::{App, FocusedArea};
|
||||||
use super::widgets::{self, popups::confirm as confirm_popup, popups::import_modpack, popups::new_instance, WidgetKey};
|
use super::widgets::{
|
||||||
|
self, WidgetKey, popups::confirm as confirm_popup, popups::import_modpack, popups::new_instance,
|
||||||
|
};
|
||||||
use crate::tui::error_buffer;
|
use crate::tui::error_buffer;
|
||||||
|
|
||||||
impl App {
|
impl App {
|
||||||
@@ -15,6 +17,9 @@ impl App {
|
|||||||
if self.focused == FocusedArea::OverviewExpanded {
|
if self.focused == FocusedArea::OverviewExpanded {
|
||||||
if self.log_overlay_search.active {
|
if self.log_overlay_search.active {
|
||||||
match key_event.code {
|
match key_event.code {
|
||||||
|
KeyCode::Enter => {
|
||||||
|
self.log_overlay_search.confirm();
|
||||||
|
}
|
||||||
KeyCode::Esc => {
|
KeyCode::Esc => {
|
||||||
self.log_overlay_search.deactivate();
|
self.log_overlay_search.deactivate();
|
||||||
}
|
}
|
||||||
@@ -103,7 +108,8 @@ impl App {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
} else if self.content_tab == widgets::content::ContentTab::Worlds {
|
} else if self.content_tab == widgets::content::ContentTab::Worlds {
|
||||||
if widgets::content::list::handle_key_no_toggle(&key_event, &mut self.worlds_state) {
|
if widgets::content::list::handle_key_no_toggle(&key_event, &mut self.worlds_state)
|
||||||
|
{
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -116,7 +122,8 @@ impl App {
|
|||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
if let Some(state) = state
|
if let Some(state) = state
|
||||||
&& widgets::content::list::handle_key(&key_event, state) {
|
&& widgets::content::list::handle_key(&key_event, state)
|
||||||
|
{
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -129,17 +136,17 @@ impl App {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if self.focused == FocusedArea::Settings {
|
if self.focused == FocusedArea::Settings {
|
||||||
match widgets::details::handle_key(
|
match widgets::settings::handle_key(
|
||||||
&key_event,
|
&key_event,
|
||||||
self.instances_state.selected_instance(),
|
self.instances_state.selected_instance(),
|
||||||
&self.instance_manager.instances_dir,
|
&self.instance_manager.instances_dir,
|
||||||
) {
|
) {
|
||||||
widgets::details::SettingsAction::EditInstance(path)
|
widgets::settings::SettingsAction::EditInstance(path)
|
||||||
| widgets::details::SettingsAction::EditGlobal(path) => {
|
| widgets::settings::SettingsAction::EditGlobal(path) => {
|
||||||
self.pending_editor = Some(path);
|
self.pending_editor = Some(path);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
widgets::details::SettingsAction::ToggleDesktop => {
|
widgets::settings::SettingsAction::ToggleDesktop => {
|
||||||
if let Some(inst) = self.instances_state.selected_instance() {
|
if let Some(inst) = self.instances_state.selected_instance() {
|
||||||
let name = inst.name.clone();
|
let name = inst.name.clone();
|
||||||
match crate::instance::desktop::toggle(inst) {
|
match crate::instance::desktop::toggle(inst) {
|
||||||
@@ -166,7 +173,7 @@ impl App {
|
|||||||
}
|
}
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
widgets::details::SettingsAction::None => {}
|
widgets::settings::SettingsAction::None => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,7 +185,8 @@ impl App {
|
|||||||
import_modpack::handle_key(&key_event, &mut self.instances_state);
|
import_modpack::handle_key(&key_event, &mut self.instances_state);
|
||||||
}
|
}
|
||||||
_ => {
|
_ => {
|
||||||
if self.focused == FocusedArea::Instances && self.instances_state.renaming.is_some() {
|
if self.focused == FocusedArea::Instances && self.instances_state.renaming.is_some()
|
||||||
|
{
|
||||||
match key_event.code {
|
match key_event.code {
|
||||||
KeyCode::Enter => {
|
KeyCode::Enter => {
|
||||||
let new_name = self.instances_state.renaming.take().unwrap_or_default();
|
let new_name = self.instances_state.renaming.take().unwrap_or_default();
|
||||||
@@ -267,7 +275,7 @@ impl App {
|
|||||||
.instances_dir
|
.instances_dir
|
||||||
.join(&instance.name)
|
.join(&instance.name)
|
||||||
.join(".minecraft");
|
.join(".minecraft");
|
||||||
if let Err(e) = open::that(&dir) {
|
if let Err(e) = open::that_detached(&dir) {
|
||||||
tracing::error!("Failed to open instance directory: {}", e);
|
tracing::error!("Failed to open instance directory: {}", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-3
@@ -40,7 +40,7 @@ fn push_app_log(line: String) {
|
|||||||
// before you remember this. ask me how i know.
|
// before you remember this. ask me how i know.
|
||||||
pub fn init() -> WorkerGuard {
|
pub fn init() -> WorkerGuard {
|
||||||
let log_dir = match dirs_next::cache_dir() {
|
let log_dir = match dirs_next::cache_dir() {
|
||||||
Some(d) => d.join("mcl"),
|
Some(d) => d.join("rmcl"),
|
||||||
None => std::path::PathBuf::from("./cache"),
|
None => std::path::PathBuf::from("./cache"),
|
||||||
};
|
};
|
||||||
match std::fs::create_dir_all(&log_dir) {
|
match std::fs::create_dir_all(&log_dir) {
|
||||||
@@ -54,12 +54,14 @@ pub fn init() -> WorkerGuard {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let file_appender = tracing_appender::rolling::daily(&log_dir, "mcl.log");
|
let now = chrono::Local::now().format("%Y-%m-%d_%H-%M-%S");
|
||||||
|
let file_appender = tracing_appender::rolling::never(&log_dir, format!("rmcl_{now}.log"));
|
||||||
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
|
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
|
||||||
|
|
||||||
let env_filter = EnvFilter::builder()
|
let env_filter = EnvFilter::builder()
|
||||||
.with_default_directive(Level::INFO.into())
|
.with_default_directive(Level::INFO.into())
|
||||||
.from_env_lossy();
|
.from_env_lossy()
|
||||||
|
.add_directive("mc_instance=off".parse().unwrap());
|
||||||
|
|
||||||
let rust_log = std::env::var("RUST_LOG").unwrap_or_default().to_lowercase();
|
let rust_log = std::env::var("RUST_LOG").unwrap_or_default().to_lowercase();
|
||||||
let tui_level = if rust_log.contains("debug") || rust_log.contains("trace") {
|
let tui_level = if rust_log.contains("debug") || rust_log.contains("trace") {
|
||||||
|
|||||||
@@ -12,6 +12,18 @@ pub mod widgets;
|
|||||||
pub type Tui = ratatui::DefaultTerminal;
|
pub type Tui = ratatui::DefaultTerminal;
|
||||||
|
|
||||||
pub async fn show() -> color_eyre::Result<()> {
|
pub async fn show() -> color_eyre::Result<()> {
|
||||||
|
// restore the terminal before printing a panic. without this, a panic
|
||||||
|
// leaves raw mode + alternate screen active and looks like a freeze
|
||||||
|
let default_hook = std::panic::take_hook();
|
||||||
|
std::panic::set_hook(Box::new(move |info| {
|
||||||
|
let _ = crossterm::execute!(
|
||||||
|
std::io::stdout(),
|
||||||
|
crossterm::event::PopKeyboardEnhancementFlags
|
||||||
|
);
|
||||||
|
ratatui::restore();
|
||||||
|
default_hook(info);
|
||||||
|
}));
|
||||||
|
|
||||||
let mut terminal = ratatui::init();
|
let mut terminal = ratatui::init();
|
||||||
|
|
||||||
// opt into enhanced keyboard protocol to distinguish key press vs release
|
// opt into enhanced keyboard protocol to distinguish key press vs release
|
||||||
|
|||||||
+35
-16
@@ -4,22 +4,24 @@
|
|||||||
// popups and error toasts render on top of everything.
|
// popups and error toasts render on top of everything.
|
||||||
|
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
layout::{Constraint, Direction, Layout},
|
|
||||||
Frame,
|
Frame,
|
||||||
|
layout::{Constraint, Direction, Layout},
|
||||||
};
|
};
|
||||||
use tachyonfx::{fx, EffectRenderer, Interpolation, Motion};
|
use tachyonfx::{EffectRenderer, Interpolation, Motion, fx};
|
||||||
|
|
||||||
use super::app::{App, ErrorEffectState, FocusedArea};
|
use super::app::{App, ErrorEffectState, FocusedArea};
|
||||||
use super::widgets::{self, popups::confirm as confirm_popup, popups::import_modpack, popups::new_instance};
|
use super::widgets::{
|
||||||
|
self, popups::confirm as confirm_popup, popups::import_modpack, popups::new_instance,
|
||||||
|
};
|
||||||
use crate::tui::error_buffer;
|
use crate::tui::error_buffer;
|
||||||
use crate::tui::widgets::popups::confirm::{confirm_popup_area, ConfirmPopup};
|
use crate::tui::widgets::popups::confirm::{ConfirmPopup, confirm_popup_area};
|
||||||
use crate::tui::widgets::popups::error::{popup_area, ErrorPopup};
|
use crate::tui::widgets::popups::error::{ErrorPopup, popup_area};
|
||||||
|
|
||||||
impl App {
|
impl App {
|
||||||
pub(super) fn render_frame(&mut self, frame: &mut Frame) {
|
pub(super) fn render_frame(&mut self, frame: &mut Frame) {
|
||||||
use crate::config::theme::THEME;
|
use crate::config::theme::THEME;
|
||||||
use ratatui::widgets::Block;
|
|
||||||
use ratatui::style::Style;
|
use ratatui::style::Style;
|
||||||
|
use ratatui::widgets::Block;
|
||||||
|
|
||||||
let theme = THEME.as_ref();
|
let theme = THEME.as_ref();
|
||||||
frame.render_widget(
|
frame.render_widget(
|
||||||
@@ -29,10 +31,7 @@ impl App {
|
|||||||
|
|
||||||
let chunks = Layout::default()
|
let chunks = Layout::default()
|
||||||
.direction(Direction::Horizontal)
|
.direction(Direction::Horizontal)
|
||||||
.constraints([
|
.constraints([Constraint::Percentage(20), Constraint::Percentage(80)])
|
||||||
Constraint::Percentage(20),
|
|
||||||
Constraint::Percentage(80),
|
|
||||||
])
|
|
||||||
.split(frame.area());
|
.split(frame.area());
|
||||||
|
|
||||||
widgets::instances::render(frame, chunks[0], self.focused, &mut self.instances_state);
|
widgets::instances::render(frame, chunks[0], self.focused, &mut self.instances_state);
|
||||||
@@ -83,7 +82,7 @@ impl App {
|
|||||||
self.focused,
|
self.focused,
|
||||||
&mut self.account_state,
|
&mut self.account_state,
|
||||||
);
|
);
|
||||||
widgets::details::render(
|
widgets::settings::render(
|
||||||
frame,
|
frame,
|
||||||
bottom_chunks[1],
|
bottom_chunks[1],
|
||||||
self.focused,
|
self.focused,
|
||||||
@@ -136,7 +135,7 @@ impl App {
|
|||||||
// full-screen log viewer with search highlighting and auto-scroll.
|
// full-screen log viewer with search highlighting and auto-scroll.
|
||||||
// auto-sticks to the bottom unless the user scrolled up manually
|
// auto-sticks to the bottom unless the user scrolled up manually
|
||||||
fn render_log_overlay(&mut self, frame: &mut Frame) {
|
fn render_log_overlay(&mut self, frame: &mut Frame) {
|
||||||
use crate::config::theme::{THEME, BORDER_STYLE};
|
use crate::config::theme::{BORDER_STYLE, THEME};
|
||||||
use crate::tui::logging::get_app_logs;
|
use crate::tui::logging::get_app_logs;
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
layout::{Alignment, Margin},
|
layout::{Alignment, Margin},
|
||||||
@@ -247,7 +246,13 @@ impl App {
|
|||||||
for event in events {
|
for event in events {
|
||||||
self.error_effects.entry(event.id).or_insert_with(|| {
|
self.error_effects.entry(event.id).or_insert_with(|| {
|
||||||
ErrorEffectState::SlidingIn(
|
ErrorEffectState::SlidingIn(
|
||||||
fx::slide_in(Motion::RightToLeft, 4, 0, bg, (250, Interpolation::CubicOut)),
|
fx::slide_in(
|
||||||
|
Motion::RightToLeft,
|
||||||
|
4,
|
||||||
|
0,
|
||||||
|
bg,
|
||||||
|
(250, Interpolation::CubicOut),
|
||||||
|
),
|
||||||
std::time::Instant::now(),
|
std::time::Instant::now(),
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
@@ -278,7 +283,13 @@ impl App {
|
|||||||
.or_insert(ErrorEffectState::Idle);
|
.or_insert(ErrorEffectState::Idle);
|
||||||
if !matches!(entry, ErrorEffectState::FadingOut(..)) {
|
if !matches!(entry, ErrorEffectState::FadingOut(..)) {
|
||||||
*entry = ErrorEffectState::FadingOut(
|
*entry = ErrorEffectState::FadingOut(
|
||||||
fx::slide_out(Motion::LeftToRight, 4, 0, bg, (fly_out_ms as u32, Interpolation::CubicIn)),
|
fx::slide_out(
|
||||||
|
Motion::LeftToRight,
|
||||||
|
4,
|
||||||
|
0,
|
||||||
|
bg,
|
||||||
|
(fly_out_ms as u32, Interpolation::CubicIn),
|
||||||
|
),
|
||||||
std::time::Instant::now(),
|
std::time::Instant::now(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -289,7 +300,11 @@ impl App {
|
|||||||
ErrorEffectState::SlidingIn(effect, started) => {
|
ErrorEffectState::SlidingIn(effect, started) => {
|
||||||
let dt = started.elapsed().as_millis() as u32;
|
let dt = started.elapsed().as_millis() as u32;
|
||||||
if effect.running() {
|
if effect.running() {
|
||||||
frame.render_effect(effect, area, tachyonfx::Duration::from_millis(dt.min(32)));
|
frame.render_effect(
|
||||||
|
effect,
|
||||||
|
area,
|
||||||
|
tachyonfx::Duration::from_millis(dt.min(32)),
|
||||||
|
);
|
||||||
*started = std::time::Instant::now();
|
*started = std::time::Instant::now();
|
||||||
} else {
|
} else {
|
||||||
*effect_state = ErrorEffectState::Idle;
|
*effect_state = ErrorEffectState::Idle;
|
||||||
@@ -299,7 +314,11 @@ impl App {
|
|||||||
ErrorEffectState::FadingOut(effect, started) => {
|
ErrorEffectState::FadingOut(effect, started) => {
|
||||||
let dt = started.elapsed().as_millis() as u32;
|
let dt = started.elapsed().as_millis() as u32;
|
||||||
if effect.running() {
|
if effect.running() {
|
||||||
frame.render_effect(effect, area, tachyonfx::Duration::from_millis(dt.min(32)));
|
frame.render_effect(
|
||||||
|
effect,
|
||||||
|
area,
|
||||||
|
tachyonfx::Duration::from_millis(dt.min(32)),
|
||||||
|
);
|
||||||
*started = std::time::Instant::now();
|
*started = std::time::Instant::now();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+70
-30
@@ -6,17 +6,17 @@ use std::sync::{Arc, Mutex};
|
|||||||
|
|
||||||
use crossterm::event::{KeyCode, KeyEvent};
|
use crossterm::event::{KeyCode, KeyEvent};
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
|
Frame,
|
||||||
layout::Rect,
|
layout::Rect,
|
||||||
style::{Modifier, Style},
|
style::{Modifier, Style},
|
||||||
text::{Line, Span},
|
text::{Line, Span},
|
||||||
widgets::{Block, Borders, Paragraph, Widget},
|
widgets::{Block, Borders, Paragraph, Widget},
|
||||||
Frame,
|
|
||||||
};
|
};
|
||||||
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
|
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
|
||||||
|
|
||||||
use crate::auth::{self, AccountStore, AccountType, AuthResult, DeviceCodeInfo};
|
use crate::auth::{self, AccountStore, AccountType, AuthResult, DeviceCodeInfo};
|
||||||
|
use crate::config::theme::{BORDER_STYLE, THEME};
|
||||||
use crate::tui::app::FocusedArea;
|
use crate::tui::app::FocusedArea;
|
||||||
use crate::config::theme::{THEME, BORDER_STYLE};
|
|
||||||
|
|
||||||
use super::styled_title;
|
use super::styled_title;
|
||||||
|
|
||||||
@@ -26,6 +26,7 @@ pub enum AddMode {
|
|||||||
None,
|
None,
|
||||||
ChooseType,
|
ChooseType,
|
||||||
OfflineNameInput(String),
|
OfflineNameInput(String),
|
||||||
|
OfflineBlocked,
|
||||||
ConfirmDelete(usize),
|
ConfirmDelete(usize),
|
||||||
DeviceCodeWaiting {
|
DeviceCodeWaiting {
|
||||||
info: DeviceCodeInfo,
|
info: DeviceCodeInfo,
|
||||||
@@ -59,11 +60,10 @@ impl AccountState {
|
|||||||
// can't block on it because the TUI needs to keep rendering
|
// can't block on it because the TUI needs to keep rendering
|
||||||
pub fn drain_auth_result(&mut self) {
|
pub fn drain_auth_result(&mut self) {
|
||||||
if let AddMode::DeviceCodeWaiting { pending, .. } = &self.add_mode {
|
if let AddMode::DeviceCodeWaiting { pending, .. } = &self.add_mode {
|
||||||
let result = match pending.lock() { Ok(mut slot) => {
|
let result = match pending.lock() {
|
||||||
slot.take()
|
Ok(mut slot) => slot.take(),
|
||||||
} _ => {
|
_ => None,
|
||||||
None
|
};
|
||||||
}};
|
|
||||||
|
|
||||||
if let Some(result) = result {
|
if let Some(result) = result {
|
||||||
match result {
|
match result {
|
||||||
@@ -99,7 +99,11 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
|
|||||||
true
|
true
|
||||||
}
|
}
|
||||||
KeyCode::Char('o') | KeyCode::Char('2') => {
|
KeyCode::Char('o') | KeyCode::Char('2') => {
|
||||||
state.add_mode = AddMode::OfflineNameInput(String::new());
|
state.add_mode = if state.store.has_microsoft_account() {
|
||||||
|
AddMode::OfflineNameInput(String::new())
|
||||||
|
} else {
|
||||||
|
AddMode::OfflineBlocked
|
||||||
|
};
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
KeyCode::Esc => {
|
KeyCode::Esc => {
|
||||||
@@ -112,13 +116,19 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
|
|||||||
KeyCode::Enter => {
|
KeyCode::Enter => {
|
||||||
let trimmed = name.trim().to_string();
|
let trimmed = name.trim().to_string();
|
||||||
if !trimmed.is_empty() {
|
if !trimmed.is_empty() {
|
||||||
|
if state.store.has_microsoft_account() {
|
||||||
let account = auth::create_offline_account(&trimmed);
|
let account = auth::create_offline_account(&trimmed);
|
||||||
state.store.add(account);
|
state.store.add(account);
|
||||||
if state.list_state.selected.is_none() && !state.store.accounts.is_empty() {
|
if state.list_state.selected.is_none() && !state.store.accounts.is_empty() {
|
||||||
state.list_state.selected = Some(0);
|
state.list_state.selected = Some(0);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
state.add_mode = AddMode::None;
|
state.add_mode = AddMode::None;
|
||||||
|
} else {
|
||||||
|
state.add_mode = AddMode::OfflineBlocked;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
state.add_mode = AddMode::None;
|
||||||
|
}
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
KeyCode::Char(c) => {
|
KeyCode::Char(c) => {
|
||||||
@@ -139,6 +149,13 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
|
|||||||
}
|
}
|
||||||
_ => true,
|
_ => true,
|
||||||
},
|
},
|
||||||
|
AddMode::OfflineBlocked => match key_event.code {
|
||||||
|
KeyCode::Enter | KeyCode::Esc => {
|
||||||
|
state.add_mode = AddMode::None;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
_ => true,
|
||||||
|
},
|
||||||
AddMode::DeviceCodeWaiting { .. } => match key_event.code {
|
AddMode::DeviceCodeWaiting { .. } => match key_event.code {
|
||||||
KeyCode::Esc => {
|
KeyCode::Esc => {
|
||||||
state.add_mode = AddMode::None;
|
state.add_mode = AddMode::None;
|
||||||
@@ -211,7 +228,8 @@ pub fn drain_device_code(state: &mut AccountState) {
|
|||||||
if let AddMode::DeviceCodeWaiting { info, .. } = &mut state.add_mode
|
if let AddMode::DeviceCodeWaiting { info, .. } = &mut state.add_mode
|
||||||
&& info.user_code.is_empty()
|
&& info.user_code.is_empty()
|
||||||
&& let Ok(mut slot) = auth::DEVICE_CODE_DISPLAY.lock()
|
&& let Ok(mut slot) = auth::DEVICE_CODE_DISPLAY.lock()
|
||||||
&& let Some(dc_info) = slot.take() {
|
&& let Some(dc_info) = slot.take()
|
||||||
|
{
|
||||||
info.user_code = dc_info.user_code;
|
info.user_code = dc_info.user_code;
|
||||||
info.verification_uri = dc_info.verification_uri;
|
info.verification_uri = dc_info.verification_uri;
|
||||||
}
|
}
|
||||||
@@ -246,8 +264,7 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut A
|
|||||||
|
|
||||||
if state.store.accounts.is_empty() {
|
if state.store.accounts.is_empty() {
|
||||||
frame.render_widget(
|
frame.render_widget(
|
||||||
Paragraph::new("No accounts.")
|
Paragraph::new("No accounts.").style(Style::default().fg(theme.text_dim())),
|
||||||
.style(Style::default().fg(theme.text_dim())),
|
|
||||||
inner,
|
inner,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
@@ -258,6 +275,7 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut A
|
|||||||
match &state.add_mode {
|
match &state.add_mode {
|
||||||
AddMode::ChooseType => render_choose_popup(frame),
|
AddMode::ChooseType => render_choose_popup(frame),
|
||||||
AddMode::OfflineNameInput(name) => render_offline_popup(frame, name),
|
AddMode::OfflineNameInput(name) => render_offline_popup(frame, name),
|
||||||
|
AddMode::OfflineBlocked => render_offline_blocked_popup(frame),
|
||||||
AddMode::ConfirmDelete(idx) => render_confirm_delete(frame, state, *idx),
|
AddMode::ConfirmDelete(idx) => render_confirm_delete(frame, state, *idx),
|
||||||
AddMode::DeviceCodeWaiting { info, .. } => render_device_code_popup(frame, info),
|
AddMode::DeviceCodeWaiting { info, .. } => render_device_code_popup(frame, info),
|
||||||
AddMode::None => {}
|
AddMode::None => {}
|
||||||
@@ -299,7 +317,9 @@ fn render_account_list(
|
|||||||
let active_marker = if *is_active { "\u{25b8} " } else { " " };
|
let active_marker = if *is_active { "\u{25b8} " } else { " " };
|
||||||
|
|
||||||
let style = if show_selected {
|
let style = if show_selected {
|
||||||
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD)
|
Style::default()
|
||||||
|
.fg(theme.accent())
|
||||||
|
.add_modifier(Modifier::BOLD)
|
||||||
} else if *is_active {
|
} else if *is_active {
|
||||||
Style::default()
|
Style::default()
|
||||||
.fg(theme.text())
|
.fg(theme.text())
|
||||||
@@ -315,7 +335,9 @@ fn render_account_list(
|
|||||||
|
|
||||||
if *acc_type == AccountType::Offline {
|
if *acc_type == AccountType::Offline {
|
||||||
let offline_style = if show_selected {
|
let offline_style = if show_selected {
|
||||||
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD)
|
Style::default()
|
||||||
|
.fg(theme.accent())
|
||||||
|
.add_modifier(Modifier::BOLD)
|
||||||
} else {
|
} else {
|
||||||
Style::default().fg(theme.text_dim())
|
Style::default().fg(theme.text_dim())
|
||||||
};
|
};
|
||||||
@@ -372,10 +394,7 @@ fn render_choose_popup(frame: &mut Frame) {
|
|||||||
.fg(accent_color)
|
.fg(accent_color)
|
||||||
.add_modifier(Modifier::BOLD),
|
.add_modifier(Modifier::BOLD),
|
||||||
),
|
),
|
||||||
Span::styled(
|
Span::styled("Microsoft Account", Style::default().fg(text_color)),
|
||||||
"Microsoft Account",
|
|
||||||
Style::default().fg(text_color),
|
|
||||||
),
|
|
||||||
]),
|
]),
|
||||||
Line::from(vec![
|
Line::from(vec![
|
||||||
Span::styled(
|
Span::styled(
|
||||||
@@ -384,10 +403,7 @@ fn render_choose_popup(frame: &mut Frame) {
|
|||||||
.fg(accent_color)
|
.fg(accent_color)
|
||||||
.add_modifier(Modifier::BOLD),
|
.add_modifier(Modifier::BOLD),
|
||||||
),
|
),
|
||||||
Span::styled(
|
Span::styled("Offline Account", Style::default().fg(text_color)),
|
||||||
"Offline Account",
|
|
||||||
Style::default().fg(text_color),
|
|
||||||
),
|
|
||||||
]),
|
]),
|
||||||
];
|
];
|
||||||
Paragraph::new(text).render(inner, buf);
|
Paragraph::new(text).render(inner, buf);
|
||||||
@@ -422,10 +438,7 @@ fn render_offline_popup(frame: &mut Frame, name: &str) {
|
|||||||
content: Box::new(move |inner, buf| {
|
content: Box::new(move |inner, buf| {
|
||||||
let line = if name.is_empty() {
|
let line = if name.is_empty() {
|
||||||
Line::from(vec![
|
Line::from(vec![
|
||||||
Span::styled(
|
Span::styled("Username...", Style::default().fg(dim_color)),
|
||||||
"Username...",
|
|
||||||
Style::default().fg(dim_color),
|
|
||||||
),
|
|
||||||
Span::styled(
|
Span::styled(
|
||||||
"\u{2588}",
|
"\u{2588}",
|
||||||
Style::default()
|
Style::default()
|
||||||
@@ -450,6 +463,36 @@ fn render_offline_popup(frame: &mut Frame, name: &str) {
|
|||||||
.render(area, frame.buffer_mut());
|
.render(area, frame.buffer_mut());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn render_offline_blocked_popup(frame: &mut Frame) {
|
||||||
|
use super::popups::{base::PopupFrame, keybind_line};
|
||||||
|
let theme = THEME.as_ref();
|
||||||
|
let area = popup_area(frame, 58, 5);
|
||||||
|
|
||||||
|
let border_color = theme.text_dim();
|
||||||
|
let bg_color = theme.surface();
|
||||||
|
let text_color = theme.text();
|
||||||
|
|
||||||
|
PopupFrame {
|
||||||
|
title: Line::from(Span::styled(
|
||||||
|
" Offline Account ",
|
||||||
|
Style::default()
|
||||||
|
.fg(border_color)
|
||||||
|
.add_modifier(Modifier::BOLD),
|
||||||
|
))
|
||||||
|
.centered(),
|
||||||
|
border_color,
|
||||||
|
bg: Some(bg_color),
|
||||||
|
keybinds: Some(keybind_line(&[("Enter", " close")])),
|
||||||
|
search_line: None,
|
||||||
|
content: Box::new(move |inner, buf| {
|
||||||
|
Paragraph::new("Add a Microsoft account that owns Minecraft first.")
|
||||||
|
.style(Style::default().fg(text_color))
|
||||||
|
.render(inner, buf);
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
.render(area, frame.buffer_mut());
|
||||||
|
}
|
||||||
|
|
||||||
fn render_confirm_delete(frame: &mut Frame, state: &AccountState, idx: usize) {
|
fn render_confirm_delete(frame: &mut Frame, state: &AccountState, idx: usize) {
|
||||||
use super::popups::{base::PopupFrame, keybind_line};
|
use super::popups::{base::PopupFrame, keybind_line};
|
||||||
let theme = THEME.as_ref();
|
let theme = THEME.as_ref();
|
||||||
@@ -534,10 +577,7 @@ fn render_device_code_popup(frame: &mut Frame, info: &DeviceCodeInfo) {
|
|||||||
)),
|
)),
|
||||||
Line::from(""),
|
Line::from(""),
|
||||||
Line::from(vec![
|
Line::from(vec![
|
||||||
Span::styled(
|
Span::styled("Enter code: ", Style::default().fg(dim_color)),
|
||||||
"Enter code: ",
|
|
||||||
Style::default().fg(dim_color),
|
|
||||||
),
|
|
||||||
Span::styled(
|
Span::styled(
|
||||||
code.as_str(),
|
code.as_str(),
|
||||||
Style::default()
|
Style::default()
|
||||||
|
|||||||
+334
-75
@@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex, mpsc};
|
||||||
|
|
||||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
@@ -21,14 +21,21 @@ use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
|
|||||||
use crate::config::theme::THEME;
|
use crate::config::theme::THEME;
|
||||||
use crate::instance::content::mods::{ContentEntry, IconCell};
|
use crate::instance::content::mods::{ContentEntry, IconCell};
|
||||||
|
|
||||||
type PendingContent = Arc<Mutex<Option<(String, Vec<ContentEntry>)>>>;
|
|
||||||
type SnapshotRow = (String, String, bool, Option<Vec<Vec<IconCell>>>);
|
type SnapshotRow = (String, String, bool, Option<Vec<Vec<IconCell>>>);
|
||||||
|
type ScanOneFn = fn(&Path, &str, bool) -> ContentEntry;
|
||||||
|
|
||||||
struct CachedList {
|
struct CachedList {
|
||||||
entries: Vec<ContentEntry>,
|
entries: Vec<ContentEntry>,
|
||||||
selected: Option<usize>,
|
selected: Option<usize>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// result from the notify-triggered background diff
|
||||||
|
struct WatcherDiff {
|
||||||
|
toggled: Vec<(String, bool, std::path::PathBuf)>,
|
||||||
|
removed: Vec<String>,
|
||||||
|
added: Vec<ContentEntry>,
|
||||||
|
}
|
||||||
|
|
||||||
pub struct ContentListState {
|
pub struct ContentListState {
|
||||||
pub entries: Vec<ContentEntry>,
|
pub entries: Vec<ContentEntry>,
|
||||||
pub list_state: TuiListState,
|
pub list_state: TuiListState,
|
||||||
@@ -37,10 +44,16 @@ pub struct ContentListState {
|
|||||||
pub loading: bool,
|
pub loading: bool,
|
||||||
pub search: crate::tui::widgets::search::SearchState,
|
pub search: crate::tui::widgets::search::SearchState,
|
||||||
cache: HashMap<String, CachedList>,
|
cache: HashMap<String, CachedList>,
|
||||||
pending: PendingContent,
|
// streaming: individual entries arrive here during initial load
|
||||||
check_counter: u16,
|
stream_rx: Option<mpsc::Receiver<ContentEntry>>,
|
||||||
|
// file watcher: notify callback spawns background work,
|
||||||
|
// precomputed diff lands here for the UI to pick up
|
||||||
|
watcher_diff: Arc<Mutex<Option<WatcherDiff>>>,
|
||||||
|
_watcher: Option<notify::RecommendedWatcher>,
|
||||||
watched_dir: Option<std::path::PathBuf>,
|
watched_dir: Option<std::path::PathBuf>,
|
||||||
last_dir_mtime: Option<std::time::SystemTime>,
|
// stored for the watcher to scan individual new files
|
||||||
|
scan_one_fn: Option<ScanOneFn>,
|
||||||
|
content_ext: Option<&'static str>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for ContentListState {
|
impl Default for ContentListState {
|
||||||
@@ -53,41 +66,229 @@ impl Default for ContentListState {
|
|||||||
loading: false,
|
loading: false,
|
||||||
search: crate::tui::widgets::search::SearchState::default(),
|
search: crate::tui::widgets::search::SearchState::default(),
|
||||||
cache: HashMap::new(),
|
cache: HashMap::new(),
|
||||||
pending: Arc::new(Mutex::new(None)),
|
stream_rx: None,
|
||||||
check_counter: 0,
|
watcher_diff: Arc::new(Mutex::new(None)),
|
||||||
|
_watcher: None,
|
||||||
watched_dir: None,
|
watched_dir: None,
|
||||||
last_dir_mtime: None,
|
scan_one_fn: None,
|
||||||
|
content_ext: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ContentListState {
|
impl ContentListState {
|
||||||
// poll the content directory for changes every ~120 ticks.
|
// drain streaming entries from the initial load. each entry arrives
|
||||||
// if the dir's mtime changed, invalidate the cache to pick up
|
// individually and is inserted in sorted position for a smooth fill-in
|
||||||
// mods/packs the user dropped in from outside the launcher
|
pub fn drain_pending(&mut self) {
|
||||||
pub fn try_rescan(&mut self) {
|
let Some(rx) = &self.stream_rx else {
|
||||||
self.check_counter = self.check_counter.wrapping_add(1);
|
|
||||||
if !self.check_counter.is_multiple_of(120) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let Some(dir) = &self.watched_dir else {
|
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
let current_mtime = std::fs::metadata(dir).ok().and_then(|m| m.modified().ok());
|
let mut received = false;
|
||||||
|
let mut finished = false;
|
||||||
if current_mtime != self.last_dir_mtime {
|
loop {
|
||||||
self.last_dir_mtime = current_mtime;
|
match rx.try_recv() {
|
||||||
if let Some(name) = &self.loaded_for {
|
Ok(entry) => {
|
||||||
self.cache.remove(name);
|
received = true;
|
||||||
self.loaded_for = None;
|
let pos = self
|
||||||
|
.entries
|
||||||
|
.binary_search_by(|e| {
|
||||||
|
e.name.to_lowercase().cmp(&entry.name.to_lowercase())
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|i| i);
|
||||||
|
self.entries.insert(pos, entry);
|
||||||
|
}
|
||||||
|
Err(mpsc::TryRecvError::Empty) => break,
|
||||||
|
Err(mpsc::TryRecvError::Disconnected) => {
|
||||||
|
self.stream_rx = None;
|
||||||
|
finished = true;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if received || finished {
|
||||||
|
self.loading = false;
|
||||||
|
if self.list_state.selected.is_none() && !self.entries.is_empty() {
|
||||||
|
self.list_state.selected = Some(0);
|
||||||
|
}
|
||||||
|
self.update_scrollbar();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// pick up the precomputed diff from the notify watcher callback.
|
||||||
|
// skip while streaming is in progress to avoid duplicate entries.
|
||||||
|
pub fn drain_watcher(&mut self) {
|
||||||
|
if self.stream_rx.is_some() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let diff = match self.watcher_diff.lock() {
|
||||||
|
Ok(mut slot) => slot.take(),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
let Some(diff) = diff else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
// apply toggles (enabled/path changes)
|
||||||
|
for (stem, enabled, path) in &diff.toggled {
|
||||||
|
if let Some(entry) = self.entries.iter_mut().find(|e| &e.file_stem == stem) {
|
||||||
|
entry.enabled = *enabled;
|
||||||
|
entry.path = path.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// apply removals
|
||||||
|
if !diff.removed.is_empty() {
|
||||||
|
self.entries
|
||||||
|
.retain(|e| !diff.removed.contains(&e.file_stem));
|
||||||
|
}
|
||||||
|
|
||||||
|
// insert new entries in sorted position
|
||||||
|
for entry in diff.added {
|
||||||
|
let pos = self
|
||||||
|
.entries
|
||||||
|
.binary_search_by(|e| e.name.to_lowercase().cmp(&entry.name.to_lowercase()))
|
||||||
|
.unwrap_or_else(|i| i);
|
||||||
|
self.entries.insert(pos, entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
// clamp selected
|
||||||
|
if let Some(sel) = self.list_state.selected {
|
||||||
|
if self.entries.is_empty() {
|
||||||
|
self.list_state.selected = None;
|
||||||
|
} else {
|
||||||
|
self.list_state.selected =
|
||||||
|
Some(sel.min(self.entries.len().saturating_sub(1)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.update_scrollbar();
|
||||||
|
}
|
||||||
|
|
||||||
|
// starts a notify file watcher on the given directory. changes trigger
|
||||||
|
// a background diff that lands in watcher_diff for drain_watcher to apply.
|
||||||
pub fn watch_dir(&mut self, dir: std::path::PathBuf) {
|
pub fn watch_dir(&mut self, dir: std::path::PathBuf) {
|
||||||
self.last_dir_mtime = std::fs::metadata(&dir).ok().and_then(|m| m.modified().ok());
|
use notify::{RecursiveMode, Watcher};
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
|
||||||
|
// drop previous watcher
|
||||||
|
self._watcher = None;
|
||||||
|
|
||||||
|
let watcher_diff = self.watcher_diff.clone();
|
||||||
|
let ext: &'static str = self.content_ext.unwrap_or(".jar");
|
||||||
|
let scan_one = self.scan_one_fn;
|
||||||
|
|
||||||
|
let dirty = Arc::new(AtomicBool::new(false));
|
||||||
|
let running = Arc::new(AtomicBool::new(false));
|
||||||
|
let dirty_cb = dirty.clone();
|
||||||
|
let running_cb = running.clone();
|
||||||
|
|
||||||
|
// initialize known stems from the current directory state so existing
|
||||||
|
// files are not treated as "new" on the first notify event
|
||||||
|
let known_stems = Arc::new(Mutex::new(read_dir_stems(&dir, ext)));
|
||||||
|
|
||||||
|
let watch_dir = dir.clone();
|
||||||
|
let watcher = notify::recommended_watcher(move |res: Result<notify::Event, _>| {
|
||||||
|
if res.is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// mark dirty. if a thread is already running it will loop to
|
||||||
|
// pick up the change after its current diff
|
||||||
|
dirty_cb.store(true, Ordering::Relaxed);
|
||||||
|
|
||||||
|
if running_cb.swap(true, Ordering::Relaxed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let dir = watch_dir.clone();
|
||||||
|
let diff_slot = watcher_diff.clone();
|
||||||
|
let dirty = dirty_cb.clone();
|
||||||
|
let running = running_cb.clone();
|
||||||
|
let known = known_stems.clone();
|
||||||
|
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
// always clear `running` even if we panic
|
||||||
|
struct ResetOnDrop(Arc<AtomicBool>);
|
||||||
|
impl Drop for ResetOnDrop {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.0.store(false, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _guard = ResetOnDrop(running);
|
||||||
|
|
||||||
|
loop {
|
||||||
|
dirty.store(false, Ordering::Relaxed);
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||||
|
|
||||||
|
let result = (|| {
|
||||||
|
let on_disk = read_dir_stems(&dir, ext);
|
||||||
|
let mut known_map = known.lock().ok()?;
|
||||||
|
|
||||||
|
let mut toggled = Vec::new();
|
||||||
|
let mut removed = Vec::new();
|
||||||
|
let mut added = Vec::new();
|
||||||
|
|
||||||
|
for (stem, (old_path, old_enabled)) in known_map.iter() {
|
||||||
|
if let Some((disk_path, disk_enabled)) = on_disk.get(stem) {
|
||||||
|
if *disk_enabled != *old_enabled || *disk_path != *old_path {
|
||||||
|
toggled.push((
|
||||||
|
stem.clone(),
|
||||||
|
*disk_enabled,
|
||||||
|
disk_path.clone(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
removed.push(stem.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (stem, (path, enabled)) in &on_disk {
|
||||||
|
if !known_map.contains_key(stem)
|
||||||
|
&& let Some(scan_one) = scan_one
|
||||||
|
{
|
||||||
|
added.push(scan_one(path, stem, *enabled));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
*known_map = on_disk;
|
||||||
|
|
||||||
|
Some(WatcherDiff {
|
||||||
|
toggled,
|
||||||
|
removed,
|
||||||
|
added,
|
||||||
|
})
|
||||||
|
})();
|
||||||
|
|
||||||
|
if let Some(diff) = result
|
||||||
|
&& let Ok(mut slot) = diff_slot.lock()
|
||||||
|
{
|
||||||
|
*slot = Some(diff);
|
||||||
|
}
|
||||||
|
|
||||||
|
if !dirty.load(Ordering::Relaxed) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
match watcher {
|
||||||
|
Ok(mut w) => {
|
||||||
|
if let Err(e) = w.watch(&dir, RecursiveMode::NonRecursive) {
|
||||||
|
tracing::warn!("Failed to watch {}: {e}", dir.display());
|
||||||
|
} else {
|
||||||
|
self._watcher = Some(w);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!("Failed to create file watcher: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
self.watched_dir = Some(dir);
|
self.watched_dir = Some(dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,11 +304,19 @@ impl ContentListState {
|
|||||||
|
|
||||||
impl ContentListState {
|
impl ContentListState {
|
||||||
// saves current entries to cache before loading new ones, and restores
|
// saves current entries to cache before loading new ones, and restores
|
||||||
// from cache if this instance was seen before (avoids re-scanning)
|
// from cache if this instance was seen before (avoids re-scanning).
|
||||||
pub fn start_load<F>(&mut self, instances_dir: &Path, instance_name: &str, scan_fn: F)
|
// content_dir is the actual directory to scan (e.g. .minecraft/mods).
|
||||||
where
|
pub fn start_load(
|
||||||
F: FnOnce(&Path, &str) -> Vec<ContentEntry> + Send + 'static,
|
&mut self,
|
||||||
{
|
content_dir: &Path,
|
||||||
|
instance_name: &str,
|
||||||
|
scan_one_fn: ScanOneFn,
|
||||||
|
ext: &'static str,
|
||||||
|
) {
|
||||||
|
self.scan_one_fn = Some(scan_one_fn);
|
||||||
|
self.content_ext = Some(ext);
|
||||||
|
|
||||||
|
// save current entries to cache
|
||||||
if let Some(prev) = self.loaded_for.take()
|
if let Some(prev) = self.loaded_for.take()
|
||||||
&& !self.entries.is_empty()
|
&& !self.entries.is_empty()
|
||||||
{
|
{
|
||||||
@@ -120,66 +329,62 @@ impl ContentListState {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// try cache first
|
||||||
if let Some(cached) = self.cache.remove(instance_name) {
|
if let Some(cached) = self.cache.remove(instance_name) {
|
||||||
self.entries = cached.entries;
|
self.entries = cached.entries;
|
||||||
self.list_state.selected = cached.selected;
|
self.list_state.selected = cached.selected;
|
||||||
self.loading = false;
|
self.loading = false;
|
||||||
} else {
|
self.stream_rx = None;
|
||||||
|
self.loaded_for = Some(instance_name.to_string());
|
||||||
|
self.update_scrollbar();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// no cache, stream entries one by one as each file is scanned
|
||||||
self.entries.clear();
|
self.entries.clear();
|
||||||
self.list_state = TuiListState::default();
|
self.list_state = TuiListState::default();
|
||||||
self.loading = true;
|
self.loading = true;
|
||||||
}
|
|
||||||
|
|
||||||
self.loaded_for = Some(instance_name.to_string());
|
self.loaded_for = Some(instance_name.to_string());
|
||||||
self.update_scrollbar();
|
self.update_scrollbar();
|
||||||
|
|
||||||
let dir = instances_dir.to_path_buf();
|
let (tx, rx) = mpsc::channel();
|
||||||
let tag = instance_name.to_string();
|
self.stream_rx = Some(rx);
|
||||||
let pending = self.pending.clone();
|
|
||||||
|
let dir = content_dir.to_path_buf();
|
||||||
|
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let scan_dir = dir.clone();
|
let _ = tokio::task::spawn_blocking(move || {
|
||||||
let scan_name = tag.clone();
|
let read_dir = match std::fs::read_dir(&dir) {
|
||||||
let entries = tokio::task::spawn_blocking(move || scan_fn(&scan_dir, &scan_name))
|
Ok(rd) => rd,
|
||||||
.await
|
Err(_) => return,
|
||||||
.unwrap_or_default();
|
};
|
||||||
|
let disabled_ext = format!("{ext}.disabled");
|
||||||
|
|
||||||
if let Ok(mut slot) = pending.lock() {
|
for dir_entry in read_dir.flatten() {
|
||||||
*slot = Some((tag, entries));
|
let path = dir_entry.path();
|
||||||
}
|
let Some(fname) = path.file_name().and_then(|n| n.to_str()) else {
|
||||||
});
|
continue;
|
||||||
}
|
|
||||||
|
|
||||||
pub fn drain_pending(&mut self) {
|
|
||||||
let taken = match self.pending.lock() {
|
|
||||||
Ok(mut slot) => slot.take(),
|
|
||||||
_ => None,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Some((instance_name, entries)) = taken
|
let (enabled, file_stem) =
|
||||||
&& (self.loaded_for.as_deref() == Some(&instance_name) || instance_name.is_empty())
|
if let Some(stem) = fname.strip_suffix(&disabled_ext) {
|
||||||
{
|
(false, stem.to_owned())
|
||||||
let selected_name = self
|
} else if let Some(stem) = fname.strip_suffix(ext) {
|
||||||
.list_state
|
(true, stem.to_owned())
|
||||||
.selected
|
} else if path.is_dir() {
|
||||||
.and_then(|i| self.entries.get(i))
|
crate::instance::content::parse_enabled_stem_dir(fname)
|
||||||
.map(|e| e.name.clone());
|
|
||||||
|
|
||||||
self.entries = entries;
|
|
||||||
self.loading = false;
|
|
||||||
|
|
||||||
if !self.entries.is_empty() {
|
|
||||||
let new_index = selected_name
|
|
||||||
.and_then(|name| self.entries.iter().position(|e| e.name == name))
|
|
||||||
.or(self.list_state.selected)
|
|
||||||
.map(|i| i.min(self.entries.len().saturating_sub(1)))
|
|
||||||
.unwrap_or(0);
|
|
||||||
self.list_state.selected = Some(new_index);
|
|
||||||
} else {
|
} else {
|
||||||
self.list_state.selected = None;
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
let entry = scan_one_fn(&path, &file_stem, enabled);
|
||||||
|
if tx.send(entry).is_err() {
|
||||||
|
break; // receiver dropped (instance switched)
|
||||||
}
|
}
|
||||||
self.update_scrollbar();
|
|
||||||
}
|
}
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn update_scrollbar(&mut self) {
|
fn update_scrollbar(&mut self) {
|
||||||
@@ -233,6 +438,11 @@ impl ContentListState {
|
|||||||
fn handle_search_keys(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
|
fn handle_search_keys(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
|
||||||
if state.search.active {
|
if state.search.active {
|
||||||
match key_event.code {
|
match key_event.code {
|
||||||
|
KeyCode::Enter => {
|
||||||
|
state.search.confirm();
|
||||||
|
state.list_state.selected = Some(0);
|
||||||
|
state.update_scrollbar();
|
||||||
|
}
|
||||||
KeyCode::Esc => {
|
KeyCode::Esc => {
|
||||||
state.search.deactivate();
|
state.search.deactivate();
|
||||||
state.list_state.selected = Some(0);
|
state.list_state.selected = Some(0);
|
||||||
@@ -286,7 +496,7 @@ pub fn handle_key_no_toggle(key_event: &KeyEvent, state: &mut ContentListState)
|
|||||||
KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => {
|
KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => {
|
||||||
if let Some(&real_idx) = state.list_state.selected.and_then(|i| filtered.get(i))
|
if let Some(&real_idx) = state.list_state.selected.and_then(|i| filtered.get(i))
|
||||||
&& let Some(dir) = state.entries[real_idx].path.parent()
|
&& let Some(dir) = state.entries[real_idx].path.parent()
|
||||||
&& let Err(e) = open::that(dir)
|
&& let Err(e) = open::that_detached(dir)
|
||||||
{
|
{
|
||||||
tracing::error!("Failed to open directory: {}", e);
|
tracing::error!("Failed to open directory: {}", e);
|
||||||
}
|
}
|
||||||
@@ -321,7 +531,7 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
|
|||||||
KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => {
|
KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => {
|
||||||
if let Some(&real_idx) = state.list_state.selected.and_then(|i| filtered.get(i))
|
if let Some(&real_idx) = state.list_state.selected.and_then(|i| filtered.get(i))
|
||||||
&& let Some(dir) = state.entries[real_idx].path.parent()
|
&& let Some(dir) = state.entries[real_idx].path.parent()
|
||||||
&& let Err(e) = open::that(dir)
|
&& let Err(e) = open::that_detached(dir)
|
||||||
{
|
{
|
||||||
tracing::error!("Failed to open directory: {}", e);
|
tracing::error!("Failed to open directory: {}", e);
|
||||||
}
|
}
|
||||||
@@ -360,6 +570,7 @@ pub fn render(
|
|||||||
let filtered = state.filtered_indices();
|
let filtered = state.filtered_indices();
|
||||||
|
|
||||||
if filtered.is_empty() {
|
if filtered.is_empty() {
|
||||||
|
state.list_state.selected = None;
|
||||||
frame.render_widget(
|
frame.render_widget(
|
||||||
Paragraph::new(empty_text).style(Style::default().fg(theme.text_dim())),
|
Paragraph::new(empty_text).style(Style::default().fg(theme.text_dim())),
|
||||||
area,
|
area,
|
||||||
@@ -369,6 +580,13 @@ pub fn render(
|
|||||||
|
|
||||||
let count = filtered.len();
|
let count = filtered.len();
|
||||||
|
|
||||||
|
// clamp selected so the ListView builder never gets an out-of-bounds index
|
||||||
|
if let Some(sel) = state.list_state.selected
|
||||||
|
&& sel >= count
|
||||||
|
{
|
||||||
|
state.list_state.selected = Some(count.saturating_sub(1));
|
||||||
|
}
|
||||||
|
|
||||||
let snapshot: Vec<SnapshotRow> = filtered
|
let snapshot: Vec<SnapshotRow> = filtered
|
||||||
.iter()
|
.iter()
|
||||||
.map(|&i| {
|
.map(|&i| {
|
||||||
@@ -656,3 +874,44 @@ fn icon_spans(icon_pixels: Option<&Vec<Vec<IconCell>>>, row: usize) -> Vec<Span<
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// reads a content directory and builds a stem -> (path, enabled) map.
|
||||||
|
// used both by watch_dir to initialize known state and by the watcher
|
||||||
|
// thread to detect changes. when ext is empty (worlds), only directories
|
||||||
|
// are included.
|
||||||
|
fn read_dir_stems(
|
||||||
|
dir: &std::path::Path,
|
||||||
|
ext: &str,
|
||||||
|
) -> HashMap<String, (std::path::PathBuf, bool)> {
|
||||||
|
let mut map = HashMap::new();
|
||||||
|
let Ok(read_dir) = std::fs::read_dir(dir) else {
|
||||||
|
return map;
|
||||||
|
};
|
||||||
|
let dirs_only = ext.is_empty();
|
||||||
|
let disabled_ext = format!("{ext}.disabled");
|
||||||
|
|
||||||
|
for dir_entry in read_dir.flatten() {
|
||||||
|
let path = dir_entry.path();
|
||||||
|
let Some(fname) = path.file_name().and_then(|n| n.to_str()) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if dirs_only {
|
||||||
|
if !path.is_dir() && !fname.ends_with(".disabled") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let (enabled, stem) = crate::instance::content::parse_enabled_stem_dir(fname);
|
||||||
|
map.insert(stem, (path, enabled));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(stem) = fname.strip_suffix(&disabled_ext) {
|
||||||
|
map.insert(stem.to_owned(), (path, false));
|
||||||
|
} else if let Some(stem) = fname.strip_suffix(ext) {
|
||||||
|
map.insert(stem.to_owned(), (path, true));
|
||||||
|
} else if path.is_dir() {
|
||||||
|
let (enabled, stem) = crate::instance::content::parse_enabled_stem_dir(fname);
|
||||||
|
map.insert(stem, (path, enabled));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
map
|
||||||
|
}
|
||||||
@@ -3,5 +3,5 @@
|
|||||||
pub mod list;
|
pub mod list;
|
||||||
pub mod tabs;
|
pub mod tabs;
|
||||||
|
|
||||||
pub use tabs::{ContentTab, render, title};
|
|
||||||
pub use list::{ContentListState, handle_key, handle_key_no_toggle};
|
pub use list::{ContentListState, handle_key, handle_key_no_toggle};
|
||||||
|
pub use tabs::{ContentTab, render, title};
|
||||||
@@ -3,16 +3,16 @@
|
|||||||
// also renders the instance name/version header with run state indicators.
|
// also renders the instance name/version header with run state indicators.
|
||||||
|
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
|
Frame,
|
||||||
layout::{Alignment, Constraint, Layout, Rect},
|
layout::{Alignment, Constraint, Layout, Rect},
|
||||||
style::{Modifier, Style},
|
style::{Modifier, Style},
|
||||||
text::{Line, Span},
|
text::{Line, Span},
|
||||||
widgets::{Block, Borders, Paragraph},
|
widgets::{Block, Borders, Paragraph},
|
||||||
Frame,
|
|
||||||
};
|
};
|
||||||
use throbber_widgets_tui::{Throbber, ThrobberState};
|
use throbber_widgets_tui::{Throbber, ThrobberState};
|
||||||
|
|
||||||
|
use crate::config::theme::{BORDER_STYLE, THEME};
|
||||||
use crate::tui::app::FocusedArea;
|
use crate::tui::app::FocusedArea;
|
||||||
use crate::config::theme::{THEME, BORDER_STYLE};
|
|
||||||
|
|
||||||
use crate::tui::widgets::styled_title;
|
use crate::tui::widgets::styled_title;
|
||||||
|
|
||||||
@@ -200,7 +200,8 @@ pub fn render(
|
|||||||
};
|
};
|
||||||
|
|
||||||
if let Some(kb) = kb {
|
if let Some(kb) = kb {
|
||||||
let lines = crate::tui::widgets::popups::keybind_lines_wrapped(kb, area.width.saturating_sub(2));
|
let lines =
|
||||||
|
crate::tui::widgets::popups::keybind_lines_wrapped(kb, area.width.saturating_sub(2));
|
||||||
for line in lines {
|
for line in lines {
|
||||||
block = block.title_bottom(line);
|
block = block.title_bottom(line);
|
||||||
}
|
}
|
||||||
@@ -214,12 +215,9 @@ pub fn render(
|
|||||||
ContentTab::Mods => {
|
ContentTab::Mods => {
|
||||||
if let Some(instance) = instance {
|
if let Some(instance) = instance {
|
||||||
if mods_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
if mods_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
||||||
mods_state.start_load(
|
let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("mods");
|
||||||
instances_dir,
|
mods_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_mod, ".jar");
|
||||||
&instance.name,
|
mods_state.watch_dir(content_dir);
|
||||||
crate::instance::scan_mods,
|
|
||||||
);
|
|
||||||
mods_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("mods"));
|
|
||||||
}
|
}
|
||||||
super::list::render(
|
super::list::render(
|
||||||
frame,
|
frame,
|
||||||
@@ -240,12 +238,9 @@ pub fn render(
|
|||||||
ContentTab::ResourcePacks => {
|
ContentTab::ResourcePacks => {
|
||||||
if let Some(instance) = instance {
|
if let Some(instance) = instance {
|
||||||
if resource_packs_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
if resource_packs_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
||||||
resource_packs_state.start_load(
|
let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("resourcepacks");
|
||||||
instances_dir,
|
resource_packs_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_resource_pack, ".zip");
|
||||||
&instance.name,
|
resource_packs_state.watch_dir(content_dir);
|
||||||
crate::instance::scan_resource_packs,
|
|
||||||
);
|
|
||||||
resource_packs_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("resourcepacks"));
|
|
||||||
}
|
}
|
||||||
super::list::render(
|
super::list::render(
|
||||||
frame,
|
frame,
|
||||||
@@ -266,12 +261,9 @@ pub fn render(
|
|||||||
ContentTab::Shaders => {
|
ContentTab::Shaders => {
|
||||||
if let Some(instance) = instance {
|
if let Some(instance) = instance {
|
||||||
if shaders_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
if shaders_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
||||||
shaders_state.start_load(
|
let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("shaderpacks");
|
||||||
instances_dir,
|
shaders_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_shader, ".zip");
|
||||||
&instance.name,
|
shaders_state.watch_dir(content_dir);
|
||||||
crate::instance::scan_shaders,
|
|
||||||
);
|
|
||||||
shaders_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("shaderpacks"));
|
|
||||||
}
|
}
|
||||||
super::list::render(
|
super::list::render(
|
||||||
frame,
|
frame,
|
||||||
@@ -294,7 +286,12 @@ pub fn render(
|
|||||||
if logs_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
if logs_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
||||||
logs_state.start_load(instances_dir, &instance.name);
|
logs_state.start_load(instances_dir, &instance.name);
|
||||||
}
|
}
|
||||||
crate::tui::widgets::logs_viewer::render(frame, content_area, logs_state, is_focused);
|
crate::tui::widgets::logs_viewer::render(
|
||||||
|
frame,
|
||||||
|
content_area,
|
||||||
|
logs_state,
|
||||||
|
is_focused,
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
frame.render_widget(
|
frame.render_widget(
|
||||||
Paragraph::new("No instance selected.")
|
Paragraph::new("No instance selected.")
|
||||||
@@ -308,7 +305,12 @@ pub fn render(
|
|||||||
if screenshots_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
if screenshots_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
||||||
screenshots_state.start_load(instances_dir, &instance.name);
|
screenshots_state.start_load(instances_dir, &instance.name);
|
||||||
}
|
}
|
||||||
crate::tui::widgets::screenshots_grid::render(frame, content_area, screenshots_state, is_focused);
|
crate::tui::widgets::screenshots_grid::render(
|
||||||
|
frame,
|
||||||
|
content_area,
|
||||||
|
screenshots_state,
|
||||||
|
is_focused,
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
frame.render_widget(
|
frame.render_widget(
|
||||||
Paragraph::new("No instance selected.")
|
Paragraph::new("No instance selected.")
|
||||||
@@ -320,12 +322,9 @@ pub fn render(
|
|||||||
ContentTab::Worlds => {
|
ContentTab::Worlds => {
|
||||||
if let Some(instance) = instance {
|
if let Some(instance) = instance {
|
||||||
if worlds_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
if worlds_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
|
||||||
worlds_state.start_load(
|
let content_dir = instances_dir.join(&instance.name).join(".minecraft").join("saves");
|
||||||
instances_dir,
|
worlds_state.start_load(&content_dir, &instance.name, crate::instance::scan_one_world, "");
|
||||||
&instance.name,
|
worlds_state.watch_dir(content_dir);
|
||||||
crate::instance::scan_worlds,
|
|
||||||
);
|
|
||||||
worlds_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("saves"));
|
|
||||||
}
|
}
|
||||||
super::list::render(
|
super::list::render(
|
||||||
frame,
|
frame,
|
||||||
@@ -374,8 +373,7 @@ pub fn title(
|
|||||||
match instance {
|
match instance {
|
||||||
None => {
|
None => {
|
||||||
frame.render_widget(
|
frame.render_widget(
|
||||||
Paragraph::new("No instance selected")
|
Paragraph::new("No instance selected").style(Style::default().fg(theme.text_dim())),
|
||||||
.style(Style::default().fg(theme.text_dim())),
|
|
||||||
inner,
|
inner,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+115
-10
@@ -2,22 +2,22 @@
|
|||||||
// handles search/filter, scrollbar sync, and inline renaming.
|
// handles search/filter, scrollbar sync, and inline renaming.
|
||||||
// each row shows instance name + "last played" or current run state.
|
// each row shows instance name + "last played" or current run state.
|
||||||
|
|
||||||
use crate::config::theme::{THEME, BORDER_STYLE};
|
use crate::config::theme::{BORDER_STYLE, THEME};
|
||||||
use crossterm::event::KeyCode;
|
use crossterm::event::KeyCode;
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
|
Frame,
|
||||||
layout::Rect,
|
layout::Rect,
|
||||||
style::{Modifier, Style},
|
style::{Modifier, Style},
|
||||||
text::{Line, Span, Text},
|
text::{Line, Span, Text},
|
||||||
widgets::{Block, Borders, Scrollbar, ScrollbarOrientation, ScrollbarState},
|
widgets::{Block, Borders, Scrollbar, ScrollbarOrientation, ScrollbarState},
|
||||||
Frame,
|
|
||||||
};
|
};
|
||||||
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
|
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
|
||||||
|
|
||||||
use crate::instance::models::InstanceConfig;
|
use crate::instance::models::InstanceConfig;
|
||||||
use crate::running::{get as get_run_state, RunState};
|
use crate::running::{RunState, get as get_run_state};
|
||||||
use crate::tui::app::FocusedArea;
|
use crate::tui::app::FocusedArea;
|
||||||
|
|
||||||
use super::{search::SearchState, styled_title, WidgetKey};
|
use super::{WidgetKey, search::SearchState, styled_title};
|
||||||
|
|
||||||
// rough human-friendly time delta. not trying to be precise here,
|
// rough human-friendly time delta. not trying to be precise here,
|
||||||
// "2 months ago" is close enough when months are ~30 days
|
// "2 months ago" is close enough when months are ~30 days
|
||||||
@@ -149,12 +149,30 @@ impl State {
|
|||||||
self.instances.push(instance);
|
self.instances.push(instance);
|
||||||
self.update_scrollbar();
|
self.update_scrollbar();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn replace_instance(&mut self, old_name: &str, instance: InstanceConfig) {
|
||||||
|
if let Some(existing) = self
|
||||||
|
.instances
|
||||||
|
.iter_mut()
|
||||||
|
.find(|i| i.name == old_name || i.name == instance.name)
|
||||||
|
{
|
||||||
|
*existing = instance;
|
||||||
|
} else {
|
||||||
|
self.instances.push(instance);
|
||||||
|
}
|
||||||
|
self.update_scrollbar();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WidgetKey for State {
|
impl WidgetKey for State {
|
||||||
fn handle_key(&mut self, key_event: &crossterm::event::KeyEvent) {
|
fn handle_key(&mut self, key_event: &crossterm::event::KeyEvent) {
|
||||||
if self.search.active {
|
if self.search.active {
|
||||||
match key_event.code {
|
match key_event.code {
|
||||||
|
KeyCode::Enter => {
|
||||||
|
self.search.confirm();
|
||||||
|
self.list_state.selected = Some(0);
|
||||||
|
self.update_scrollbar();
|
||||||
|
}
|
||||||
KeyCode::Esc => {
|
KeyCode::Esc => {
|
||||||
self.search.deactivate();
|
self.search.deactivate();
|
||||||
self.list_state.selected = Some(0);
|
self.list_state.selected = Some(0);
|
||||||
@@ -237,7 +255,9 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
|
|||||||
|
|
||||||
let (name_style, meta_style, bg) = if context.is_selected {
|
let (name_style, meta_style, bg) = if context.is_selected {
|
||||||
(
|
(
|
||||||
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD),
|
Style::default()
|
||||||
|
.fg(theme.accent())
|
||||||
|
.add_modifier(Modifier::BOLD),
|
||||||
Style::default().fg(theme.text_dim()),
|
Style::default().fg(theme.text_dim()),
|
||||||
stripe_bg,
|
stripe_bg,
|
||||||
)
|
)
|
||||||
@@ -282,14 +302,16 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
|
|||||||
"Authenticating".to_string(),
|
"Authenticating".to_string(),
|
||||||
Style::default().fg(theme.success()),
|
Style::default().fg(theme.success()),
|
||||||
),
|
),
|
||||||
Some(RunState::Running) | Some(RunState::Starting) => (
|
Some(RunState::Running) | Some(RunState::Starting) => {
|
||||||
"Playing".to_string(),
|
("Playing".to_string(), Style::default().fg(theme.success()))
|
||||||
Style::default().fg(theme.success()),
|
}
|
||||||
),
|
|
||||||
_ => (format_last_played(instance.last_played), meta_style),
|
_ => (format_last_played(instance.last_played), meta_style),
|
||||||
};
|
};
|
||||||
|
|
||||||
let meta_line = Line::from(vec![selector.clone(), Span::styled(meta_text, meta_text_style)]);
|
let meta_line = Line::from(vec![
|
||||||
|
selector.clone(),
|
||||||
|
Span::styled(meta_text, meta_text_style),
|
||||||
|
]);
|
||||||
|
|
||||||
let item = Text::from(vec![name_line, meta_line]).style(Style::default().bg(bg));
|
let item = Text::from(vec![name_line, meta_line]).style(Style::default().bg(bg));
|
||||||
(item, 2)
|
(item, 2)
|
||||||
@@ -315,3 +337,86 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
|
|||||||
&mut state.scrollbar_state,
|
&mut state.scrollbar_state,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn format_last_played_none_returns_never_played() {
|
||||||
|
assert_eq!(format_last_played(None), "Never played");
|
||||||
|
}
|
||||||
|
|
||||||
|
// each #[case] picks a "seconds ago" value that lands in exactly one
|
||||||
|
// bucket of the match. mutating any bucket boundary (e.g. 3600 to 3601,
|
||||||
|
// or "minutes" to "seconds") makes one of these cases fail.
|
||||||
|
#[rstest::rstest]
|
||||||
|
#[case::just_now(0, "Just now")]
|
||||||
|
#[case::just_now_upper(59, "Just now")]
|
||||||
|
#[case::minutes(60, "1 minutes ago")]
|
||||||
|
#[case::minutes_upper(3599, "59 minutes ago")]
|
||||||
|
#[case::hours(3600, "1 hours ago")]
|
||||||
|
#[case::hours_upper(86_399, "23 hours ago")]
|
||||||
|
#[case::days(86_400, "1 days ago")]
|
||||||
|
#[case::days_upper(2_591_999, "29 days ago")]
|
||||||
|
#[case::months(2_592_000, "1 months ago")]
|
||||||
|
#[case::months_upper(31_535_999, "12 months ago")]
|
||||||
|
#[case::over_a_year(31_536_000, "Over a year ago")]
|
||||||
|
fn format_last_played_buckets(#[case] seconds_ago: i64, #[case] expected: &str) {
|
||||||
|
let dt = chrono::Utc::now() - chrono::Duration::seconds(seconds_ago);
|
||||||
|
assert_eq!(format_last_played(Some(dt)), expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
use crate::instance::models::{InstanceConfig, ModLoader};
|
||||||
|
use ratatui::Terminal;
|
||||||
|
use ratatui::backend::TestBackend;
|
||||||
|
|
||||||
|
fn synthetic_instance(name: &str) -> InstanceConfig {
|
||||||
|
// last_played intentionally None so the rendered text is the
|
||||||
|
// deterministic "Never played" string. anything else would make the
|
||||||
|
// snapshot drift relative to chrono::Utc::now().
|
||||||
|
InstanceConfig {
|
||||||
|
name: name.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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn instances_list_renders_three_instances() {
|
||||||
|
let mut state = State::with_instances(vec![
|
||||||
|
synthetic_instance("Vanilla 1.20.1"),
|
||||||
|
synthetic_instance("Forge Pack"),
|
||||||
|
synthetic_instance("Fabric Test"),
|
||||||
|
]);
|
||||||
|
|
||||||
|
let backend = TestBackend::new(40, 12);
|
||||||
|
let mut terminal = Terminal::new(backend).unwrap();
|
||||||
|
terminal
|
||||||
|
.draw(|f| render(f, f.area(), FocusedArea::Instances, &mut state))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
insta::assert_snapshot!(terminal.backend());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn instances_list_renders_empty() {
|
||||||
|
let mut state = State::with_instances(vec![]);
|
||||||
|
|
||||||
|
let backend = TestBackend::new(40, 8);
|
||||||
|
let mut terminal = Terminal::new(backend).unwrap();
|
||||||
|
terminal
|
||||||
|
.draw(|f| render(f, f.area(), FocusedArea::Instances, &mut state))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
insta::assert_snapshot!(terminal.backend());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,16 +8,16 @@ use std::sync::{Arc, Mutex};
|
|||||||
|
|
||||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||||
use ratatui::{
|
use ratatui::{
|
||||||
|
Frame,
|
||||||
layout::{Constraint, Layout, Rect},
|
layout::{Constraint, Layout, Rect},
|
||||||
style::{Modifier, Style},
|
style::{Modifier, Style},
|
||||||
text::{Line, Span},
|
text::{Line, Span},
|
||||||
widgets::{Block, Borders, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
|
widgets::{Block, Borders, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
|
||||||
Frame,
|
|
||||||
};
|
};
|
||||||
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
|
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
|
||||||
|
|
||||||
use crate::instance::log_files::{read_log_file, scan_log_files, LogFileEntry};
|
use crate::config::theme::{BORDER_STYLE, THEME};
|
||||||
use crate::config::theme::{THEME, BORDER_STYLE};
|
use crate::instance::log_files::{LogFileEntry, read_log_file, scan_log_files};
|
||||||
|
|
||||||
type PendingLogs = Arc<Mutex<Option<(String, Vec<LogFileEntry>)>>>;
|
type PendingLogs = Arc<Mutex<Option<(String, Vec<LogFileEntry>)>>>;
|
||||||
|
|
||||||
@@ -38,6 +38,7 @@ pub struct LogsState {
|
|||||||
pending: PendingLogs,
|
pending: PendingLogs,
|
||||||
rescan_counter: u8,
|
rescan_counter: u8,
|
||||||
instances_dir_cache: Option<std::path::PathBuf>,
|
instances_dir_cache: Option<std::path::PathBuf>,
|
||||||
|
was_live: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for LogsState {
|
impl Default for LogsState {
|
||||||
@@ -59,6 +60,7 @@ impl Default for LogsState {
|
|||||||
pending: Arc::new(Mutex::new(None)),
|
pending: Arc::new(Mutex::new(None)),
|
||||||
rescan_counter: 0,
|
rescan_counter: 0,
|
||||||
instances_dir_cache: None,
|
instances_dir_cache: None,
|
||||||
|
was_live: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -94,14 +96,22 @@ impl LogsState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn drain_pending(&mut self) {
|
pub fn drain_pending(&mut self) {
|
||||||
let taken = match self.pending.lock() { Ok(mut slot) => {
|
// when the instance stops while viewing the live log, transition
|
||||||
slot.take()
|
// to the on-disk log file so the viewer doesn't go blank
|
||||||
} _ => {
|
let live_now = self.has_live();
|
||||||
None
|
if self.was_live && !live_now && self.list_state.selected == Some(0) {
|
||||||
}};
|
self.load_selected_content();
|
||||||
|
}
|
||||||
|
self.was_live = live_now;
|
||||||
|
|
||||||
|
let taken = match self.pending.lock() {
|
||||||
|
Ok(mut slot) => slot.take(),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
if let Some((instance_name, entries)) = taken
|
if let Some((instance_name, entries)) = taken
|
||||||
&& self.loaded_for.as_deref() == Some(&instance_name) {
|
&& self.loaded_for.as_deref() == Some(&instance_name)
|
||||||
|
{
|
||||||
let prev_selected = self.list_state.selected;
|
let prev_selected = self.list_state.selected;
|
||||||
self.entries = entries;
|
self.entries = entries;
|
||||||
self.loading = false;
|
self.loading = false;
|
||||||
@@ -112,7 +122,9 @@ impl LogsState {
|
|||||||
self.list_state.selected = Some(0);
|
self.list_state.selected = Some(0);
|
||||||
self.load_selected_content();
|
self.load_selected_content();
|
||||||
} else if let Some(sel) = prev_selected
|
} else if let Some(sel) = prev_selected
|
||||||
&& sel >= display_count && display_count > 0 {
|
&& sel >= display_count
|
||||||
|
&& display_count > 0
|
||||||
|
{
|
||||||
self.list_state.selected = Some(display_count - 1);
|
self.list_state.selected = Some(display_count - 1);
|
||||||
}
|
}
|
||||||
self.update_scrollbar();
|
self.update_scrollbar();
|
||||||
@@ -225,6 +237,10 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
|
|||||||
if state.viewer_focused {
|
if state.viewer_focused {
|
||||||
if state.viewer_search.active {
|
if state.viewer_search.active {
|
||||||
match key_event.code {
|
match key_event.code {
|
||||||
|
KeyCode::Enter => {
|
||||||
|
state.viewer_search.confirm();
|
||||||
|
state.viewer_scroll = 0;
|
||||||
|
}
|
||||||
KeyCode::Esc => {
|
KeyCode::Esc => {
|
||||||
state.viewer_search.deactivate();
|
state.viewer_search.deactivate();
|
||||||
state.viewer_scroll = 0;
|
state.viewer_scroll = 0;
|
||||||
@@ -288,6 +304,11 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
|
|||||||
} else {
|
} else {
|
||||||
if state.search.active {
|
if state.search.active {
|
||||||
match key_event.code {
|
match key_event.code {
|
||||||
|
KeyCode::Enter => {
|
||||||
|
state.search.confirm();
|
||||||
|
state.list_state.selected = Some(0);
|
||||||
|
state.update_scrollbar();
|
||||||
|
}
|
||||||
KeyCode::Esc => {
|
KeyCode::Esc => {
|
||||||
state.search.deactivate();
|
state.search.deactivate();
|
||||||
state.list_state.selected = Some(0);
|
state.list_state.selected = Some(0);
|
||||||
@@ -408,7 +429,12 @@ fn render_list(
|
|||||||
let entries_snapshot: Vec<(String, bool)> = {
|
let entries_snapshot: Vec<(String, bool)> = {
|
||||||
let mut v = Vec::new();
|
let mut v = Vec::new();
|
||||||
if has_live {
|
if has_live {
|
||||||
v.push(("\u{25cf} Live".to_string(), true));
|
let live_name = state
|
||||||
|
.entries
|
||||||
|
.first()
|
||||||
|
.map(|e| e.name.trim_end_matches(".log"))
|
||||||
|
.unwrap_or("Live");
|
||||||
|
v.push((live_name.to_string(), true));
|
||||||
}
|
}
|
||||||
for e in &state.entries {
|
for e in &state.entries {
|
||||||
v.push((e.name.trim_end_matches(".log").to_string(), false));
|
v.push((e.name.trim_end_matches(".log").to_string(), false));
|
||||||
@@ -421,11 +447,15 @@ fn render_list(
|
|||||||
let show_selected = list_focused && context.is_selected;
|
let show_selected = list_focused && context.is_selected;
|
||||||
|
|
||||||
let style = if *is_live && show_selected {
|
let style = if *is_live && show_selected {
|
||||||
Style::default().fg(theme.success()).add_modifier(Modifier::BOLD)
|
Style::default()
|
||||||
|
.fg(theme.success())
|
||||||
|
.add_modifier(Modifier::BOLD)
|
||||||
} else if *is_live {
|
} else if *is_live {
|
||||||
Style::default().fg(theme.success())
|
Style::default().fg(theme.success())
|
||||||
} else if show_selected {
|
} else if show_selected {
|
||||||
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD)
|
Style::default()
|
||||||
|
.fg(theme.accent())
|
||||||
|
.add_modifier(Modifier::BOLD)
|
||||||
} else {
|
} else {
|
||||||
Style::default().fg(theme.text())
|
Style::default().fg(theme.text())
|
||||||
};
|
};
|
||||||
@@ -441,7 +471,10 @@ fn render_list(
|
|||||||
} else {
|
} else {
|
||||||
Span::raw(" ")
|
Span::raw(" ")
|
||||||
};
|
};
|
||||||
let item = ratatui::text::Text::from(Line::from(vec![selector, Span::styled(name.clone(), style)]))
|
let item = ratatui::text::Text::from(Line::from(vec![
|
||||||
|
selector,
|
||||||
|
Span::styled(name.clone(), style),
|
||||||
|
]))
|
||||||
.style(Style::default().bg(bg));
|
.style(Style::default().bg(bg));
|
||||||
(item, 1)
|
(item, 1)
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -9,10 +9,10 @@ use ratatui::{
|
|||||||
|
|
||||||
pub mod account;
|
pub mod account;
|
||||||
pub mod content;
|
pub mod content;
|
||||||
pub mod details;
|
pub mod settings;
|
||||||
|
pub mod instances;
|
||||||
pub mod logs_viewer;
|
pub mod logs_viewer;
|
||||||
pub mod popups;
|
pub mod popups;
|
||||||
pub mod instances;
|
|
||||||
pub mod screenshots_grid;
|
pub mod screenshots_grid;
|
||||||
pub mod search;
|
pub mod search;
|
||||||
pub mod status;
|
pub mod status;
|
||||||
|
|||||||
Loaded 100 of 138 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user