Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e58da16cdc | ||
|
|
eabe74dba8 | ||
|
|
acfab673a3 | ||
|
|
25a4b90f1f | ||
|
|
464b279570 | ||
|
|
913d2c9254 | ||
|
|
874c38d7f8 | ||
|
|
51ec22ad67 | ||
|
|
894a0d6cf8 | ||
|
|
526db91665 | ||
|
|
017f7e4d17 | ||
|
|
c2e039e412 | ||
|
|
ad039cab05 | ||
|
|
41707c8a09 | ||
|
|
b5c680ed55 | ||
|
|
8adadf75a8 | ||
|
|
9c54e8f321 | ||
|
|
65edd0b31b | ||
|
|
ce0bb34401 | ||
|
|
f5068d09d2 | ||
|
|
7cbfe9cd0d | ||
|
|
3479a05e63 | ||
|
|
8998139934 | ||
|
|
7ead3706a2 | ||
|
|
9cd454cee2 | ||
|
|
eb53c7164e | ||
|
|
00ba2faffe | ||
|
|
dc351df546 | ||
|
|
eb436c2ab8 | ||
|
|
7362354109 | ||
|
|
615d3fb8fc | ||
|
|
cf9007fa06 | ||
|
|
7ea4860202 | ||
|
|
260ad39c03 | ||
|
|
500d72a473 | ||
|
|
2114cdc72a | ||
|
|
4de886fcd0 | ||
|
|
75c74333c5 | ||
|
|
0d1cafcb10 | ||
|
|
3149b96971 | ||
|
|
2b6750a971 | ||
|
|
22a3eebe78 | ||
|
|
7e7e5c0c31 | ||
|
|
783fb76f06 | ||
|
|
04c92f17bf | ||
|
|
3525c7b69c | ||
|
|
6167cc8f2a | ||
|
|
9d76f852aa | ||
|
|
68bbf6fc1c | ||
|
|
df4feaa5a1 | ||
|
|
495f31778b | ||
|
|
69a1010d4a | ||
|
|
cef09e32ad | ||
|
|
28c0731478 | ||
|
|
9d480f8bfb | ||
|
|
978fd3e971 | ||
|
|
bdc78c54e7 | ||
|
|
3259608c3b | ||
|
|
1747e64278 | ||
|
|
a529a4cb35 | ||
|
|
9932de1c73 | ||
|
|
88dfef51ad | ||
|
|
644afd430a | ||
|
|
884a0b6df3 | ||
|
|
38cd978f29 | ||
|
|
de61fb747f | ||
|
|
38d240ba7b | ||
|
|
a78bcff171 | ||
|
|
d38b0b74b5 | ||
|
|
902b0e9347 | ||
|
|
af6d0b003b | ||
|
|
a7ace33ae1 | ||
|
|
dcefb3b7ba | ||
|
|
8c7bbb9a79 | ||
|
|
53a95c6022 | ||
|
|
2b900253d0 | ||
|
|
e77ae06bea | ||
|
|
3f2f514097 | ||
|
|
297a52aed8 | ||
|
|
ca1a4c40a5 | ||
|
|
cab6b2e804 | ||
|
|
95670fc3d9 | ||
|
|
a31ed6e510 | ||
|
|
8b46a5168f | ||
|
|
ea63cf7b40 | ||
|
|
cd234db299 | ||
|
|
31edc0dbf8 | ||
|
|
ccc09419fb | ||
|
|
9a408769c5 | ||
|
|
a25f7d20c8 | ||
|
|
1079680513 | ||
|
|
d078035394 | ||
|
|
5853ce4fd3 | ||
|
|
a5fdbaf74a | ||
|
|
429e46b7b7 | ||
|
|
78ea2f0f54 | ||
|
|
033a8b144a | ||
|
|
31d56f80fa | ||
|
|
773e57dd76 | ||
|
|
ad9902bc9a | ||
|
|
f38cd24fae | ||
|
|
8f7e117438 | ||
|
|
5ba1e70e39 | ||
|
|
53191bc23b | ||
|
|
e8d67322b0 | ||
|
|
8de0cbaa09 | ||
|
|
59407ee01d | ||
|
|
3566d6b50d | ||
|
|
17aff8ec6d | ||
|
|
45d9b85abf | ||
|
|
5f99de36ba | ||
|
|
8739ab2421 | ||
|
|
f97e3a3780 | ||
|
|
fa6220649f | ||
|
|
6ce48b640a | ||
|
|
84ec724d4f | ||
|
|
d5d77c222e | ||
|
|
4edc920912 | ||
|
|
ff64920b7b | ||
|
|
6a4cab9405 | ||
|
|
0b6618c661 | ||
|
|
94362f0947 | ||
|
|
c95f2d17ff | ||
|
|
8c94e126c3 | ||
|
|
937e9dac1f | ||
|
|
e1cce7b5b3 | ||
|
|
e99e307790 | ||
|
|
7a6145342d | ||
|
|
0db8421caf | ||
|
|
cc3b783ab1 | ||
|
|
7f07c7636c | ||
|
|
41a5fe0aa9 | ||
|
|
c0833d4bb1 | ||
|
|
51bb896f91 | ||
|
|
40db30ce5a | ||
|
|
4803fe9e3f | ||
|
|
edd8a34b14 | ||
|
|
29ad70fa16 | ||
|
|
0c67290f74 | ||
|
|
aef091e205 | ||
|
|
4ce081d6ed | ||
|
|
6155236a4c | ||
|
|
4ad7cfb757 | ||
|
|
6cd81962b3 | ||
|
|
eed614fd67 | ||
|
|
85227bd31f | ||
|
|
da4a66850d | ||
|
|
a839925041 | ||
|
|
16e2f3204d | ||
|
|
70286ed9b8 | ||
|
|
59707b77d2 | ||
|
|
63b4adaca8 | ||
|
|
ae7a2de19d | ||
|
|
2d0007de52 | ||
|
|
e9ad30dc29 | ||
|
|
bfd8be6abe | ||
|
|
ed7387beb3 | ||
|
|
7d382aade9 | ||
|
|
e09e5a0168 | ||
|
|
bbf0317775 | ||
|
|
aa03dac34d | ||
|
|
062a9234ee | ||
|
|
695ba5a758 | ||
|
|
f049904466 | ||
|
|
d001ab8d0a | ||
|
|
d488954548 | ||
|
|
bf2957e75b | ||
|
|
2f982435f9 | ||
|
|
95a25836a0 | ||
|
|
fb976f1cb9 | ||
|
|
30a9f60830 | ||
|
|
37cccc352b | ||
|
|
52f074ce46 | ||
|
|
94b71fdc4e | ||
|
|
7986bab3a7 | ||
|
|
a98426e22a | ||
|
|
3192851556 | ||
|
|
3bee6d8338 | ||
|
|
ea7478eb27 | ||
|
|
4eed312c3d | ||
|
|
aefc4535e1 | ||
|
|
8f920080d1 | ||
|
|
7d904ccdfa | ||
|
|
12074f63d5 | ||
|
|
3b26581af5 | ||
|
|
de6defa1ff | ||
|
|
cccf65981a | ||
|
|
315567a79c | ||
|
|
bd1a1f910d | ||
|
|
6527b24081 | ||
|
|
992f15b082 | ||
|
|
6e898b8c45 | ||
|
|
b3c17b58c9 | ||
|
|
9c9c6d9976 | ||
|
|
c1af0f1b51 | ||
|
|
5e3699b64d | ||
|
|
1fa9aee3f0 | ||
|
|
d79843c54b | ||
|
|
3077fb9b35 | ||
|
|
7839602bcc | ||
|
|
b10e88c304 | ||
|
|
2aa45fe15a | ||
|
|
257cec9f41 | ||
|
|
e14075ad8d | ||
|
|
1742f62cd0 | ||
|
|
22d5da9f0d | ||
|
|
07212aa130 | ||
|
|
e95f544948 | ||
|
|
feeb3e6d50 | ||
|
|
c6205a337c | ||
|
|
15d76c18a0 | ||
|
|
078afe4b9d | ||
|
|
dc13746841 | ||
|
|
45ce7ef84b | ||
|
|
64bb5e2d16 | ||
|
|
9b17ec96c5 | ||
|
|
e21f68fd7c | ||
|
|
9a390fd7a4 | ||
|
|
1de0c7e139 | ||
|
|
d123bb5c19 | ||
|
|
798c323a82 | ||
|
|
aac3f47f6c | ||
|
|
6f0825c321 | ||
|
|
6138e248cb | ||
|
|
868f3e5b9d | ||
|
|
0d7903fc06 | ||
|
|
72b8b19f52 | ||
|
|
23c138dc32 | ||
|
|
e0fb34e876 | ||
|
|
4f5141760a | ||
|
|
6a0f8978b7 | ||
|
|
a7e4f30a8a | ||
|
|
18581fea34 | ||
|
|
aaa9224c7c | ||
|
|
77980dbb4d | ||
|
|
130661f144 | ||
|
|
f26a3542b9 | ||
|
|
32a5868894 | ||
|
|
0a930a4f86 | ||
|
|
c59228e1fd | ||
|
|
8a2a562235 | ||
|
|
fbf8142ea0 | ||
|
|
a05b030862 | ||
|
|
725b52579b | ||
|
|
19c47cdf7b | ||
|
|
774a6c6723 | ||
|
|
ddfe0e26b2 | ||
|
|
5feb656e9a | ||
|
|
39400d3149 | ||
|
|
803ac58f4d | ||
|
|
c4dd8488fe | ||
|
|
6dda8dc410 | ||
|
|
b4d03e7212 | ||
|
|
c792e1cc11 | ||
|
|
d10be1676e | ||
|
|
b94957a952 | ||
|
|
6f5722aa02 | ||
|
|
4bf43a438b | ||
|
|
b372571648 | ||
|
|
b5d98e5e8a | ||
|
|
7e5ff7f75f | ||
|
|
099d96bcca | ||
|
|
4ba9c65f73 | ||
|
|
be01370ab2 | ||
|
|
4ddb8f49bb | ||
|
|
4576da4551 | ||
|
|
269814945d | ||
|
|
69549b7152 | ||
|
|
8f16931502 | ||
|
|
a95250cf9a | ||
|
|
2adfd0afbd | ||
|
|
3ab6adf700 | ||
|
|
7c59758f5f | ||
|
|
63d7ef0fa1 | ||
|
|
68d2f45236 | ||
|
|
3dd384c5c6 | ||
|
|
c5da2c7c99 | ||
|
|
1fd1b4e09d | ||
|
|
0d9cd9c6b8 | ||
|
|
09f403aa07 | ||
|
|
3d7f233e27 | ||
|
|
db23b86dca | ||
|
|
09bc8f26fb | ||
|
|
a58e6fb76d | ||
|
|
7723716e18 | ||
|
|
29280e9f8d | ||
|
|
e7e033715e | ||
|
|
4c22381675 | ||
|
|
e809fac364 | ||
|
|
bf95404920 | ||
|
|
4197beea3c | ||
|
|
10bfe8ad2f | ||
|
|
58cbeb3ba0 | ||
|
|
8b15dbcda5 | ||
|
|
595af32e54 | ||
|
|
c6c774b1e3 | ||
|
|
5f43128a80 | ||
|
|
0eb47fd7b4 | ||
|
|
0d1b7984fc | ||
|
|
d612f83446 | ||
|
|
8d7a0903fd | ||
|
|
41d6da8008 | ||
|
|
6ac9f4e239 | ||
|
|
1f1a0ebb3d | ||
|
|
623acd9e2c | ||
|
|
7a9dfa850d | ||
|
|
d2e08d818b | ||
|
|
cc0dde106a | ||
|
|
c6fce8592a | ||
|
|
2163fef175 | ||
|
|
05bea59ef1 | ||
|
|
63fb96a0d2 | ||
|
|
c15cb9a378 | ||
|
|
961983d1fe | ||
|
|
aeeef26614 | ||
|
|
efcef1cab4 | ||
|
|
f45351841c | ||
|
|
d88ab085b5 | ||
|
|
363ada8211 | ||
|
|
412e6ff91a | ||
|
|
19887643bc | ||
|
|
a7b378b17d | ||
|
|
8d2b5b9832 | ||
|
|
0d00678a7c | ||
|
|
63014726e9 | ||
|
|
2029005c78 | ||
|
|
22e4481a2b | ||
|
|
50e31f38bb | ||
|
|
2cc0173873 | ||
|
|
681f7974d6 | ||
|
|
a54e53038a | ||
|
|
17bb771020 | ||
|
|
c3ea0bc592 | ||
|
|
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 @@
|
|||||||
|
github: objz
|
||||||
@@ -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,8 @@
|
|||||||
|
- name: install JDK
|
||||||
|
uses: actions/setup-java@v5
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: "21"
|
||||||
|
- name: install Linux build dependencies
|
||||||
|
if: runner.os == 'Linux'
|
||||||
|
run: sudo apt-get update && sudo apt-get install --yes libxcb1-dev
|
||||||
@@ -0,0 +1,381 @@
|
|||||||
|
# Based on cargo-dist's generated GitHub workflow.
|
||||||
|
|
||||||
|
name: build release
|
||||||
|
permissions:
|
||||||
|
"contents": "write"
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
tag:
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
plan:
|
||||||
|
runs-on: "ubuntu-22.04"
|
||||||
|
outputs:
|
||||||
|
val: ${{ steps.plan.outputs.manifest }}
|
||||||
|
tag: ${{ inputs.tag }}
|
||||||
|
tag-flag: ${{ format('--tag={0}', inputs.tag) }}
|
||||||
|
publishing: true
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
ref: ${{ inputs.tag }}
|
||||||
|
persist-credentials: false
|
||||||
|
submodules: recursive
|
||||||
|
- name: Install dist
|
||||||
|
# we specify bash to get pipefail; it guards against the `curl` command
|
||||||
|
# failing. otherwise `sh` won't catch that `curl` returned non-0
|
||||||
|
shell: bash
|
||||||
|
run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.31.0/cargo-dist-installer.sh | sh"
|
||||||
|
- name: Cache dist
|
||||||
|
uses: actions/upload-artifact@v6
|
||||||
|
with:
|
||||||
|
name: cargo-dist-cache
|
||||||
|
path: ~/.cargo/bin/dist
|
||||||
|
- id: plan
|
||||||
|
run: |
|
||||||
|
dist host --steps=create --tag=${{ inputs.tag }} --output-format=json > plan-dist-manifest.json
|
||||||
|
echo "dist ran successfully"
|
||||||
|
cat plan-dist-manifest.json
|
||||||
|
echo "manifest=$(jq -c "." plan-dist-manifest.json)" >> "$GITHUB_OUTPUT"
|
||||||
|
- name: "Upload dist-manifest.json"
|
||||||
|
uses: actions/upload-artifact@v6
|
||||||
|
with:
|
||||||
|
name: artifacts-plan-dist-manifest
|
||||||
|
path: plan-dist-manifest.json
|
||||||
|
|
||||||
|
build-local-artifacts:
|
||||||
|
name: build-local-artifacts (${{ join(matrix.targets, ', ') }})
|
||||||
|
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
|
||||||
|
matrix: ${{ fromJson(needs.plan.outputs.val || '{"ci":{"github":{"artifacts_matrix":{"include":[]}}}}').ci.github.artifacts_matrix }}
|
||||||
|
runs-on: ${{ matrix.runner }}
|
||||||
|
container: ${{ matrix.container && matrix.container.image || null }}
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
CURSEFORGE_API_KEY: ${{ secrets.CURSEFORGE_API_KEY }}
|
||||||
|
BUILD_MANIFEST_NAME: target/distrib/${{ join(matrix.targets, '-') }}-dist-manifest.json
|
||||||
|
steps:
|
||||||
|
- name: enable windows longpaths
|
||||||
|
run: |
|
||||||
|
git config --global core.longpaths true
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
ref: ${{ inputs.tag }}
|
||||||
|
persist-credentials: false
|
||||||
|
submodules: recursive
|
||||||
|
- name: Install Rust non-interactively if not already installed
|
||||||
|
if: ${{ matrix.container }}
|
||||||
|
run: |
|
||||||
|
if ! command -v cargo > /dev/null 2>&1; then
|
||||||
|
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
|
||||||
|
echo "$HOME/.cargo/bin" >> $GITHUB_PATH
|
||||||
|
fi
|
||||||
|
- name: "install JDK"
|
||||||
|
uses: "actions/setup-java@v5"
|
||||||
|
with:
|
||||||
|
"distribution": "temurin"
|
||||||
|
"java-version": "21"
|
||||||
|
- name: install Linux build dependencies
|
||||||
|
if: runner.os == 'Linux'
|
||||||
|
run: sudo apt-get update && sudo apt-get install --yes libxcb1-dev
|
||||||
|
- name: Install dist
|
||||||
|
run: ${{ matrix.install_dist.run }}
|
||||||
|
- 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: |
|
||||||
|
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: |
|
||||||
|
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-global-artifacts:
|
||||||
|
needs:
|
||||||
|
- plan
|
||||||
|
- build-local-artifacts
|
||||||
|
runs-on: "ubuntu-22.04"
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
BUILD_MANIFEST_NAME: target/distrib/global-dist-manifest.json
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
ref: ${{ inputs.tag }}
|
||||||
|
persist-credentials: false
|
||||||
|
submodules: recursive
|
||||||
|
- name: Install cached dist
|
||||||
|
uses: actions/download-artifact@v7
|
||||||
|
with:
|
||||||
|
name: cargo-dist-cache
|
||||||
|
path: ~/.cargo/bin/
|
||||||
|
- run: chmod +x ~/.cargo/bin/dist
|
||||||
|
- 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"
|
||||||
|
|
||||||
|
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 }}
|
||||||
|
host:
|
||||||
|
needs:
|
||||||
|
- plan
|
||||||
|
- build-local-artifacts
|
||||||
|
- build-global-artifacts
|
||||||
|
if: ${{ always() && needs.plan.result == 'success' && needs.plan.outputs.publishing == 'true' && (needs.build-global-artifacts.result == 'skipped' || needs.build-global-artifacts.result == 'success') && (needs.build-local-artifacts.result == 'skipped' || needs.build-local-artifacts.result == 'success') }}
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
runs-on: "ubuntu-22.04"
|
||||||
|
outputs:
|
||||||
|
val: ${{ steps.host.outputs.manifest }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
ref: ${{ inputs.tag }}
|
||||||
|
persist-credentials: false
|
||||||
|
submodules: recursive
|
||||||
|
fetch-depth: 0
|
||||||
|
fetch-tags: true
|
||||||
|
- name: Install cached dist
|
||||||
|
uses: actions/download-artifact@v7
|
||||||
|
with:
|
||||||
|
name: cargo-dist-cache
|
||||||
|
path: ~/.cargo/bin/
|
||||||
|
- run: chmod +x ~/.cargo/bin/dist
|
||||||
|
- 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:
|
||||||
|
name: artifacts-dist-manifest
|
||||||
|
path: dist-manifest.json
|
||||||
|
- 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 }}"
|
||||||
|
CHANGELOG: "${{ steps.changelog.outputs.content }}"
|
||||||
|
RELEASE_TAG: "${{ needs.plan.outputs.tag }}"
|
||||||
|
APP_VERSION: "${{ fromJson(steps.host.outputs.manifest).releases[0].app_version }}"
|
||||||
|
PUBLISH_WINGET: "${{ !fromJson(needs.plan.outputs.val).announcement_is_prerelease || fromJson(needs.plan.outputs.val).publish_prereleases }}"
|
||||||
|
run: |
|
||||||
|
RELEASE_COMMIT="$(git rev-parse HEAD)"
|
||||||
|
echo "$CHANGELOG" > $RUNNER_TEMP/notes.txt
|
||||||
|
WINGET_MANIFEST_NOTE=""
|
||||||
|
if [[ "$PUBLISH_WINGET" == true ]]; then
|
||||||
|
WINGET_MANIFEST_NOTE="The generated WinGet manifest is attached as \`winget-manifest-${APP_VERSION}.zip\` for local validation."
|
||||||
|
fi
|
||||||
|
cat >> $RUNNER_TEMP/notes.txt <<EOF
|
||||||
|
|
||||||
|
## downloads
|
||||||
|
|
||||||
|
| File | Platform | Checksum |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| [rmcl-aarch64-apple-darwin.tar.xz](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-aarch64-apple-darwin.tar.xz) | Apple Silicon macOS | [checksum](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-aarch64-apple-darwin.tar.xz.sha256) |
|
||||||
|
| [rmcl-x86_64-apple-darwin.tar.xz](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-apple-darwin.tar.xz) | Intel macOS | [checksum](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-apple-darwin.tar.xz.sha256) |
|
||||||
|
| [rmcl-x86_64-pc-windows-msvc.zip](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-pc-windows-msvc.zip) | x64 Windows | [checksum](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-pc-windows-msvc.zip.sha256) |
|
||||||
|
| [rmcl-x86_64-pc-windows-msvc.msi](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-pc-windows-msvc.msi) | x64 Windows | [checksum](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-pc-windows-msvc.msi.sha256) |
|
||||||
|
| [rmcl-aarch64-unknown-linux-gnu.tar.xz](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-aarch64-unknown-linux-gnu.tar.xz) | ARM64 Linux | [checksum](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-aarch64-unknown-linux-gnu.tar.xz.sha256) |
|
||||||
|
| [rmcl-x86_64-unknown-linux-gnu.tar.xz](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-unknown-linux-gnu.tar.xz) | x64 Linux | [checksum](https://github.com/objz/rmcl/releases/download/${RELEASE_TAG}/rmcl-x86_64-unknown-linux-gnu.tar.xz.sha256) |
|
||||||
|
|
||||||
|
## installation
|
||||||
|
|
||||||
|
release archives and installers are attached above. package-manager releases can take a little longer to become available.
|
||||||
|
|
||||||
|
### Cargo
|
||||||
|
|
||||||
|
\`\`\`
|
||||||
|
cargo install rmcl
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### Homebrew
|
||||||
|
|
||||||
|
\`\`\`
|
||||||
|
brew install objz/tap/rmcl
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
### WinGet
|
||||||
|
|
||||||
|
\`\`\`
|
||||||
|
winget install Objz.Rmcl
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
$WINGET_MANIFEST_NOTE
|
||||||
|
|
||||||
|
### 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 }}
|
||||||
|
- 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
|
||||||
|
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
|
||||||
|
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
|
||||||
|
permissions:
|
||||||
|
"contents": "write"
|
||||||
+8
-107
@@ -1,116 +1,17 @@
|
|||||||
name: build
|
name: ci
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [master]
|
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [master]
|
branches: [master]
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ci-${{ github.ref }}
|
||||||
|
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
checks:
|
||||||
strategy:
|
uses: ./.github/workflows/checks.yml
|
||||||
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 }}
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: install Rust
|
|
||||||
uses: dtolnay/rust-toolchain@stable
|
|
||||||
with:
|
|
||||||
targets: ${{ matrix.target }}
|
|
||||||
|
|
||||||
- uses: Swatinem/rust-cache@v2
|
|
||||||
with:
|
|
||||||
key: ${{ matrix.target }}
|
|
||||||
|
|
||||||
- name: install cross-compilation deps (aarch64-linux)
|
|
||||||
if: matrix.target == 'aarch64-unknown-linux-gnu'
|
|
||||||
run: |
|
|
||||||
sudo apt-get update
|
|
||||||
sudo apt-get install -y gcc-aarch64-linux-gnu g++-aarch64-linux-gnu
|
|
||||||
|
|
||||||
- name: build
|
|
||||||
env:
|
|
||||||
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
|
|
||||||
run: cargo build --release --target ${{ matrix.target }}
|
|
||||||
|
|
||||||
- name: package (unix)
|
|
||||||
if: runner.os != 'Windows'
|
|
||||||
run: |
|
|
||||||
cd target/${{ matrix.target }}/release
|
|
||||||
tar czf ../../../mcl-${{ matrix.target }}.tar.gz ${{ matrix.artifact }}
|
|
||||||
|
|
||||||
- name: package (windows)
|
|
||||||
if: runner.os == 'Windows'
|
|
||||||
run: |
|
|
||||||
cd target/${{ matrix.target }}/release
|
|
||||||
Compress-Archive -Path ${{ matrix.artifact }} -DestinationPath ../../../mcl-${{ matrix.target }}.zip
|
|
||||||
|
|
||||||
- name: upload artifact
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
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,81 @@
|
|||||||
|
name: checks
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
network-tests:
|
||||||
|
type: boolean
|
||||||
|
default: false
|
||||||
|
ref:
|
||||||
|
type: string
|
||||||
|
default: ""
|
||||||
|
secrets:
|
||||||
|
curseforge-api-key:
|
||||||
|
required: false
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
env:
|
||||||
|
CARGO_TERM_COLOR: always
|
||||||
|
RUST_BACKTRACE: 1
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
format:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
ref: ${{ inputs.ref || github.sha }}
|
||||||
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
|
with:
|
||||||
|
components: rustfmt
|
||||||
|
- run: cargo fmt --all -- --check
|
||||||
|
|
||||||
|
build-and-test:
|
||||||
|
name: build and test (${{ matrix.os }})
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
ref: ${{ inputs.ref || github.sha }}
|
||||||
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
|
with:
|
||||||
|
components: clippy
|
||||||
|
- uses: actions/setup-java@v5
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: "21"
|
||||||
|
- uses: Swatinem/rust-cache@v2
|
||||||
|
with:
|
||||||
|
key: ${{ matrix.os }}
|
||||||
|
- name: install Linux build dependencies
|
||||||
|
if: runner.os == 'Linux'
|
||||||
|
run: sudo apt-get update && sudo apt-get install --yes libxcb1-dev
|
||||||
|
- run: cargo build --locked
|
||||||
|
- run: cargo clippy --all-targets --locked -- -D warnings
|
||||||
|
- run: cargo test --locked --all-targets
|
||||||
|
|
||||||
|
network-tests:
|
||||||
|
if: inputs.network-tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
env:
|
||||||
|
CURSEFORGE_API_KEY: ${{ secrets.curseforge-api-key }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
ref: ${{ inputs.ref || github.sha }}
|
||||||
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
|
- uses: actions/setup-java@v5
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: "21"
|
||||||
|
- uses: Swatinem/rust-cache@v2
|
||||||
|
- name: install Linux build dependencies
|
||||||
|
run: sudo apt-get update && sudo apt-get install --yes libxcb1-dev
|
||||||
|
- run: cargo test --locked --all-targets -- --ignored
|
||||||
@@ -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,49 @@
|
|||||||
|
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: install Linux build dependencies
|
||||||
|
run: sudo apt-get update && sudo apt-get install --yes libxcb1-dev
|
||||||
|
|
||||||
|
- name: publish to crates.io
|
||||||
|
run: |
|
||||||
|
if [ "${{ inputs.dry_run }}" = "true" ]; then
|
||||||
|
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,74 @@
|
|||||||
|
name: release
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: release
|
||||||
|
cancel-in-progress: false
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
resolve:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
outputs:
|
||||||
|
sha: ${{ steps.checkout.outputs.commit }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
id: checkout
|
||||||
|
with:
|
||||||
|
ref: master
|
||||||
|
|
||||||
|
checks:
|
||||||
|
needs: resolve
|
||||||
|
uses: ./.github/workflows/checks.yml
|
||||||
|
with:
|
||||||
|
network-tests: true
|
||||||
|
ref: ${{ needs.resolve.outputs.sha }}
|
||||||
|
secrets:
|
||||||
|
curseforge-api-key: ${{ secrets.CURSEFORGE_API_KEY }}
|
||||||
|
|
||||||
|
prepare:
|
||||||
|
needs: [resolve, checks]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
outputs:
|
||||||
|
release: ${{ steps.version.outputs.release }}
|
||||||
|
tag: ${{ steps.version.outputs.tag }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
ref: ${{ needs.resolve.outputs.sha }}
|
||||||
|
fetch-depth: 0
|
||||||
|
fetch-tags: true
|
||||||
|
|
||||||
|
- name: check version
|
||||||
|
id: version
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
version=$(cargo metadata --no-deps --format-version 1 | jq -r '.packages[] | select(.name == "rmcl") | .version')
|
||||||
|
python3 scripts/release-version.py --check
|
||||||
|
python3 scripts/release-version.py "$version"
|
||||||
|
|
||||||
|
- name: create tag
|
||||||
|
if: steps.version.outputs.release == 'true'
|
||||||
|
env:
|
||||||
|
TAG: ${{ steps.version.outputs.tag }}
|
||||||
|
run: |
|
||||||
|
git config user.name github-actions[bot]
|
||||||
|
git config user.email 41898282+github-actions[bot]@users.noreply.github.com
|
||||||
|
git tag --annotate "$TAG" --message "Release $TAG"
|
||||||
|
git push origin "$TAG"
|
||||||
|
|
||||||
|
publish:
|
||||||
|
needs: prepare
|
||||||
|
if: needs.prepare.outputs.release == 'true'
|
||||||
|
uses: ./.github/workflows/build-release.yml
|
||||||
|
with:
|
||||||
|
tag: ${{ needs.prepare.outputs.tag }}
|
||||||
|
secrets: inherit
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
@@ -1,2 +1,6 @@
|
|||||||
/target
|
/target
|
||||||
|
/scripts
|
||||||
*.log
|
*.log
|
||||||
|
result
|
||||||
|
result-*
|
||||||
|
.direnv
|
||||||
@@ -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,99 @@
|
|||||||
|
# Contributing to rmcl
|
||||||
|
|
||||||
|
Bug reports, fixes, documentation, and themes are welcome. For a larger feature or
|
||||||
|
architectural change, open an issue first so we can agree on the approach before
|
||||||
|
you spend time implementing it.
|
||||||
|
|
||||||
|
## Reporting bugs
|
||||||
|
|
||||||
|
Search the [existing issues](https://github.com/objz/rmcl/issues) before opening a
|
||||||
|
new one. Include your rmcl version, operating system, steps to reproduce, and what
|
||||||
|
you expected to happen. For game-launch problems, include the Minecraft version
|
||||||
|
and mod loader; for TUI problems, include your terminal and a screenshot if useful.
|
||||||
|
|
||||||
|
Relevant logs help, but remove tokens, account details, and other private
|
||||||
|
information before posting them. See the [README](README.md#logs) for log locations.
|
||||||
|
|
||||||
|
## Development setup
|
||||||
|
|
||||||
|
You need a stable Rust toolchain and a JDK with `javac` and `jar` on `PATH`.
|
||||||
|
CI uses JDK 21. On Linux, install the libxcb development package (`libxcb1-dev` on
|
||||||
|
Debian/Ubuntu, `libxcb` on Arch).
|
||||||
|
|
||||||
|
Fork the repository and create a branch for your change. The
|
||||||
|
[source build instructions](README.md#from-source) cover cloning and building.
|
||||||
|
Run the development version with `cargo run --locked`, or use
|
||||||
|
`cargo run --locked -- --help` to see the CLI commands.
|
||||||
|
|
||||||
|
The main parts of the codebase are:
|
||||||
|
|
||||||
|
- `src/cli/`: command-line commands and output.
|
||||||
|
- `src/config/`: settings, paths, and themes.
|
||||||
|
- `src/instance/`: instance management, content, modpack imports, loaders, and launches.
|
||||||
|
- `src/net/`: HTTP requests, downloads, and service API clients.
|
||||||
|
- `src/tui/`: the terminal interface.
|
||||||
|
- `tests/`: integration tests; unit tests are under `src/`.
|
||||||
|
|
||||||
|
## Making changes
|
||||||
|
|
||||||
|
Keep each pull request focused on one fix or feature. Follow the style of nearby
|
||||||
|
code and reuse existing helpers where they fit. Keep public APIs and new
|
||||||
|
dependencies limited to what the change needs.
|
||||||
|
|
||||||
|
Comments should explain a decision, constraint, or non-obvious behavior. There is
|
||||||
|
no need to describe what a clearly named function already does. Keep modules
|
||||||
|
organized by responsibility without splitting files just to meet a size target.
|
||||||
|
|
||||||
|
For a bug fix, add a regression test that fails without the fix. For new behavior,
|
||||||
|
cover the cases that could break. Use test names that describe the scenario and
|
||||||
|
avoid repeating coverage unless the inputs exercise different behavior.
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Run the same checks as CI before submitting code changes:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo fmt --all -- --check
|
||||||
|
cargo build --locked
|
||||||
|
cargo clippy --all-targets --locked -- -D warnings
|
||||||
|
cargo test --locked --all-targets
|
||||||
|
```
|
||||||
|
|
||||||
|
Live-service tests are ignored by default. If you run them, note that in the PR,
|
||||||
|
along with any failures caused by network access or provider credentials.
|
||||||
|
|
||||||
|
Check visual and input changes in a real terminal as well as the automated TUI
|
||||||
|
tests. CI covers Linux, macOS, and Windows; say which platforms you tested locally
|
||||||
|
and mention anything you could not verify.
|
||||||
|
|
||||||
|
## Pull requests
|
||||||
|
|
||||||
|
Open your PR against `master`. Explain the problem, summarize the change, link any
|
||||||
|
related issue, and list the checks you ran. Screenshots or a short recording are
|
||||||
|
useful for visible TUI changes. Use descriptive commit messages and keep unrelated
|
||||||
|
changes in separate commits or PRs.
|
||||||
|
|
||||||
|
Be available to answer review questions and make follow-up changes. Passing CI
|
||||||
|
is required before merging, but maintainers may still request changes to the
|
||||||
|
implementation or scope.
|
||||||
|
|
||||||
|
## AI and LLM assistance
|
||||||
|
|
||||||
|
AI-assisted contributions are welcome. You are responsible for the code, tests,
|
||||||
|
and documentation you submit, including anything generated by a tool. Review the
|
||||||
|
changes yourself, verify the behavior, and be prepared to explain the implementation.
|
||||||
|
|
||||||
|
If an LLM helped produce your contribution, disclose it in the PR description.
|
||||||
|
Name the tool or model, describe which parts it helped with, and say how you
|
||||||
|
reviewed and tested the result. A short note is enough, for example:
|
||||||
|
|
||||||
|
> AI assistance: ChatGPT helped draft the tests. I reviewed the assertions and ran
|
||||||
|
> the relevant tests locally.
|
||||||
|
|
||||||
|
Use your own words in issue reports, PR summaries, and review replies. Maintainers
|
||||||
|
may close contributions that have not been reviewed or that the author cannot explain.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Contributions are covered by the project's [GPL-3.0-only license](LICENSE).
|
||||||
|
Only submit code and assets you have the right to contribute under those terms.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
Copyright (C) 2026 Constantin Bauer
|
||||||
|
|
||||||
|
Unless otherwise stated, the source code in this repository is
|
||||||
|
copyrighted by Constantin Bauer and licensed under the GNU General Public
|
||||||
|
License v3.0. See LICENSE for the full license text.
|
||||||
Generated
+1890
-184
File diff suppressed because it is too large.
Load diff
+56
-9
@@ -1,46 +1,87 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "mcl"
|
name = "rmcl"
|
||||||
version = "0.1.0"
|
version = "0.6.0"
|
||||||
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"
|
||||||
|
include = ["pkg/wix/main.wxs"]
|
||||||
|
license = false
|
||||||
|
eula = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "rmcl"
|
||||||
|
path = "src/main.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
async-trait = "0.1"
|
async-trait = "0.1"
|
||||||
|
base64 = "0.22"
|
||||||
chrono = { version = "0.4.39", features = ["serde"] }
|
chrono = { version = "0.4.39", features = ["serde"] }
|
||||||
clap = "4.5.27"
|
clap = "4.5.27"
|
||||||
color-eyre = "0.6.3"
|
color-eyre = "0.6.3"
|
||||||
config = "0.15.6"
|
config = "0.15.6"
|
||||||
crossterm = "0.29.0"
|
crossterm = "0.29.0"
|
||||||
dirs-next = "2.0.0"
|
display-info = "0.5.9"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
ratatui = { version = "0.30.0", features = ["serde"] }
|
ratatui = { version = "0.30.0", features = ["serde", "unstable-rendered-line-info"] }
|
||||||
ratatui-themekit = { version = "0.6", features = ["serde"] }
|
ratatui-themekit = { version = "0.6", features = ["serde"] }
|
||||||
ratatui-textarea = { version = "0.9.1", features = ["crossterm"] }
|
ratatui-textarea = { version = "0.9.1", features = ["crossterm"] }
|
||||||
|
tui-markdown = { version = "0.3.7", default-features = false }
|
||||||
|
pulldown-cmark = { version = "0.13.4", default-features = false }
|
||||||
|
html-to-markdown-rs = { version = "3.9.0", features = ["visitor"] }
|
||||||
|
resvg = "0.47"
|
||||||
reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls"] }
|
reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls"] }
|
||||||
serde = { version = "1.0.217", features = ["derive"] }
|
serde = { version = "1.0.217", features = ["derive"] }
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
|
sha1 = "0.10"
|
||||||
|
sha2 = "0.10"
|
||||||
toml = "1.1.2"
|
toml = "1.1.2"
|
||||||
|
toml_edit = "0.25"
|
||||||
tachyonfx = "0.25"
|
tachyonfx = "0.25"
|
||||||
throbber-widgets-tui = "0.11"
|
throbber-widgets-tui = "0.11"
|
||||||
thiserror = "2"
|
thiserror = "2"
|
||||||
tokio = { version = "1", features = ["full"] }
|
tokio = { version = "1", features = ["full", "test-util"] }
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
tracing-appender = "0.2"
|
tracing-appender = "0.2"
|
||||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
|
unicode-segmentation = "1"
|
||||||
tui-popup = "0.7"
|
tui-popup = "0.7"
|
||||||
tui-prompts = "0.6"
|
tui-prompts = "0.6"
|
||||||
tui-logger = { version = "0.18", features = ["tracing-support"] }
|
tui-logger = { version = "0.18", features = ["tracing-support"] }
|
||||||
tui-scrollview = "0.6"
|
tui-scrollview = "0.6"
|
||||||
tui-widget-list = "0.15"
|
tui-widget-list = "0.15"
|
||||||
ratatui-image = { version = "10.0.6", default-features = false, features = ["crossterm"] }
|
ratatui-image = { version = "11.0.6", default-features = false, features = ["crossterm"] }
|
||||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
image = { version = "0.25", default-features = false, features = ["gif", "jpeg", "png", "webp"] }
|
||||||
zip = "8.5.1"
|
zip = "8.5.1"
|
||||||
minecraft-msa-auth = "0.4.0"
|
minecraft-msa-auth = "0.4.0"
|
||||||
oauth2 = "5.0.0"
|
oauth2 = "5.0.0"
|
||||||
open = "5"
|
open = { version = "5", features = ["shellexecute-on-windows"] }
|
||||||
which = "8.0.2"
|
which = "8.0.2"
|
||||||
dirs = "6.0.0"
|
dirs = "6.0.0"
|
||||||
|
notify = "8"
|
||||||
|
regex = "1"
|
||||||
|
fast-strip-ansi = "0.13"
|
||||||
|
libcasr = "2.13"
|
||||||
|
fs2 = "0.4"
|
||||||
|
fastnbt = "2.6.2"
|
||||||
|
flate2 = "1.1.9"
|
||||||
|
tempfile = "3"
|
||||||
|
|
||||||
|
[target.'cfg(unix)'.dependencies]
|
||||||
|
libc = "0.2"
|
||||||
|
shlex = "1.3"
|
||||||
|
|
||||||
|
[target.'cfg(windows)'.dependencies]
|
||||||
|
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_System_Diagnostics_ToolHelp", "Win32_UI_Shell"] }
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
codegen-units = 1
|
codegen-units = 1
|
||||||
@@ -48,5 +89,11 @@ lto = true
|
|||||||
opt-level = "s"
|
opt-level = "s"
|
||||||
strip = true
|
strip = true
|
||||||
|
|
||||||
|
[profile.dist]
|
||||||
|
inherits = "release"
|
||||||
|
lto = "thin"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile = "3"
|
insta = "1"
|
||||||
|
wiremock = "0.6"
|
||||||
|
rstest = "0.23"
|
||||||
@@ -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,14 @@
|
|||||||
[![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,110 +23,283 @@
|
|||||||
|
|
||||||
## 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.
|
||||||
|
|
||||||
it does everything you'd expect from a launcher. multiple instances, mod loaders, modpack imports, Microsoft auth, content management, launching. all from a TUI or from the command line. the TUI is the main thing though, the CLI is there for scripting and automation.
|
it does everything you'd expect from a launcher.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
## features
|
## features
|
||||||
|
| Mod Loader | Supported |
|
||||||
|
|------------|-----------|
|
||||||
|
| Vanilla | ✅ |
|
||||||
|
| Fabric | ✅ |
|
||||||
|
| Forge | ✅ |
|
||||||
|
| NeoForge | ✅ |
|
||||||
|
| Quilt | ✅ |
|
||||||
|
| LiteLoader | ❌ |
|
||||||
|
| Rift | ❌ |
|
||||||
|
|
||||||
| | |
|
|
||||||
|---|---|
|
### modpacks and accounts
|
||||||
| **instances** | create and manage multiple instances, each with their own version, loader, mods, and settings |
|
|
||||||
| **mod loaders** | vanilla, Fabric, Quilt, Forge, NeoForge. more might show up later |
|
Browse Modrinth and CurseForge modpacks or import Modrinth, CurseForge, and MultiMC/Prism archives (including GTNH packs in that format). Direct imports accept a local archive, Modrinth URL, or Modrinth project slug. CurseForge requires a build-time [API key](#curseforge-api). Multiple Microsoft accounts and offline accounts are supported.
|
||||||
| **content** | browse and toggle mods, shaders, resource packs. view worlds, screenshots, and logs |
|
|
||||||
| **modpack import** | import from Modrinth via `.mrpack` file, URL, or slug |
|
|
||||||
| **accounts** | multiple Microsoft accounts and offline players, switch between them |
|
|
||||||
| **launching** | launch directly from the TUI or generate a desktop shortcut for any instance |
|
|
||||||
| **desktop shortcuts** | click it and Minecraft starts, no need to open mcl or type anything |
|
|
||||||
| **CLI** | every feature the TUI has is also available as a subcommand |
|
|
||||||
| **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.
|
||||||
|
|
||||||
|
## CurseForge API
|
||||||
|
|
||||||
|
Git, source, and Cargo builds use rmcl's dedicated API key unless `CURSEFORGE_API_KEY` is set at compile time. An empty or whitespace-only override disables CurseForge.
|
||||||
|
Use of the API is subject to the [CurseForge 3rd Party API Terms and Conditions](https://support.curseforge.com/en/support/solutions/articles/9000207405-curse-forge-3rd-party-api-terms-and-conditions).
|
||||||
|
Keys supplied for rmcl are for rmcl builds only. Forks, rebranded applications,
|
||||||
|
and unrelated projects must use their own key. Keys included in source or compiled
|
||||||
|
binaries are extractable; do not publish a private key.
|
||||||
|
|
||||||
## installation
|
## installation
|
||||||
|
|
||||||
|
[](https://github.com/objz/rmcl/releases)
|
||||||
|
|
||||||
|
### macOS / Linux
|
||||||
|
|
||||||
|
prebuilt archives are attached to each GitHub release.
|
||||||
|
|
||||||
|
[](https://github.com/objz/homebrew-tap)
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# Homebrew
|
||||||
|
brew install objz/tap/rmcl
|
||||||
|
```
|
||||||
|
|
||||||
|
Linux archives and Homebrew installations require the system `libxcb` runtime
|
||||||
|
package (`libxcb1` on Debian/Ubuntu, `libxcb` on Arch).
|
||||||
|
|
||||||
|
An ARM64 launcher build still needs Minecraft natives for that platform. For
|
||||||
|
example, Minecraft 1.20.1 supplies macOS ARM64 natives but no Linux ARM64 natives;
|
||||||
|
using a custom GLFW library alone does not provide the other required libraries.
|
||||||
|
|
||||||
|
### Windows
|
||||||
|
|
||||||
|
release builds include a `.zip` archive and an `.msi`. WinGet packages are
|
||||||
|
submitted from release CI and become available after review.
|
||||||
|
|
||||||
|
[](https://winstall.app/apps/Objz.Rmcl)
|
||||||
|
```powershell
|
||||||
|
# WinGet
|
||||||
|
winget install Objz.Rmcl
|
||||||
|
```
|
||||||
|
|
||||||
### Arch Linux
|
### Arch Linux
|
||||||
|
|
||||||
[](https://aur.archlinux.org/packages/mcl-launcher)
|
[](https://aur.archlinux.org/packages/rmcl)
|
||||||
[](https://aur.archlinux.org/packages/mcl-launcher-bin)
|
[](https://aur.archlinux.org/packages/rmcl-bin)
|
||||||
[](https://aur.archlinux.org/packages/mcl-launcher-git)
|
[](https://aur.archlinux.org/packages/rmcl-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
|
||||||
|
```
|
||||||
|
|
||||||
|
### Nix
|
||||||
|
|
||||||
|
[](https://github.com/objz/rmcl)
|
||||||
|
|
||||||
|
```sh
|
||||||
|
nix run github:objz/rmcl
|
||||||
|
nix profile install github:objz/rmcl
|
||||||
|
```
|
||||||
|
|
||||||
|
the flake builds rmcl from source. To use your own key instead, override it
|
||||||
|
at build time:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
CURSEFORGE_API_KEY=your-key nix build --impure .#
|
||||||
|
```
|
||||||
|
|
||||||
|
Minecraft 1.12 and older currently fail to launch because rmcl doesn't pass
|
||||||
|
`-Djava.library.path` for legacy version profiles.
|
||||||
|
|
||||||
|
### Cargo
|
||||||
|
|
||||||
|
[](https://crates.io/crates/rmcl)
|
||||||
|
```sh
|
||||||
|
cargo install rmcl
|
||||||
```
|
```
|
||||||
|
|
||||||
### from source
|
### from source
|
||||||
|
|
||||||
requires a Rust toolchain and OpenSSL.
|
requires a Rust toolchain and a JDK (`javac` and `jar` on `PATH`).
|
||||||
|
Linux builds also require the libxcb development package (`libxcb1-dev` on Debian/Ubuntu, `libxcb` on Arch).
|
||||||
|
|
||||||
```sh
|
```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) |
|
|
||||||
| `~/.config/mcl/theme.toml` | theme, border style, color overrides |
|
|
||||||
| `~/.config/mcl/accounts.json` | accounts |
|
|
||||||
| `~/.local/share/mcl/instances/` | instances, each in its own directory |
|
|
||||||
| `~/.local/share/mcl/meta/` | cached game metadata, libraries, assets, loader profiles |
|
|
||||||
|
|
||||||
each instance has an `instance.json` for its config and a `.minecraft/` directory with the actual game files. standard layout, nothing weird.
|
settings, accounts, instances, and cached game metadata.
|
||||||
|
|
||||||
|
| what | Linux | macOS | Windows |
|
||||||
|
|---|---|---|---|
|
||||||
|
| config (`config.toml`, `theme.toml`, `accounts.json`) | `~/.config/rmcl/` | `~/Library/Application Support/rmcl/` | `%APPDATA%\rmcl\` |
|
||||||
|
| instances | `~/.local/share/rmcl/instances/` | `~/Library/Application Support/rmcl/instances/` | `%APPDATA%\rmcl\instances\` |
|
||||||
|
| metadata (versions, libraries, assets, loader profiles) | `~/.local/share/rmcl/meta/` | `~/Library/Application Support/rmcl/meta/` | `%APPDATA%\rmcl\meta\` |
|
||||||
|
|
||||||
|
These are default locations. On Linux, `XDG_CONFIG_HOME`, `XDG_DATA_HOME`, and
|
||||||
|
`XDG_CACHE_HOME` override the corresponding base directories. Instance and metadata
|
||||||
|
paths can also be changed in `config.toml`.
|
||||||
|
|
||||||
|
each instance has an `instance.json` for its config and a `minecraft/` directory with the actual game files.
|
||||||
|
|
||||||
|
Launcher settings saved through the TUI apply immediately, except changes to
|
||||||
|
`instances_dir`, `meta_dir`, and `image_protocol`, which require a restart.
|
||||||
|
Settings files opened through rmcl's editor shortcut are reloaded after saves;
|
||||||
|
otherwise, restart rmcl after editing `config.toml` externally. When neither global nor instance
|
||||||
|
`java_path` is set, rmcl selects Java automatically. Global JVM arguments and
|
||||||
|
environment variables are applied before per-instance values. Instances can
|
||||||
|
explicitly inherit the launcher window mode and resolution defaults.
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[general]
|
||||||
|
check_modpack_updates = true
|
||||||
|
check_content_updates = true
|
||||||
|
|
||||||
|
[defaults]
|
||||||
|
memory_min = "512M"
|
||||||
|
memory_max = "2G"
|
||||||
|
jvm_args = []
|
||||||
|
environment = {}
|
||||||
|
window_mode = "windowed"
|
||||||
|
resolution = [854, 480]
|
||||||
|
|
||||||
|
[ui]
|
||||||
|
image_protocol = "auto"
|
||||||
|
hidden_shortcut_hints = [] # all, main, instances, content, accounts, settings, popups
|
||||||
|
|
||||||
|
[content]
|
||||||
|
preferred_provider = "modrinth"
|
||||||
|
preferred_provider_only = false
|
||||||
|
ask_on_provider_conflict = true
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `hidden_shortcut_hints = ["main"]` to keep only popup guides,
|
||||||
|
`["all"]` to hide every guide, or list individual areas to hide them selectively.
|
||||||
|
|
||||||
|
### 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
|
## performance
|
||||||
|
|
||||||
everything is configured through TOML files. `config.toml` for paths, default memory allocation, and UI behavior. `theme.toml` for theme selection and border style. you can also override individual colors without making a full custom theme.
|
the following measurements were taken from a release build on a Linux development system. they are intended as a practical reference, since terminal, window size, content count, and hardware all affect the result.
|
||||||
|
|
||||||
|
### idle instance list
|
||||||
|
|
||||||
|
over a `60` second sample, the instance list used `497.81 ms` of CPU time. that is about `0.83%` of one CPU core. resident memory was `15.1 MiB`.
|
||||||
|
|
||||||
|
### idle mods list
|
||||||
|
|
||||||
|
with a populated mods list and its icons loaded, a `60` second sample used `664.77 ms` of CPU time. that is about `1.11%` of one CPU core. resident memory was `67.2 MiB`, with a peak of `69.9 MiB`.
|
||||||
|
|
||||||
|
### scrolling mods list
|
||||||
|
|
||||||
|
continuously scrolling through the populated mods list used `1000.02 ms` of CPU time over 30 seconds. that is about `3.33%` of one CPU core.
|
||||||
|
|
||||||
|
In comparison, the Modrinth AppImage used approximately `14-30%` of a CPU core and about `327 Mib` of memory while browsing the mod list.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 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.
|
pick one in `~/.config/rmcl/theme.toml`:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
theme = "gruvbox"
|
||||||
|
border_style = "rounded" # rounded | plain | double | thick
|
||||||
|
```
|
||||||
|
|
||||||
|
### custom themes
|
||||||
|
|
||||||
|
drop a TOML file in `~/.config/rmcl/theme/` and reference it by name, or point `theme` at an absolute path. keys are flat and top level, don't nest them under `[theme]`. only `name`, `id` and `accent` are required, the rest falls back to a default:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
# ~/.config/rmcl/theme/my-theme.toml
|
||||||
|
name = "My Theme"
|
||||||
|
id = "my-theme"
|
||||||
|
|
||||||
|
accent = { Rgb = [249, 115, 22] }
|
||||||
|
accent_dim = "#7f5539"
|
||||||
|
text = "#cdd6f4"
|
||||||
|
text_dim = "DarkGray"
|
||||||
|
text_bright = "#ffffff"
|
||||||
|
success = "#a6e3a1"
|
||||||
|
error = "#f38ba8"
|
||||||
|
warning = "#f9e2af"
|
||||||
|
info = "#89dceb"
|
||||||
|
diff_added = "#a6e3a1"
|
||||||
|
diff_removed = "#f38ba8"
|
||||||
|
diff_context = "DarkGray"
|
||||||
|
border = "#585b70"
|
||||||
|
surface = "#313244"
|
||||||
|
background = "#1e1e2e"
|
||||||
|
```
|
||||||
|
|
||||||
|
then set `theme = "my-theme"` in `theme.toml`.
|
||||||
|
|
||||||
|
colors accept `"#f97316"`, ANSI names (`"Red"`, `"LightBlue"`), `{ Rgb = [r, g, b] }` or `{ Indexed = n }`.
|
||||||
|
|
||||||
|
note that `[custom]` in `theme.toml` overrides colors of the selected theme, whether built-in or loaded from a file; it doesn't define a standalone theme. `border_style` belongs at the top level of `theme.toml`, not in a custom theme file.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 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)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## license
|
## license
|
||||||
|
Copyright (C) 2026 Constantin Bauer
|
||||||
|
|
||||||
GPL-3.0. see [LICENSE](LICENSE).
|
This project is licensed under the GNU General Public License v3.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
|
||||||
+36
-9
@@ -1,19 +1,32 @@
|
|||||||
|
[general]
|
||||||
|
# check imported modpacks and managed content for updates automatically
|
||||||
|
check_modpack_updates = true
|
||||||
|
check_content_updates = true
|
||||||
|
|
||||||
[paths]
|
[paths]
|
||||||
# where instances are stored
|
# instances_dir and meta_dir use platform defaults when omitted
|
||||||
instances_dir = "~/.local/share/mcl/instances"
|
# java_path is omitted to select Java automatically
|
||||||
|
# instances_dir = "/path/to/minecraft/instances"
|
||||||
# metadata, cache, whatever else ends up there
|
# meta_dir = "/path/to/rmcl/meta"
|
||||||
meta_dir = "~/.local/share/mcl/meta"
|
# java_path = "/usr/bin/java"
|
||||||
|
|
||||||
# optional java override (empty = uses JAVA_HOME)
|
|
||||||
java_path = ""
|
|
||||||
|
|
||||||
[defaults]
|
[defaults]
|
||||||
# default heap settings
|
# inherited by instances that do not override their memory
|
||||||
memory_min = "512M"
|
memory_min = "512M"
|
||||||
memory_max = "2G"
|
memory_max = "2G"
|
||||||
|
# appended to every instance; instance values take precedence where applicable
|
||||||
|
jvm_args = []
|
||||||
|
environment = {}
|
||||||
|
# inherited by instances that use launcher window defaults
|
||||||
|
window_mode = "windowed"
|
||||||
|
resolution = [854, 480]
|
||||||
|
|
||||||
[ui]
|
[ui]
|
||||||
|
# image protocol: auto, halfblocks, quadrants, kitty, or iterm2
|
||||||
|
image_protocol = "auto"
|
||||||
|
# [] shows all guides; ["main"] keeps popup guides; ["all"] hides every guide
|
||||||
|
# areas can also be hidden selectively: instances, content, accounts, settings, popups
|
||||||
|
hidden_shortcut_hints = []
|
||||||
# error popup timing (in ms)
|
# error popup timing (in ms)
|
||||||
error_auto_dismiss_ms = 5000
|
error_auto_dismiss_ms = 5000
|
||||||
error_slide_start_ms = 3500
|
error_slide_start_ms = 3500
|
||||||
@@ -21,3 +34,17 @@ error_fly_out_ms = 300
|
|||||||
|
|
||||||
# don’t let this blow up endlessly
|
# don’t let this blow up endlessly
|
||||||
max_error_events = 50
|
max_error_events = 50
|
||||||
|
|
||||||
|
[content]
|
||||||
|
# ask before choosing when the same file exists on multiple providers
|
||||||
|
ask_on_provider_conflict = true
|
||||||
|
# preferred for duplicate discovery results and automatic conflict resolution
|
||||||
|
# accepts "modrinth" or "curseforge"
|
||||||
|
preferred_provider = "modrinth"
|
||||||
|
# only show results from the preferred provider instead of filling from both
|
||||||
|
preferred_provider_only = false
|
||||||
|
# retry unchanged files that were not found after this many hours
|
||||||
|
unmatched_retry_hours = 24
|
||||||
|
# avoid hashing enormous external packs during automatic provider matching;
|
||||||
|
# set to 0 to remove the limit
|
||||||
|
max_fingerprint_size_mib = 512
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# example custom theme -> ~/.config/rmcl/theme/my-theme.toml
|
||||||
|
# activate it in ~/.config/rmcl/theme.toml with: theme = "my-theme"
|
||||||
|
#
|
||||||
|
# this file is a theme, not the config: keys live at the top level, NOT under
|
||||||
|
# [theme] or [custom]. only name, id and accent are required; every other key
|
||||||
|
# falls back to a sane default.
|
||||||
|
#
|
||||||
|
# color formats: "#f97316" | "Red" / "LightBlue" (ANSI names) |
|
||||||
|
# { Rgb = [249, 115, 22] } | { Indexed = 42 }
|
||||||
|
|
||||||
|
name = "My Theme"
|
||||||
|
id = "my-theme"
|
||||||
|
|
||||||
|
accent = { Rgb = [249, 115, 22] }
|
||||||
|
accent_dim = "#7f5539"
|
||||||
|
|
||||||
|
text = "#cdd6f4"
|
||||||
|
text_dim = "DarkGray"
|
||||||
|
text_bright = "#ffffff"
|
||||||
|
|
||||||
|
success = "#a6e3a1"
|
||||||
|
error = "#f38ba8"
|
||||||
|
warning = "#f9e2af"
|
||||||
|
info = "#89dceb"
|
||||||
|
|
||||||
|
diff_added = "#a6e3a1"
|
||||||
|
diff_removed = "#f38ba8"
|
||||||
|
diff_context = "DarkGray"
|
||||||
|
|
||||||
|
border = "#585b70"
|
||||||
|
surface = "#313244"
|
||||||
|
background = "#1e1e2e"
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<!-- Generator: Adobe Illustrator 26.2.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
|
|
||||||
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
|
||||||
viewBox="0 0 133.2 144.10001" style="enable-background:new 0 0 133.2 144.10001;" xml:space="preserve">
|
viewBox="0 0 133.2 144.10001" style="enable-background:new 0 0 133.2 144.10001;" xml:space="preserve">
|
||||||
<style type="text/css">
|
<style type="text/css">
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 149 KiB After Width: | Height: | Size: 149 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.3 MiB |
Binary file not shown.
|
Before Width: | Height: | Size: 389 KiB After Width: | Height: | Size: 1.1 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 354 KiB |
+5
-3
@@ -2,10 +2,12 @@
|
|||||||
# catppuccin, dracula, nord, gruvbox, one-dark,
|
# catppuccin, dracula, nord, gruvbox, one-dark,
|
||||||
# solarized, tailwind, tokyo-night, rose-pine, terminal
|
# solarized, tailwind, tokyo-night, rose-pine, terminal
|
||||||
#
|
#
|
||||||
# custom themes:
|
# custom themes:
|
||||||
# theme = "my-theme" (loads ~/.config/mcl/theme/my-theme.toml)
|
# theme = "my-theme" (loads ~/.config/rmcl/theme/my-theme.toml)
|
||||||
# theme = "/path/to/file" (loads from absolute path)
|
# theme = "/path/to/file" (loads from absolute path)
|
||||||
theme = "terminal"
|
# a theme file has flat top-level keys (name, id, accent, ...), not the
|
||||||
|
# [custom] table below. see assets/example-theme.toml in the repo.
|
||||||
|
theme = "gruvbox"
|
||||||
|
|
||||||
# rounded, plain, double, thick
|
# rounded, plain, double, thick
|
||||||
border_style = "rounded"
|
border_style = "rounded"
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
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");
|
||||||
|
|
||||||
|
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");
|
||||||
|
}
|
||||||
+66
@@ -0,0 +1,66 @@
|
|||||||
|
[remote.github]
|
||||||
|
owner = "objz"
|
||||||
|
repo = "rmcl"
|
||||||
|
|
||||||
|
[changelog]
|
||||||
|
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 }}
|
||||||
|
{% for commit in commits %}
|
||||||
|
- {% if commit.scope %}*({{ commit.scope }})* {% endif %}\
|
||||||
|
{% if commit.breaking %}[**breaking**] {% endif %}\
|
||||||
|
{{ commit.message }}\
|
||||||
|
{% 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 %}
|
||||||
|
"""
|
||||||
|
trim = true
|
||||||
|
render_always = true
|
||||||
|
postprocessors = []
|
||||||
|
|
||||||
|
[git]
|
||||||
|
conventional_commits = true
|
||||||
|
filter_unconventional = false
|
||||||
|
require_conventional = false
|
||||||
|
split_commits = false
|
||||||
|
commit_preprocessors = [
|
||||||
|
{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](https://github.com/objz/rmcl/issues/${2}))" },
|
||||||
|
]
|
||||||
|
protect_breaking_commits = false
|
||||||
|
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 -->refactoring" },
|
||||||
|
{ 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 -->maintenance" },
|
||||||
|
{ body = ".*security", group = "<!-- 8 -->security" },
|
||||||
|
{ message = "^revert", group = "<!-- 9 -->reverts" },
|
||||||
|
{ message = ".*", group = "<!-- 10 -->other changes" },
|
||||||
|
]
|
||||||
|
filter_commits = false
|
||||||
|
fail_on_unmatched_commit = false
|
||||||
|
link_parsers = []
|
||||||
|
use_branch_tags = false
|
||||||
|
topo_order = false
|
||||||
|
topo_order_commits = true
|
||||||
|
sort_commits = "oldest"
|
||||||
|
recurse_submodules = false
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
[workspace]
|
||||||
|
members = ["cargo:."]
|
||||||
|
|
||||||
|
[dist]
|
||||||
|
cargo-dist-version = "0.31.0"
|
||||||
|
ci = "github"
|
||||||
|
installers = ["homebrew", "msi"]
|
||||||
|
tap = "objz/homebrew-tap"
|
||||||
|
targets = ["aarch64-apple-darwin", "aarch64-unknown-linux-gnu", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu", "x86_64-pc-windows-msvc"]
|
||||||
|
install-path = "CARGO_HOME"
|
||||||
|
publish-jobs = ["homebrew", "./publish-crates", "./publish-aur", "./publish-winget"]
|
||||||
|
github-custom-job-permissions = { publish-crates = { contents = "read" }, publish-aur = { contents = "read" }, publish-winget = { contents = "write" } }
|
||||||
|
github-build-setup = "../dist-build-setup.yml"
|
||||||
|
hosting = "github"
|
||||||
|
install-updater = false
|
||||||
|
allow-dirty = ["ci", "msi"]
|
||||||
Generated
+61
@@ -0,0 +1,61 @@
|
|||||||
|
{
|
||||||
|
"nodes": {
|
||||||
|
"flake-utils": {
|
||||||
|
"inputs": {
|
||||||
|
"systems": "systems"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1731533236,
|
||||||
|
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1790570722,
|
||||||
|
"narHash": "sha256-Avcz96Q+8OkfUIUXipBBVsQn19L622BtKP7mk6M+uls=",
|
||||||
|
"owner": "nixos",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "419fe0f449b3fbe3bdd53d9840288db4509ec32e",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "nixos",
|
||||||
|
"ref": "nixpkgs-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": {
|
||||||
|
"inputs": {
|
||||||
|
"flake-utils": "flake-utils",
|
||||||
|
"nixpkgs": "nixpkgs"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"systems": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1681028828,
|
||||||
|
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": "root",
|
||||||
|
"version": 7
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
{
|
||||||
|
description = "rmcl: A fully featured Minecraft TUI launcher";
|
||||||
|
|
||||||
|
inputs = {
|
||||||
|
nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-unstable";
|
||||||
|
flake-utils.url = "github:numtide/flake-utils";
|
||||||
|
};
|
||||||
|
|
||||||
|
outputs = {
|
||||||
|
nixpkgs,
|
||||||
|
flake-utils,
|
||||||
|
...
|
||||||
|
}:
|
||||||
|
flake-utils.lib.eachDefaultSystem (system: let
|
||||||
|
pkgs = nixpkgs.legacyPackages.${system};
|
||||||
|
# release binaries have the curseforge key compiled in; source builds
|
||||||
|
# don't, so forward the caller's key when building impurely.
|
||||||
|
curseforgeApiKey = builtins.getEnv "CURSEFORGE_API_KEY";
|
||||||
|
# minecraft's bundled lwjgl natives dlopen the host's x11 stack, which
|
||||||
|
# isn't on the default loader path on nixos. java is spawned as a child
|
||||||
|
# of rmcl, so a wrapper LD_LIBRARY_PATH propagates all the way down.
|
||||||
|
runtimeLibs = pkgs.lib.makeLibraryPath (with pkgs; [
|
||||||
|
libX11
|
||||||
|
libXext
|
||||||
|
libXcursor
|
||||||
|
libXrandr
|
||||||
|
libXxf86vm
|
||||||
|
]);
|
||||||
|
in {
|
||||||
|
packages.default = pkgs.rustPlatform.buildRustPackage {
|
||||||
|
pname = "rmcl";
|
||||||
|
version = (builtins.fromTOML (builtins.readFile ./Cargo.toml)).package.version;
|
||||||
|
src = pkgs.lib.cleanSource ./.;
|
||||||
|
cargoLock.lockFile = ./Cargo.lock;
|
||||||
|
nativeBuildInputs = [pkgs.jdk pkgs.makeWrapper];
|
||||||
|
buildInputs = [pkgs.libxcb];
|
||||||
|
|
||||||
|
env = pkgs.lib.optionalAttrs (curseforgeApiKey != "") {
|
||||||
|
CURSEFORGE_API_KEY = curseforgeApiKey;
|
||||||
|
};
|
||||||
|
|
||||||
|
postFixup = ''
|
||||||
|
wrapProgram $out/bin/rmcl --prefix LD_LIBRARY_PATH : ${runtimeLibs}
|
||||||
|
'';
|
||||||
|
|
||||||
|
meta = with pkgs.lib; {
|
||||||
|
description = "A fully featured Minecraft TUI launcher";
|
||||||
|
homepage = "https://github.com/objz/rmcl";
|
||||||
|
license = licenses.gpl3Only;
|
||||||
|
mainProgram = "rmcl";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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=('libxcb')
|
||||||
|
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,42 @@
|
|||||||
|
# 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=('libxcb')
|
||||||
|
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() {
|
||||||
|
export CARGO_TARGET_DIR="$srcdir/target"
|
||||||
|
rm -rf "$CARGO_TARGET_DIR"
|
||||||
|
cd "$srcdir/rmcl"
|
||||||
|
cargo build --release --locked
|
||||||
|
}
|
||||||
|
|
||||||
|
check() {
|
||||||
|
export CARGO_TARGET_DIR="$srcdir/target"
|
||||||
|
export XDG_CONFIG_HOME="$srcdir/xdg-config"
|
||||||
|
mkdir -p "$XDG_CONFIG_HOME"
|
||||||
|
cd "$srcdir/rmcl"
|
||||||
|
cargo test --release --locked
|
||||||
|
}
|
||||||
|
|
||||||
|
package() {
|
||||||
|
cd "$srcdir/rmcl"
|
||||||
|
install -Dm755 "$srcdir/target/release/rmcl" "$pkgdir/usr/bin/rmcl"
|
||||||
|
install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
||||||
|
install -Dm644 README.md "$pkgdir/usr/share/doc/$pkgname/README.md"
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# 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=('libxcb')
|
||||||
|
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() {
|
||||||
|
export CARGO_TARGET_DIR="$srcdir/target"
|
||||||
|
rm -rf "$CARGO_TARGET_DIR"
|
||||||
|
cd "$srcdir/rmcl-${pkgver}"
|
||||||
|
cargo build --release --locked
|
||||||
|
}
|
||||||
|
|
||||||
|
check() {
|
||||||
|
export CARGO_TARGET_DIR="$srcdir/target"
|
||||||
|
export XDG_CONFIG_HOME="$srcdir/xdg-config"
|
||||||
|
mkdir -p "$XDG_CONFIG_HOME"
|
||||||
|
cd "$srcdir/rmcl-${pkgver}"
|
||||||
|
cargo test --release --locked
|
||||||
|
}
|
||||||
|
|
||||||
|
package() {
|
||||||
|
cd "$srcdir/rmcl-${pkgver}"
|
||||||
|
install -Dm755 "$srcdir/target/release/rmcl" "$pkgdir/usr/bin/rmcl"
|
||||||
|
install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
|
||||||
|
install -Dm644 README.md "$pkgdir/usr/share/doc/$pkgname/README.md"
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
<?xml version='1.0' encoding='windows-1252'?>
|
||||||
|
<!--
|
||||||
|
Copyright (C) 2017 Christopher R. Field.
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
|
-->
|
||||||
|
|
||||||
|
<!--
|
||||||
|
The "cargo wix" subcommand provides a variety of predefined variables available
|
||||||
|
for customization of this template. The values for each variable are set at
|
||||||
|
installer creation time. The following variables are available:
|
||||||
|
|
||||||
|
TargetTriple = The rustc target triple name.
|
||||||
|
TargetEnv = The rustc target environment. This is typically either
|
||||||
|
"msvc" or "gnu" depending on the toolchain downloaded and
|
||||||
|
installed.
|
||||||
|
TargetVendor = The rustc target vendor. This is typically "pc", but Rust
|
||||||
|
does support other vendors, like "uwp".
|
||||||
|
CargoTargetBinDir = The complete path to the directory containing the
|
||||||
|
binaries (exes) to include. The default would be
|
||||||
|
"target\release\". If an explicit rustc target triple is
|
||||||
|
used, i.e. cross-compiling, then the default path would
|
||||||
|
be "target\<CARGO_TARGET>\<CARGO_PROFILE>",
|
||||||
|
where "<CARGO_TARGET>" is replaced with the "CargoTarget"
|
||||||
|
variable value and "<CARGO_PROFILE>" is replaced with the
|
||||||
|
value from the "CargoProfile" variable. This can also
|
||||||
|
be overridden manually with the "target-bin-dir" flag.
|
||||||
|
CargoTargetDir = The path to the directory for the build artifacts, i.e.
|
||||||
|
"target".
|
||||||
|
CargoProfile = The cargo profile used to build the binaries
|
||||||
|
(usually "debug" or "release").
|
||||||
|
Version = The version for the installer. The default is the
|
||||||
|
"Major.Minor.Fix" semantic versioning number of the Rust
|
||||||
|
package.
|
||||||
|
-->
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Please do not remove these pre-processor If-Else blocks. These are used with
|
||||||
|
the `cargo wix` subcommand to automatically determine the installation
|
||||||
|
destination for 32-bit versus 64-bit installers. Removal of these lines will
|
||||||
|
cause installation errors.
|
||||||
|
-->
|
||||||
|
<?if $(sys.BUILDARCH) = x64 or $(sys.BUILDARCH) = arm64 ?>
|
||||||
|
<?define PlatformProgramFilesFolder = "ProgramFiles64Folder" ?>
|
||||||
|
<?else ?>
|
||||||
|
<?define PlatformProgramFilesFolder = "ProgramFilesFolder" ?>
|
||||||
|
<?endif ?>
|
||||||
|
|
||||||
|
<Wix xmlns='http://schemas.microsoft.com/wix/2006/wi'>
|
||||||
|
|
||||||
|
<Product
|
||||||
|
Id='*'
|
||||||
|
Name='rmcl'
|
||||||
|
UpgradeCode='BEC08BE4-6A8F-4C1D-A1B4-B1AC963000AE'
|
||||||
|
Manufacturer='objz'
|
||||||
|
Language='1033'
|
||||||
|
Codepage='1252'
|
||||||
|
Version='$(var.Version)'>
|
||||||
|
|
||||||
|
<Package Id='*'
|
||||||
|
Keywords='Installer'
|
||||||
|
Description='A fully featured Minecraft TUI launcher'
|
||||||
|
Manufacturer='objz'
|
||||||
|
InstallerVersion='450'
|
||||||
|
Languages='1033'
|
||||||
|
Compressed='yes'
|
||||||
|
InstallScope='perMachine'
|
||||||
|
SummaryCodepage='1252'
|
||||||
|
/>
|
||||||
|
|
||||||
|
<MajorUpgrade
|
||||||
|
Schedule='afterInstallInitialize'
|
||||||
|
DowngradeErrorMessage='A newer version of [ProductName] is already installed. Setup will now exit.'/>
|
||||||
|
|
||||||
|
<Media Id='1' Cabinet='media1.cab' EmbedCab='yes' DiskPrompt='CD-ROM #1'/>
|
||||||
|
<Property Id='DiskPrompt' Value='rmcl Installation'/>
|
||||||
|
|
||||||
|
<Directory Id='TARGETDIR' Name='SourceDir'>
|
||||||
|
<Directory Id='$(var.PlatformProgramFilesFolder)' Name='PFiles'>
|
||||||
|
<Directory Id='APPLICATIONFOLDER' Name='rmcl'>
|
||||||
|
|
||||||
|
<Directory Id='Bin' Name='bin'>
|
||||||
|
<Component Id='Path' Guid='E5863AC2-13FC-45C8-B79D-55338F371A8A' KeyPath='yes'>
|
||||||
|
<Environment
|
||||||
|
Id='PATH'
|
||||||
|
Name='PATH'
|
||||||
|
Value='[Bin]'
|
||||||
|
Permanent='no'
|
||||||
|
Part='last'
|
||||||
|
Action='set'
|
||||||
|
System='yes'/>
|
||||||
|
</Component>
|
||||||
|
<Component Id='binary0' Guid='*'>
|
||||||
|
<File
|
||||||
|
Id='exe0'
|
||||||
|
Name='rmcl.exe'
|
||||||
|
DiskId='1'
|
||||||
|
Source='$(var.CargoTargetBinDir)\rmcl.exe'
|
||||||
|
KeyPath='yes'/>
|
||||||
|
</Component>
|
||||||
|
</Directory>
|
||||||
|
</Directory>
|
||||||
|
</Directory>
|
||||||
|
</Directory>
|
||||||
|
|
||||||
|
<Feature
|
||||||
|
Id='Binaries'
|
||||||
|
Title='Application'
|
||||||
|
Description='Installs all binaries and the license.'
|
||||||
|
Level='1'
|
||||||
|
ConfigurableDirectory='APPLICATIONFOLDER'
|
||||||
|
AllowAdvertise='no'
|
||||||
|
Display='expand'
|
||||||
|
Absent='disallow'>
|
||||||
|
|
||||||
|
<ComponentRef Id='binary0'/>
|
||||||
|
|
||||||
|
<Feature
|
||||||
|
Id='Environment'
|
||||||
|
Title='PATH Environment Variable'
|
||||||
|
Description='Add the install location of the [ProductName] executable to the PATH system environment variable. This allows the [ProductName] executable to be called from any location.'
|
||||||
|
Level='1'
|
||||||
|
Absent='allow'>
|
||||||
|
<ComponentRef Id='Path'/>
|
||||||
|
</Feature>
|
||||||
|
</Feature>
|
||||||
|
|
||||||
|
<SetProperty Id='ARPINSTALLLOCATION' Value='[APPLICATIONFOLDER]' After='CostFinalize'/>
|
||||||
|
|
||||||
|
|
||||||
|
<Property Id='ARPHELPLINK' Value='https://github.com/objz/rmcl'/>
|
||||||
|
|
||||||
|
<UI>
|
||||||
|
<UIRef Id='WixUI_FeatureTree'/>
|
||||||
|
|
||||||
|
<Publish Dialog='WelcomeDlg' Control='Next' Event='NewDialog' Value='CustomizeDlg' Order='99'>1</Publish>
|
||||||
|
<Publish Dialog='CustomizeDlg' Control='Back' Event='NewDialog' Value='WelcomeDlg' Order='99'>1</Publish>
|
||||||
|
|
||||||
|
</UI>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
</Product>
|
||||||
|
|
||||||
|
</Wix>
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
# SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
def version_key(value):
|
||||||
|
match = re.fullmatch(
|
||||||
|
r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)"
|
||||||
|
r"(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?"
|
||||||
|
r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?",
|
||||||
|
value,
|
||||||
|
)
|
||||||
|
if match is None:
|
||||||
|
return None
|
||||||
|
pre = match[4].split(".") if match[4] is not None else []
|
||||||
|
if any(part.isdigit() and len(part) > 1 and part.startswith("0") for part in pre):
|
||||||
|
return None
|
||||||
|
return tuple(map(int, match.groups()[:3])) + (
|
||||||
|
match[4] is None,
|
||||||
|
tuple((0, int(part)) if part.isdigit() else (1, part) for part in pre),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def check():
|
||||||
|
chain = "1.0.0-alpha 1.0.0-alpha.1 1.0.0-alpha.beta 1.0.0-beta 1.0.0-beta.2 1.0.0-beta.11 1.0.0-rc.1 1.0.0".split()
|
||||||
|
assert all(version_key(a) < version_key(b) for a, b in zip(chain, chain[1:]))
|
||||||
|
assert version_key("1.0.0+build2") == version_key("1.0.0+build1")
|
||||||
|
assert all(version_key(v) is None for v in ["01.0.0", "1.0.0-01", "1.0.0-alpha..1"])
|
||||||
|
assert version_key("0.5.1") > version_key("0.5.1-rc.1")
|
||||||
|
assert version_key("0.5.1-rc.10") > version_key("0.5.1-rc.9")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
if sys.argv[1:] == ["--check"]:
|
||||||
|
check()
|
||||||
|
else:
|
||||||
|
version = sys.argv[1]
|
||||||
|
candidate = version_key(version)
|
||||||
|
if candidate is None:
|
||||||
|
sys.exit(f"Invalid package version: {version}")
|
||||||
|
versions = [
|
||||||
|
(key, tag[1:])
|
||||||
|
for tag in subprocess.check_output(["git", "tag", "--list", "v*"], text=True).splitlines()
|
||||||
|
if (key := version_key(tag[1:])) is not None
|
||||||
|
]
|
||||||
|
latest_key, latest = max(versions, default=(None, ""))
|
||||||
|
release = latest_key is None or candidate > latest_key
|
||||||
|
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output:
|
||||||
|
output.write(f"release={str(release).lower()}\ntag=v{version}\n")
|
||||||
|
print(f"v{version}: release={str(release).lower()}, latest={latest or 'none'}")
|
||||||
+161
-213
@@ -1,4 +1,5 @@
|
|||||||
// account management: persistence, switching active accounts, and offline uuid generation
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
@@ -12,6 +13,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)]
|
||||||
@@ -29,68 +34,178 @@ pub enum AuthResult {
|
|||||||
pub struct AccountStore {
|
pub struct AccountStore {
|
||||||
pub accounts: Vec<Account>,
|
pub accounts: Vec<Account>,
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
|
load_error: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AccountStore {
|
impl AccountStore {
|
||||||
pub fn load() -> Self {
|
pub fn load() -> Self {
|
||||||
let path = account_store_path();
|
Self::load_from(account_store_path())
|
||||||
let accounts = match std::fs::read_to_string(&path) {
|
|
||||||
Ok(content) => serde_json::from_str(&content).unwrap_or_default(),
|
|
||||||
Err(_) => Vec::new(),
|
|
||||||
};
|
|
||||||
Self { accounts, path }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn save(&self) {
|
fn load_from(path: PathBuf) -> Self {
|
||||||
if let Some(parent) = self.path.parent()
|
let (accounts, load_error) = match std::fs::read_to_string(&path) {
|
||||||
&& let Err(e) = std::fs::create_dir_all(parent)
|
Ok(content) => match serde_json::from_str(&content) {
|
||||||
{
|
Ok(accounts) => (accounts, None),
|
||||||
tracing::error!("Failed to create accounts directory: {}", e);
|
Err(e) => {
|
||||||
return;
|
tracing::warn!("Failed to parse accounts file {}: {}", path.display(), e);
|
||||||
}
|
(
|
||||||
match serde_json::to_string_pretty(&self.accounts) {
|
Vec::new(),
|
||||||
Ok(json) => {
|
Some(format!("Invalid accounts file {}: {e}", path.display())),
|
||||||
if let Err(e) = std::fs::write(&self.path, json) {
|
)
|
||||||
tracing::error!("Failed to write accounts file: {}", e);
|
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||||
|
tracing::debug!("No accounts file at {}", path.display());
|
||||||
|
(Vec::new(), None)
|
||||||
}
|
}
|
||||||
Err(e) => tracing::error!("Failed to serialize accounts: {}", e),
|
Err(e) => {
|
||||||
|
tracing::warn!("Failed to read accounts file {}: {}", path.display(), e);
|
||||||
|
(
|
||||||
|
Vec::new(),
|
||||||
|
Some(format!("Cannot read accounts file {}: {e}", path.display())),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
tracing::debug!(
|
||||||
|
"Loaded {} account(s) from {}",
|
||||||
|
accounts.len(),
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
Self {
|
||||||
|
accounts,
|
||||||
|
path,
|
||||||
|
load_error,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn check_loaded(&self) -> std::io::Result<()> {
|
||||||
|
if let Some(error) = &self.load_error {
|
||||||
|
return Err(std::io::Error::other(error.clone()));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save(&self) -> std::io::Result<()> {
|
||||||
|
self.check_loaded()?;
|
||||||
|
let json = serde_json::to_vec_pretty(&self.accounts).map_err(std::io::Error::other)?;
|
||||||
|
crate::storage::write_atomic_private(&self.path, &json)?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Saved {} account(s) to {}",
|
||||||
|
self.accounts.len(),
|
||||||
|
self.path.display()
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn active_account(&self) -> Option<&Account> {
|
pub fn active_account(&self) -> Option<&Account> {
|
||||||
self.accounts.iter().find(|a| a.active)
|
self.accounts.iter().find(|a| a.active)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_active(&mut self, index: usize) {
|
pub fn has_microsoft_account(&self) -> bool {
|
||||||
for (i, acc) in self.accounts.iter_mut().enumerate() {
|
self.accounts
|
||||||
acc.active = i == index;
|
.iter()
|
||||||
}
|
.any(|account| account.account_type == AccountType::Microsoft)
|
||||||
self.save();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// if an account with the same uuid already exists, replace it.
|
pub fn set_active(&mut self, index: usize) -> std::io::Result<()> {
|
||||||
// first account added auto-becomes active so there's always a selection.
|
let Some(account) = self.accounts.get(index) else {
|
||||||
pub fn add(&mut self, account: Account) {
|
// Invalid selection must leave the active account intact.
|
||||||
let uuid = &account.uuid;
|
tracing::warn!("Tried to select missing account index {}", index);
|
||||||
self.accounts.retain(|a| a.uuid != *uuid);
|
return Ok(());
|
||||||
let mut account = account;
|
};
|
||||||
if self.accounts.is_empty() {
|
let uuid = account.uuid.clone();
|
||||||
account.active = true;
|
self.update(|accounts| {
|
||||||
}
|
if !accounts.iter().any(|account| account.uuid == uuid) {
|
||||||
self.accounts.push(account);
|
return Err(std::io::Error::other("Selected account no longer exists"));
|
||||||
self.save();
|
}
|
||||||
|
for account in accounts {
|
||||||
|
account.active = account.uuid == uuid;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn remove(&mut self, index: usize) {
|
pub fn add(&mut self, account: Account) -> std::io::Result<()> {
|
||||||
|
self.update(|accounts| {
|
||||||
|
let replaced_active = accounts
|
||||||
|
.iter()
|
||||||
|
.any(|old| old.uuid == account.uuid && old.active);
|
||||||
|
accounts.retain(|old| old.uuid != account.uuid);
|
||||||
|
let mut account = account;
|
||||||
|
account.active = accounts.is_empty() || replaced_active;
|
||||||
|
accounts.push(account);
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove(&mut self, index: usize) -> std::io::Result<()> {
|
||||||
if index >= self.accounts.len() {
|
if index >= self.accounts.len() {
|
||||||
return;
|
tracing::warn!("Tried to remove missing account index {}", index);
|
||||||
|
return Ok(());
|
||||||
}
|
}
|
||||||
let account = self.accounts.remove(index);
|
let uuid = self.accounts[index].uuid.clone();
|
||||||
if account.active && !self.accounts.is_empty() {
|
self.update(|accounts| {
|
||||||
self.accounts[0].active = true;
|
let index = accounts
|
||||||
|
.iter()
|
||||||
|
.position(|account| account.uuid == uuid)
|
||||||
|
.ok_or_else(|| std::io::Error::other("Selected account no longer exists"))?;
|
||||||
|
let account = accounts.remove(index);
|
||||||
|
if account.active
|
||||||
|
&& let Some(first) = accounts.first_mut()
|
||||||
|
{
|
||||||
|
first.active = true;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update_credentials(
|
||||||
|
&mut self,
|
||||||
|
uuid: &str,
|
||||||
|
refresh: Option<String>,
|
||||||
|
token: &str,
|
||||||
|
expires: Option<i64>,
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
if refresh.is_none() && expires.is_none() {
|
||||||
|
return Ok(());
|
||||||
}
|
}
|
||||||
self.save();
|
self.update(|accounts| {
|
||||||
|
let account = accounts
|
||||||
|
.iter_mut()
|
||||||
|
.find(|account| account.uuid == uuid)
|
||||||
|
.ok_or_else(|| std::io::Error::other("Authenticated account no longer exists"))?;
|
||||||
|
if let Some(refresh) = refresh {
|
||||||
|
account.refresh_token = Some(refresh);
|
||||||
|
}
|
||||||
|
if let Some(expires) = expires {
|
||||||
|
account.cached_mc_token = Some(token.to_owned());
|
||||||
|
account.cached_mc_token_expires_at = Some(expires);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update(
|
||||||
|
&mut self,
|
||||||
|
update: impl FnOnce(&mut Vec<Account>) -> std::io::Result<()>,
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
use fs2::FileExt;
|
||||||
|
self.check_loaded()?;
|
||||||
|
if let Some(parent) = self.path.parent() {
|
||||||
|
std::fs::create_dir_all(parent)?;
|
||||||
|
}
|
||||||
|
let lock = std::fs::OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.truncate(false)
|
||||||
|
.write(true)
|
||||||
|
.open(self.path.with_extension("lock"))?;
|
||||||
|
lock.lock_exclusive()?;
|
||||||
|
let mut current = Self::load_from(self.path.clone());
|
||||||
|
current.check_loaded()?;
|
||||||
|
update(&mut current.accounts)?;
|
||||||
|
current.save()?;
|
||||||
|
self.accounts = current.accounts;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,9 +213,7 @@ pub fn account_store_path() -> PathBuf {
|
|||||||
crate::config::get_config_path().join("accounts.json")
|
crate::config::get_config_path().join("accounts.json")
|
||||||
}
|
}
|
||||||
|
|
||||||
// deterministic fake uuid from a username, formatted as uuid v3 with the proper
|
// Keep the existing mapping so saved offline player data retains its identifier.
|
||||||
// version and variant bits set. not cryptographically meaningful, just needs to
|
|
||||||
// be consistent so the same offline name always maps to the same uuid.
|
|
||||||
pub fn offline_uuid(username: &str) -> String {
|
pub fn offline_uuid(username: &str) -> String {
|
||||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||||
let mut hasher = DefaultHasher::new();
|
let mut hasher = DefaultHasher::new();
|
||||||
@@ -123,176 +236,11 @@ 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,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/accounts.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn offline_uuid_is_valid_format() {
|
|
||||||
let uuid = offline_uuid("Steve");
|
|
||||||
let parts: Vec<&str> = uuid.split('-').collect();
|
|
||||||
assert_eq!(parts.len(), 5, "UUID must have 5 dash-separated parts");
|
|
||||||
assert_eq!(parts[0].len(), 8);
|
|
||||||
assert_eq!(parts[1].len(), 4);
|
|
||||||
assert_eq!(parts[2].len(), 4);
|
|
||||||
assert_eq!(parts[3].len(), 4);
|
|
||||||
assert_eq!(parts[4].len(), 12);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn offline_uuid_version_3_marker() {
|
|
||||||
let uuid = offline_uuid("Steve");
|
|
||||||
assert!(uuid.split('-').nth(2).unwrap().starts_with('3'));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn offline_uuid_variant_bit_set() {
|
|
||||||
let uuid = offline_uuid("Steve");
|
|
||||||
let part3 = uuid.split('-').nth(3).unwrap();
|
|
||||||
let first_nibble = u8::from_str_radix(&part3[..1], 16).unwrap();
|
|
||||||
assert!((0x8..=0xb).contains(&first_nibble));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn offline_uuid_deterministic() {
|
|
||||||
assert_eq!(offline_uuid("Steve"), offline_uuid("Steve"));
|
|
||||||
assert_eq!(offline_uuid("Alex"), offline_uuid("Alex"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn offline_uuid_different_for_different_names() {
|
|
||||||
assert_ne!(offline_uuid("Steve"), offline_uuid("Alex"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn create_offline_account_fields() {
|
|
||||||
let acc = create_offline_account("TestPlayer");
|
|
||||||
assert_eq!(acc.username, "TestPlayer");
|
|
||||||
assert_eq!(acc.account_type, AccountType::Offline);
|
|
||||||
assert!(!acc.active);
|
|
||||||
assert!(acc.refresh_token.is_none());
|
|
||||||
assert!(!acc.uuid.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
fn make_store(dir: &std::path::Path) -> AccountStore {
|
|
||||||
AccountStore {
|
|
||||||
accounts: Vec::new(),
|
|
||||||
path: dir.join("accounts.json"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn dummy_account(name: &str) -> Account {
|
|
||||||
Account {
|
|
||||||
uuid: offline_uuid(name),
|
|
||||||
username: name.to_owned(),
|
|
||||||
account_type: AccountType::Offline,
|
|
||||||
active: false,
|
|
||||||
refresh_token: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_add_first_becomes_active() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = make_store(tmp.path());
|
|
||||||
store.add(dummy_account("Alice"));
|
|
||||||
assert_eq!(store.accounts.len(), 1);
|
|
||||||
assert!(store.accounts[0].active);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_add_second_stays_inactive() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = make_store(tmp.path());
|
|
||||||
store.add(dummy_account("Alice"));
|
|
||||||
store.add(dummy_account("Bob"));
|
|
||||||
assert_eq!(store.accounts.len(), 2);
|
|
||||||
assert!(store.accounts[0].active);
|
|
||||||
assert!(!store.accounts[1].active);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_add_duplicate_uuid_replaces() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = make_store(tmp.path());
|
|
||||||
store.add(dummy_account("Alice"));
|
|
||||||
let mut dup = dummy_account("Alice");
|
|
||||||
dup.username = "AliceRenamed".to_owned();
|
|
||||||
dup.uuid = store.accounts[0].uuid.clone();
|
|
||||||
store.add(dup);
|
|
||||||
assert_eq!(store.accounts.len(), 1);
|
|
||||||
assert_eq!(store.accounts[0].username, "AliceRenamed");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_active_account_none_when_empty() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let store = make_store(tmp.path());
|
|
||||||
assert!(store.active_account().is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_active_account_returns_active() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = make_store(tmp.path());
|
|
||||||
store.add(dummy_account("Alice"));
|
|
||||||
store.add(dummy_account("Bob"));
|
|
||||||
let active = store.active_account().unwrap();
|
|
||||||
assert_eq!(active.username, "Alice");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_set_active_changes_active() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = make_store(tmp.path());
|
|
||||||
store.add(dummy_account("Alice"));
|
|
||||||
store.add(dummy_account("Bob"));
|
|
||||||
store.set_active(1);
|
|
||||||
assert!(!store.accounts[0].active);
|
|
||||||
assert!(store.accounts[1].active);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_remove_activates_first_remaining() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = make_store(tmp.path());
|
|
||||||
store.add(dummy_account("Alice"));
|
|
||||||
store.add(dummy_account("Bob"));
|
|
||||||
store.remove(0);
|
|
||||||
assert_eq!(store.accounts.len(), 1);
|
|
||||||
assert_eq!(store.accounts[0].username, "Bob");
|
|
||||||
assert!(store.accounts[0].active);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_remove_out_of_bounds_noop() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = make_store(tmp.path());
|
|
||||||
store.add(dummy_account("Alice"));
|
|
||||||
store.remove(5);
|
|
||||||
assert_eq!(store.accounts.len(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn store_save_and_reload() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mut store = make_store(tmp.path());
|
|
||||||
store.add(dummy_account("Alice"));
|
|
||||||
store.add(dummy_account("Bob"));
|
|
||||||
store.save();
|
|
||||||
|
|
||||||
let reloaded = AccountStore {
|
|
||||||
accounts: serde_json::from_str(
|
|
||||||
&std::fs::read_to_string(tmp.path().join("accounts.json")).unwrap(),
|
|
||||||
)
|
|
||||||
.unwrap(),
|
|
||||||
path: tmp.path().join("accounts.json"),
|
|
||||||
};
|
|
||||||
assert_eq!(reloaded.accounts.len(), 2);
|
|
||||||
assert_eq!(reloaded.accounts[0].username, "Alice");
|
|
||||||
assert!(reloaded.accounts[0].active);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+6
-4
@@ -1,9 +1,11 @@
|
|||||||
// auth module: account storage (offline + microsoft) and the oauth device code flow
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
mod accounts;
|
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::{DeviceCodeInfo, MicrosoftAuth, refresh_and_get_token, start_microsoft_auth};
|
||||||
+139
-65
@@ -1,8 +1,9 @@
|
|||||||
// microsoft oauth device code flow for minecraft authentication.
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
// the flow goes: MSA device code -> MSA token -> xbox/mc token exchange -> mc profile fetch.
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
// device code auth is used because it works without a redirect URI, which is nice for a TUI.
|
// device code auth is used because it works without a redirect URI, which is nice for a TUI.
|
||||||
|
|
||||||
use std::sync::{Arc, LazyLock, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
use minecraft_msa_auth::MinecraftAuthorizationFlow;
|
use minecraft_msa_auth::MinecraftAuthorizationFlow;
|
||||||
use oauth2::basic::BasicClient;
|
use oauth2::basic::BasicClient;
|
||||||
@@ -14,11 +15,12 @@ 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_REFRESH_MARGIN_SECS: i64 = 5 * 60;
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
pub struct DeviceCodeInfo {
|
pub struct DeviceCodeInfo {
|
||||||
@@ -32,11 +34,29 @@ struct McProfile {
|
|||||||
name: String,
|
name: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
// shared slot so the TUI can poll for the device code to show the user
|
fn normalize_profile_uuid(id: &str) -> Option<String> {
|
||||||
pub static DEVICE_CODE_DISPLAY: LazyLock<Arc<Mutex<Option<DeviceCodeInfo>>>> =
|
(id.len() == 32 && id.bytes().all(|byte| byte.is_ascii_hexdigit())).then(|| {
|
||||||
LazyLock::new(|| Arc::new(Mutex::new(None)));
|
format!(
|
||||||
|
"{}-{}-{}-{}-{}",
|
||||||
|
&id[..8],
|
||||||
|
&id[8..12],
|
||||||
|
&id[12..16],
|
||||||
|
&id[16..20],
|
||||||
|
&id[20..32],
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
|
#[derive(Default)]
|
||||||
|
pub struct MicrosoftAuth {
|
||||||
|
pub result: Arc<Mutex<Option<AuthResult>>>,
|
||||||
|
pub device_code: Arc<Mutex<Option<DeviceCodeInfo>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_full_oauth_flow(
|
||||||
|
http_client: &reqwest::Client,
|
||||||
|
display: &Mutex<Option<DeviceCodeInfo>>,
|
||||||
|
) -> Result<(String, Option<String>), String> {
|
||||||
let oauth_client = BasicClient::new(ClientId::new(CLIENT_ID.to_owned()))
|
let oauth_client = BasicClient::new(ClientId::new(CLIENT_ID.to_owned()))
|
||||||
.set_auth_uri(AuthUrl::new(MSA_AUTHORIZE_URL.to_owned()).map_err(|e| e.to_string())?)
|
.set_auth_uri(AuthUrl::new(MSA_AUTHORIZE_URL.to_owned()).map_err(|e| e.to_string())?)
|
||||||
.set_token_uri(TokenUrl::new(MSA_TOKEN_URL.to_owned()).map_err(|e| e.to_string())?)
|
.set_token_uri(TokenUrl::new(MSA_TOKEN_URL.to_owned()).map_err(|e| e.to_string())?)
|
||||||
@@ -44,26 +64,25 @@ async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
|
|||||||
DeviceAuthorizationUrl::new(DEVICE_CODE_URL.to_owned()).map_err(|e| e.to_string())?,
|
DeviceAuthorizationUrl::new(DEVICE_CODE_URL.to_owned()).map_err(|e| e.to_string())?,
|
||||||
);
|
);
|
||||||
|
|
||||||
let http_client = reqwest::Client::new();
|
|
||||||
|
|
||||||
let details: StandardDeviceAuthorizationResponse = oauth_client
|
let details: StandardDeviceAuthorizationResponse = oauth_client
|
||||||
.exchange_device_code()
|
.exchange_device_code()
|
||||||
.add_scope(Scope::new("XboxLive.signin".to_owned()))
|
.add_scope(Scope::new("XboxLive.signin".to_owned()))
|
||||||
.add_scope(Scope::new("offline_access".to_owned()))
|
.add_scope(Scope::new("offline_access".to_owned()))
|
||||||
.request_async(&http_client)
|
.request_async(http_client)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| format!("Device code request failed: {e}"))?;
|
.map_err(|e| format!("Device code request failed: {e}"))?;
|
||||||
|
|
||||||
if let Ok(mut slot) = DEVICE_CODE_DISPLAY.lock() {
|
if let Ok(mut slot) = display.lock() {
|
||||||
*slot = Some(DeviceCodeInfo {
|
*slot = Some(DeviceCodeInfo {
|
||||||
user_code: details.user_code().secret().to_owned(),
|
user_code: details.user_code().secret().to_owned(),
|
||||||
verification_uri: details.verification_uri().to_string(),
|
verification_uri: details.verification_uri().to_string(),
|
||||||
});
|
});
|
||||||
|
crate::feedback::request_redraw();
|
||||||
}
|
}
|
||||||
|
|
||||||
let token = oauth_client
|
let token = oauth_client
|
||||||
.exchange_device_access_token(&details)
|
.exchange_device_access_token(&details)
|
||||||
.request_async(&http_client, tokio::time::sleep, None)
|
.request_async(http_client, tokio::time::sleep, None)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| format!("Authentication failed: {e}"))?;
|
.map_err(|e| format!("Authentication failed: {e}"))?;
|
||||||
|
|
||||||
@@ -73,76 +92,70 @@ async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
|
|||||||
Ok((ms_access_token, ms_refresh_token))
|
Ok((ms_access_token, ms_refresh_token))
|
||||||
}
|
}
|
||||||
|
|
||||||
// kicks off auth on a background task, returns a mutex the caller can poll for the result.
|
pub fn start_microsoft_auth() -> MicrosoftAuth {
|
||||||
// the TUI checks DEVICE_CODE_DISPLAY for the code to show, and this mutex for completion.
|
let auth = MicrosoftAuth::default();
|
||||||
pub fn start_microsoft_auth() -> Arc<Mutex<Option<AuthResult>>> {
|
let result_clone = auth.result.clone();
|
||||||
let result: Arc<Mutex<Option<AuthResult>>> = Arc::new(Mutex::new(None));
|
let device_code = auth.device_code.clone();
|
||||||
let result_clone = result.clone();
|
|
||||||
|
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let outcome = run_full_auth_flow().await;
|
let outcome = run_full_auth_flow(&device_code).await;
|
||||||
if let Ok(mut slot) = result_clone.lock() {
|
if let Ok(mut slot) = result_clone.lock() {
|
||||||
*slot = Some(outcome);
|
*slot = Some(outcome);
|
||||||
|
crate::feedback::request_redraw();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
result
|
auth
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn run_full_auth_flow() -> AuthResult {
|
async fn run_full_auth_flow(display: &Mutex<Option<DeviceCodeInfo>>) -> AuthResult {
|
||||||
let (ms_access_token, ms_refresh_token) = match run_full_oauth_flow().await {
|
let http_client = match auth_http_client() {
|
||||||
|
Ok(client) => client,
|
||||||
|
Err(error) => return AuthResult::Error(error),
|
||||||
|
};
|
||||||
|
let (ms_access_token, ms_refresh_token) = match run_full_oauth_flow(&http_client, display).await
|
||||||
|
{
|
||||||
Ok(pair) => pair,
|
Ok(pair) => pair,
|
||||||
Err(e) => return AuthResult::Error(e),
|
Err(e) => return AuthResult::Error(e),
|
||||||
};
|
};
|
||||||
|
|
||||||
exchange_and_build_account(&ms_access_token, ms_refresh_token.as_deref()).await
|
let Some(refresh_token) = ms_refresh_token.as_deref() else {
|
||||||
|
return AuthResult::Error(
|
||||||
|
"Microsoft did not return a refresh token; try signing in again".to_owned(),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
exchange_and_build_account(&http_client, &ms_access_token, Some(refresh_token)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn auth_http_client() -> Result<reqwest::Client, String> {
|
||||||
|
reqwest::Client::builder()
|
||||||
|
.connect_timeout(std::time::Duration::from_secs(30))
|
||||||
|
.timeout(std::time::Duration::from_secs(30))
|
||||||
|
.build()
|
||||||
|
.map_err(|error| format!("Could not create authentication HTTP client: {error}"))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn exchange_and_build_account(
|
async fn exchange_and_build_account(
|
||||||
|
client: &reqwest::Client,
|
||||||
ms_access_token: &str,
|
ms_access_token: &str,
|
||||||
ms_refresh_token: Option<&str>,
|
ms_refresh_token: Option<&str>,
|
||||||
) -> AuthResult {
|
) -> AuthResult {
|
||||||
let mc_flow = MinecraftAuthorizationFlow::new(reqwest::Client::new());
|
let mc_flow = MinecraftAuthorizationFlow::new(client.clone());
|
||||||
let mc_token = match mc_flow.exchange_microsoft_token(ms_access_token).await {
|
let mc_token = match mc_flow.exchange_microsoft_token(ms_access_token).await {
|
||||||
Ok(t) => t,
|
Ok(t) => t,
|
||||||
Err(e) => return AuthResult::Error(format!("Minecraft auth failed: {e}")),
|
Err(e) => return AuthResult::Error(format!("Minecraft auth failed: {e}")),
|
||||||
};
|
};
|
||||||
|
|
||||||
let client = reqwest::Client::new();
|
let profile =
|
||||||
let profile_resp = match client
|
match fetch_profile(client, MC_PROFILE_URL, mc_token.access_token().as_ref()).await {
|
||||||
.get(MC_PROFILE_URL)
|
Ok(p) => p,
|
||||||
.header(
|
Err(e) => return AuthResult::Error(e),
|
||||||
"Authorization",
|
};
|
||||||
format!("Bearer {}", mc_token.access_token().as_ref()),
|
|
||||||
)
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(r) => r,
|
|
||||||
Err(e) => return AuthResult::Error(format!("Profile fetch failed: {e}")),
|
|
||||||
};
|
|
||||||
|
|
||||||
if !profile_resp.status().is_success() {
|
// mojang returns uuids without dashes
|
||||||
return AuthResult::Error("Account does not own Minecraft".to_owned());
|
let uuid = match normalize_profile_uuid(&profile.id) {
|
||||||
}
|
Some(uuid) => uuid,
|
||||||
|
None => return AuthResult::Error("Profile returned an invalid UUID".to_owned()),
|
||||||
let profile: McProfile = match profile_resp.json().await {
|
|
||||||
Ok(p) => p,
|
|
||||||
Err(e) => return AuthResult::Error(format!("Profile parse failed: {e}")),
|
|
||||||
};
|
|
||||||
|
|
||||||
// mojang returns uuids without dashes because of course they do
|
|
||||||
let uuid = if profile.id.len() == 32 {
|
|
||||||
format!(
|
|
||||||
"{}-{}-{}-{}-{}",
|
|
||||||
&profile.id[..8],
|
|
||||||
&profile.id[8..12],
|
|
||||||
&profile.id[12..16],
|
|
||||||
&profile.id[16..20],
|
|
||||||
&profile.id[20..32],
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
profile.id.clone()
|
|
||||||
};
|
};
|
||||||
|
|
||||||
AuthResult::Success(Account {
|
AuthResult::Success(Account {
|
||||||
@@ -151,15 +164,66 @@ 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: Some(mc_token.access_token().as_ref().to_owned()),
|
||||||
|
cached_mc_token_expires_at: Some(
|
||||||
|
chrono::Utc::now().timestamp() + i64::from(mc_token.expires_in()),
|
||||||
|
),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// returns (mc_access_token, new_refresh_token). for offline accounts it just
|
async fn fetch_profile(
|
||||||
// hands back a dummy token since the server doesn't care.
|
client: &reqwest::Client,
|
||||||
pub async fn refresh_and_get_token(account: &Account) -> Result<(String, Option<String>), String> {
|
url: &str,
|
||||||
|
token: &str,
|
||||||
|
) -> Result<McProfile, String> {
|
||||||
|
let response = client
|
||||||
|
.get(url)
|
||||||
|
.bearer_auth(token)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("Profile fetch failed: {e}"))?;
|
||||||
|
if response.status() == reqwest::StatusCode::NOT_FOUND {
|
||||||
|
return Err("Account does not own Minecraft".to_owned());
|
||||||
|
}
|
||||||
|
let response = response
|
||||||
|
.error_for_status()
|
||||||
|
.map_err(|e| format!("Profile fetch failed: {e}"))?;
|
||||||
|
response
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("Profile parse failed: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn valid_cached_mc_token(account: &Account, now: i64) -> Option<&str> {
|
||||||
|
let (Some(cached), Some(expires_at)) = (
|
||||||
|
account.cached_mc_token.as_deref(),
|
||||||
|
account.cached_mc_token_expires_at,
|
||||||
|
) else {
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
|
||||||
|
if now < expires_at.saturating_sub(MC_TOKEN_CACHE_REFRESH_MARGIN_SECS) {
|
||||||
|
Some(cached)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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.",
|
||||||
@@ -173,7 +237,7 @@ pub async fn refresh_and_get_token(account: &Account) -> Result<(String, Option<
|
|||||||
)
|
)
|
||||||
.set_token_uri(TokenUrl::new(MSA_TOKEN_URL.to_owned()).map_err(|e| e.to_string())?);
|
.set_token_uri(TokenUrl::new(MSA_TOKEN_URL.to_owned()).map_err(|e| e.to_string())?);
|
||||||
|
|
||||||
let http_client = reqwest::Client::new();
|
let http_client = auth_http_client()?;
|
||||||
|
|
||||||
let token = oauth_client
|
let token = oauth_client
|
||||||
.exchange_refresh_token(&RefreshToken::new(refresh.to_owned()))
|
.exchange_refresh_token(&RefreshToken::new(refresh.to_owned()))
|
||||||
@@ -186,13 +250,23 @@ pub async fn refresh_and_get_token(account: &Account) -> Result<(String, Option<
|
|||||||
let ms_access_token = token.access_token().secret().to_owned();
|
let ms_access_token = token.access_token().secret().to_owned();
|
||||||
let new_refresh = token.refresh_token().map(|r| r.secret().to_owned());
|
let new_refresh = token.refresh_token().map(|r| r.secret().to_owned());
|
||||||
|
|
||||||
let mc_flow = MinecraftAuthorizationFlow::new(reqwest::Client::new());
|
let mc_flow = MinecraftAuthorizationFlow::new(http_client);
|
||||||
let mc_token = mc_flow
|
let mc_token = mc_flow
|
||||||
.exchange_microsoft_token(&ms_access_token)
|
.exchange_microsoft_token(&ms_access_token)
|
||||||
.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))
|
let expires_at = chrono::Utc::now().timestamp() + i64::from(mc_token.expires_in());
|
||||||
|
|
||||||
|
Ok((
|
||||||
|
mc_token.access_token().as_ref().to_owned(),
|
||||||
|
new_refresh,
|
||||||
|
Some(expires_at),
|
||||||
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "tests/oauth.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,286 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
impl AccountStore {
|
||||||
|
pub(crate) fn empty_for_test(path: PathBuf) -> Self {
|
||||||
|
Self {
|
||||||
|
accounts: Vec::new(),
|
||||||
|
path,
|
||||||
|
load_error: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn offline_uuid_has_valid_v3_shape() {
|
||||||
|
let uuid = offline_uuid("Steve");
|
||||||
|
let parts: Vec<&str> = uuid.split('-').collect();
|
||||||
|
assert_eq!(parts.len(), 5, "UUID must have 5 dash-separated parts");
|
||||||
|
assert_eq!(parts[0].len(), 8);
|
||||||
|
assert_eq!(parts[1].len(), 4);
|
||||||
|
assert_eq!(parts[2].len(), 4);
|
||||||
|
assert_eq!(parts[3].len(), 4);
|
||||||
|
assert_eq!(parts[4].len(), 12);
|
||||||
|
assert!(parts[2].starts_with('3'));
|
||||||
|
let first_nibble = u8::from_str_radix(&parts[3][..1], 16).unwrap();
|
||||||
|
assert!((0x8..=0xb).contains(&first_nibble));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn offline_uuid_is_pinned_for_known_names() {
|
||||||
|
assert_eq!(
|
||||||
|
offline_uuid("Steve"),
|
||||||
|
"7e0a3689-ed7c-347c-87cc-3689ed7c47cc"
|
||||||
|
);
|
||||||
|
assert_eq!(offline_uuid("Alex"), "a13d42a3-454f-3e39-a392-42a3454fe392");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn offline_uuid_different_for_different_names() {
|
||||||
|
assert_ne!(offline_uuid("Steve"), offline_uuid("Alex"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn create_offline_account_fields() {
|
||||||
|
let acc = create_offline_account("TestPlayer");
|
||||||
|
assert_eq!(acc.username, "TestPlayer");
|
||||||
|
assert_eq!(acc.account_type, AccountType::Offline);
|
||||||
|
assert!(!acc.active);
|
||||||
|
assert!(acc.refresh_token.is_none());
|
||||||
|
assert_eq!(acc.uuid, offline_uuid("TestPlayer"));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn make_store(dir: &std::path::Path) -> AccountStore {
|
||||||
|
AccountStore {
|
||||||
|
accounts: Vec::new(),
|
||||||
|
path: dir.join("accounts.json"),
|
||||||
|
load_error: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn microsoft_account(name: &str) -> Account {
|
||||||
|
Account {
|
||||||
|
uuid: format!("00000000-0000-0000-0000-{:012}", name.len()),
|
||||||
|
username: name.to_owned(),
|
||||||
|
account_type: AccountType::Microsoft,
|
||||||
|
active: false,
|
||||||
|
refresh_token: Some("refresh".to_owned()),
|
||||||
|
cached_mc_token: None,
|
||||||
|
cached_mc_token_expires_at: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_add_first_becomes_active() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = make_store(tmp.path());
|
||||||
|
store.add(create_offline_account("Alice")).unwrap();
|
||||||
|
assert_eq!(store.accounts.len(), 1);
|
||||||
|
assert!(store.accounts[0].active);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_add_second_stays_inactive() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = make_store(tmp.path());
|
||||||
|
store.add(create_offline_account("Alice")).unwrap();
|
||||||
|
store.add(create_offline_account("Bob")).unwrap();
|
||||||
|
assert_eq!(store.accounts.len(), 2);
|
||||||
|
assert!(store.accounts[0].active);
|
||||||
|
assert!(!store.accounts[1].active);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_add_duplicate_uuid_replaces() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = make_store(tmp.path());
|
||||||
|
store.add(create_offline_account("Alice")).unwrap();
|
||||||
|
let mut dup = create_offline_account("Alice");
|
||||||
|
dup.username = "AliceRenamed".to_owned();
|
||||||
|
dup.uuid = store.accounts[0].uuid.clone();
|
||||||
|
store.add(dup).unwrap();
|
||||||
|
assert_eq!(store.accounts.len(), 1);
|
||||||
|
assert_eq!(store.accounts[0].username, "AliceRenamed");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_active_account_none_when_empty() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let store = make_store(tmp.path());
|
||||||
|
assert!(store.active_account().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_has_microsoft_account_when_one_exists() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = make_store(tmp.path());
|
||||||
|
store.add(create_offline_account("Offline")).unwrap();
|
||||||
|
assert!(!store.has_microsoft_account());
|
||||||
|
|
||||||
|
store.add(microsoft_account("Owner")).unwrap();
|
||||||
|
assert!(store.has_microsoft_account());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_active_account_returns_active() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = make_store(tmp.path());
|
||||||
|
store.add(create_offline_account("Alice")).unwrap();
|
||||||
|
store.add(create_offline_account("Bob")).unwrap();
|
||||||
|
let active = store.active_account().unwrap();
|
||||||
|
assert_eq!(active.username, "Alice");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_set_active_changes_active() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = make_store(tmp.path());
|
||||||
|
store.add(create_offline_account("Alice")).unwrap();
|
||||||
|
store.add(create_offline_account("Bob")).unwrap();
|
||||||
|
store.set_active(1).unwrap();
|
||||||
|
assert!(!store.accounts[0].active);
|
||||||
|
assert!(store.accounts[1].active);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_set_active_out_of_bounds_keeps_selection() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = make_store(tmp.path());
|
||||||
|
store.add(create_offline_account("Alice")).unwrap();
|
||||||
|
store.add(create_offline_account("Bob")).unwrap();
|
||||||
|
store.set_active(99).unwrap();
|
||||||
|
assert!(
|
||||||
|
store.accounts[0].active,
|
||||||
|
"existing selection must survive a bad index"
|
||||||
|
);
|
||||||
|
assert!(!store.accounts[1].active);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_add_replacing_active_keeps_active() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = make_store(tmp.path());
|
||||||
|
store.add(create_offline_account("Alice")).unwrap();
|
||||||
|
store.add(create_offline_account("Bob")).unwrap();
|
||||||
|
let mut dup = create_offline_account("Alice");
|
||||||
|
dup.username = "AliceRenamed".to_owned();
|
||||||
|
store.add(dup).unwrap();
|
||||||
|
assert!(
|
||||||
|
store.accounts.iter().any(|a| a.active),
|
||||||
|
"re-adding the active account must not orphan the selection"
|
||||||
|
);
|
||||||
|
let active = store.active_account().unwrap();
|
||||||
|
assert_eq!(active.username, "AliceRenamed");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_remove_activates_first_remaining() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = make_store(tmp.path());
|
||||||
|
store.add(create_offline_account("Alice")).unwrap();
|
||||||
|
store.add(create_offline_account("Bob")).unwrap();
|
||||||
|
store.remove(0).unwrap();
|
||||||
|
assert_eq!(store.accounts.len(), 1);
|
||||||
|
assert_eq!(store.accounts[0].username, "Bob");
|
||||||
|
assert!(store.accounts[0].active);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_remove_out_of_bounds_noop() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = make_store(tmp.path());
|
||||||
|
store.add(create_offline_account("Alice")).unwrap();
|
||||||
|
store.remove(5).unwrap();
|
||||||
|
assert_eq!(store.accounts.len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn store_save_and_reload() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = make_store(tmp.path());
|
||||||
|
store.add(create_offline_account("Alice")).unwrap();
|
||||||
|
store.add(create_offline_account("Bob")).unwrap();
|
||||||
|
store.save().unwrap();
|
||||||
|
|
||||||
|
let reloaded = AccountStore {
|
||||||
|
accounts: serde_json::from_str(
|
||||||
|
&std::fs::read_to_string(tmp.path().join("accounts.json")).unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
path: tmp.path().join("accounts.json"),
|
||||||
|
load_error: None,
|
||||||
|
};
|
||||||
|
assert_eq!(reloaded.accounts.len(), 2);
|
||||||
|
assert_eq!(reloaded.accounts[0].username, "Alice");
|
||||||
|
assert!(reloaded.accounts[0].active);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn account_file_remains_owner_only_after_replacement() {
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = make_store(tmp.path());
|
||||||
|
store.add(microsoft_account("Owner")).unwrap();
|
||||||
|
let path = tmp.path().join("accounts.json");
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
|
||||||
|
0o600
|
||||||
|
);
|
||||||
|
|
||||||
|
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
|
||||||
|
store.add(create_offline_account("Player")).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::metadata(path).unwrap().permissions().mode() & 0o777,
|
||||||
|
0o600
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_account_file_cannot_be_overwritten_by_a_new_account() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let path = tmp.path().join("accounts.json");
|
||||||
|
std::fs::write(&path, b"{broken credentials").unwrap();
|
||||||
|
let mut store = AccountStore::load_from(path.clone());
|
||||||
|
assert!(store.check_loaded().is_err());
|
||||||
|
|
||||||
|
assert!(store.add(microsoft_account("Owner")).is_err());
|
||||||
|
assert!(store.accounts.is_empty());
|
||||||
|
assert_eq!(std::fs::read(path).unwrap(), b"{broken credentials");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stale_account_mutations_preserve_new_credentials_and_selection() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let mut first = make_store(tmp.path());
|
||||||
|
first.add(microsoft_account("Owner")).unwrap();
|
||||||
|
first.add(create_offline_account("Player")).unwrap();
|
||||||
|
let mut stale = AccountStore::load_from(first.path.clone());
|
||||||
|
let uuid = first.accounts[0].uuid.clone();
|
||||||
|
first
|
||||||
|
.update_credentials(
|
||||||
|
&uuid,
|
||||||
|
Some("new-refresh".to_owned()),
|
||||||
|
"new-token",
|
||||||
|
Some(12345),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
first.add(create_offline_account("New")).unwrap();
|
||||||
|
stale.set_active(1).unwrap();
|
||||||
|
assert_eq!(stale.accounts.len(), 3);
|
||||||
|
assert_eq!(
|
||||||
|
stale.accounts[0].refresh_token.as_deref(),
|
||||||
|
Some("new-refresh")
|
||||||
|
);
|
||||||
|
first
|
||||||
|
.update_credentials(&uuid, None, "newer-token", Some(23456))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(first.active_account().unwrap().username, "Player");
|
||||||
|
assert_eq!(
|
||||||
|
first.accounts[0].cached_mc_token.as_deref(),
|
||||||
|
Some("newer-token")
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn profile_status_errors_and_stalls_are_reported_accurately() {
|
||||||
|
use wiremock::{Mock, MockServer, ResponseTemplate, matchers::path};
|
||||||
|
let server = MockServer::start().await;
|
||||||
|
let client = reqwest::Client::builder()
|
||||||
|
.read_timeout(std::time::Duration::from_millis(30))
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
for status in [404, 401, 429, 503] {
|
||||||
|
let route = format!("/{status}");
|
||||||
|
Mock::given(path(&route))
|
||||||
|
.respond_with(ResponseTemplate::new(status))
|
||||||
|
.mount(&server)
|
||||||
|
.await;
|
||||||
|
let error = fetch_profile(&client, &format!("{}{route}", server.uri()), "test")
|
||||||
|
.await
|
||||||
|
.err()
|
||||||
|
.unwrap();
|
||||||
|
if status == 404 {
|
||||||
|
assert!(error.contains("does not own"));
|
||||||
|
} else {
|
||||||
|
assert!(error.contains(&status.to_string()));
|
||||||
|
assert!(!error.contains("does not own"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Mock::given(path("/stall"))
|
||||||
|
.respond_with(ResponseTemplate::new(200).set_delay(std::time::Duration::from_secs(1)))
|
||||||
|
.mount(&server)
|
||||||
|
.await;
|
||||||
|
assert!(
|
||||||
|
fetch_profile(&client, &format!("{}/stall", server.uri()), "test")
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn microsoft_account(cached_mc_token_expires_at: Option<i64>) -> Account {
|
||||||
|
Account {
|
||||||
|
uuid: "00000000-0000-0000-0000-000000000000".to_owned(),
|
||||||
|
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());
|
||||||
|
assert!(valid_cached_mc_token(µsoft_account(Some(i64::MIN)), now).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cached_mc_token_requires_expiry() {
|
||||||
|
let account = microsoft_account(None);
|
||||||
|
|
||||||
|
assert!(valid_cached_mc_token(&account, 1_000).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn profile_uuid_is_normalized_without_slicing_unicode() {
|
||||||
|
assert_eq!(
|
||||||
|
normalize_profile_uuid("0123456789abcdef0123456789abcdef"),
|
||||||
|
Some("01234567-89ab-cdef-0123-456789abcdef".to_owned())
|
||||||
|
);
|
||||||
|
|
||||||
|
let unicode_id = format!("{}é{}", "a".repeat(7), "b".repeat(23));
|
||||||
|
assert_eq!(unicode_id.len(), 32);
|
||||||
|
assert_eq!(normalize_profile_uuid(&unicode_id), None);
|
||||||
|
assert_eq!(
|
||||||
|
normalize_profile_uuid("not-a-valid-minecraft-profile-id"),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
}
|
||||||
+73
-95
@@ -1,4 +1,6 @@
|
|||||||
// cli handlers for account management (microsoft oauth + offline accounts)
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
@@ -19,24 +21,9 @@ pub async fn handle_account(matches: &ArgMatches) -> CliResult {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// trait indirection so a mock store can be swapped in for tests
|
|
||||||
trait AccountStoreLike {
|
|
||||||
fn accounts(&self) -> &[Account];
|
|
||||||
fn add_account(&mut self, account: Account);
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AccountStoreLike for AccountStore {
|
|
||||||
fn accounts(&self) -> &[Account] {
|
|
||||||
&self.accounts
|
|
||||||
}
|
|
||||||
|
|
||||||
fn add_account(&mut self, account: Account) {
|
|
||||||
self.add(account);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn list_accounts() -> CliResult {
|
fn list_accounts() -> CliResult {
|
||||||
let store = AccountStore::load();
|
let store = AccountStore::load();
|
||||||
|
store.check_loaded()?;
|
||||||
let rows = store
|
let rows = store
|
||||||
.accounts
|
.accounts
|
||||||
.iter()
|
.iter()
|
||||||
@@ -45,11 +32,12 @@ fn list_accounts() -> CliResult {
|
|||||||
active_marker(account.active).to_string(),
|
active_marker(account.active).to_string(),
|
||||||
account.username.clone(),
|
account.username.clone(),
|
||||||
format!("{:?}", account.account_type),
|
format!("{:?}", account.account_type),
|
||||||
|
account.uuid.clone(),
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
print_table(&[" ", "Username", "Type"], &rows);
|
print_table(&[" ", "Username", "Type", "UUID"], &rows);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,68 +55,78 @@ async fn add_account(matches: &ArgMatches) -> CliResult {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
// microsoft auth runs on a background thread via device code flow.
|
|
||||||
// polls two shared slots: one for the device code to display,
|
|
||||||
// then one for the final auth result. not the prettiest pattern
|
|
||||||
// but it keeps the oauth complexity out of the CLI layer.
|
|
||||||
async fn add_microsoft_account() -> CliResult {
|
async fn add_microsoft_account() -> CliResult {
|
||||||
if let Ok(mut slot) = crate::auth::DEVICE_CODE_DISPLAY.lock() {
|
|
||||||
*slot = None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let result_arc = crate::auth::start_microsoft_auth();
|
let result_arc = crate::auth::start_microsoft_auth();
|
||||||
|
|
||||||
// wait for the device code to become available before showing it
|
let info = wait_for_device_code(&result_arc).await?;
|
||||||
loop {
|
println!("Open: {}", info.verification_uri);
|
||||||
if let Ok(slot) = crate::auth::DEVICE_CODE_DISPLAY.lock()
|
println!("Code: {}", info.user_code);
|
||||||
&& let Some(info) = slot.as_ref() {
|
|
||||||
println!("Open: {}", info.verification_uri);
|
|
||||||
println!("Code: {}", info.user_code);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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.result.lock()
|
||||||
&& let Some(result) = slot.as_ref() {
|
&& let Some(result) = slot.as_ref()
|
||||||
return match result {
|
{
|
||||||
AuthResult::Success(account) => {
|
return match result {
|
||||||
let mut store = AccountStore::load();
|
AuthResult::Success(account) => {
|
||||||
store.add(account.clone());
|
let mut store = AccountStore::load();
|
||||||
println!("Added Microsoft account '{}'.", account.username);
|
store.add(account.clone())?;
|
||||||
Ok(())
|
println!("Added Microsoft account '{}'.", account.username);
|
||||||
}
|
Ok(())
|
||||||
AuthResult::Error(message) => Err(io::Error::other(message.clone()).into()),
|
}
|
||||||
};
|
AuthResult::Error(message) => Err(io::Error::other(message.clone()).into()),
|
||||||
}
|
};
|
||||||
|
}
|
||||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_offline_account<T: AccountStoreLike>(store: &mut T, username: &str) -> CliResult {
|
async fn wait_for_device_code(
|
||||||
|
result: &crate::auth::MicrosoftAuth,
|
||||||
|
) -> io::Result<crate::auth::DeviceCodeInfo> {
|
||||||
|
loop {
|
||||||
|
if let Ok(slot) = result.device_code.lock()
|
||||||
|
&& let Some(info) = slot.as_ref()
|
||||||
|
{
|
||||||
|
return Ok(info.clone());
|
||||||
|
}
|
||||||
|
if let Ok(slot) = result.result.lock()
|
||||||
|
&& let Some(AuthResult::Error(message)) = slot.as_ref()
|
||||||
|
{
|
||||||
|
return Err(io::Error::other(message.clone()));
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_offline_account(store: &mut AccountStore, username: &str) -> CliResult {
|
||||||
|
store.check_loaded()?;
|
||||||
let username = username.trim();
|
let username = username.trim();
|
||||||
if username.is_empty() {
|
if username.is_empty() {
|
||||||
return Err(io::Error::other("offline username cannot be empty").into());
|
return Err(io::Error::other("offline username cannot be empty").into());
|
||||||
}
|
}
|
||||||
|
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(crate::auth::create_offline_account(username))?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
store.check_loaded()?;
|
||||||
.ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?;
|
let index = find_account_index(&store.accounts, username)?;
|
||||||
|
|
||||||
if !matches.get_flag("yes") && !confirm(&format!("Delete '{}'", username))? {
|
if !matches.get_flag("yes") && !confirm(&format!("Delete '{}'", username))? {
|
||||||
println!("Cancelled.");
|
println!("Cancelled.");
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
store.remove(index);
|
store.remove(index)?;
|
||||||
println!("Deleted '{}'.", username);
|
println!("Deleted '{}'.", username);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -136,54 +134,34 @@ 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)
|
store.check_loaded()?;
|
||||||
.ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?;
|
let index = find_account_index(&store.accounts, username)?;
|
||||||
store.set_active(index);
|
store.set_active(index)?;
|
||||||
println!("Active account set to '{}'.", username);
|
println!("Active account set to '{}'.", username);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn find_account_index(accounts: &[Account], username: &str) -> Option<usize> {
|
fn find_account_index(accounts: &[Account], selector: &str) -> io::Result<usize> {
|
||||||
accounts
|
if let Some(index) = accounts.iter().position(|account| account.uuid == selector) {
|
||||||
|
return Ok(index);
|
||||||
|
}
|
||||||
|
let mut matches = accounts
|
||||||
.iter()
|
.iter()
|
||||||
.position(|account| account.username.eq_ignore_ascii_case(username))
|
.enumerate()
|
||||||
|
.filter(|(_, account)| account.username.eq_ignore_ascii_case(selector));
|
||||||
|
let (index, _) = matches
|
||||||
|
.next()
|
||||||
|
.ok_or_else(|| io::Error::other(format!("account '{selector}' not found")))?;
|
||||||
|
if matches.next().is_some() {
|
||||||
|
return Err(io::Error::other(format!(
|
||||||
|
"Account '{selector}' is ambiguous; use its UUID"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(index)
|
||||||
}
|
}
|
||||||
|
|
||||||
use super::utils::{confirm, required_arg};
|
use super::utils::{confirm, required_arg};
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/account.rs"]
|
||||||
use super::{add_offline_account, AccountStoreLike};
|
mod tests;
|
||||||
use crate::auth::{Account, AccountType};
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
struct MockStore {
|
|
||||||
accounts: Vec<Account>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AccountStoreLike for MockStore {
|
|
||||||
fn accounts(&self) -> &[Account] {
|
|
||||||
&self.accounts
|
|
||||||
}
|
|
||||||
|
|
||||||
fn add_account(&mut self, account: Account) {
|
|
||||||
self.accounts.push(account);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn creates_offline_account_through_store() {
|
|
||||||
let mut store = MockStore::default();
|
|
||||||
add_offline_account(&mut store, "Steve").expect("offline account should be added");
|
|
||||||
|
|
||||||
assert_eq!(store.accounts.len(), 1);
|
|
||||||
assert_eq!(store.accounts[0].username, "Steve");
|
|
||||||
assert_eq!(store.accounts[0].account_type, AccountType::Offline);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_empty_offline_username() {
|
|
||||||
let mut store = MockStore::default();
|
|
||||||
assert!(add_offline_account(&mut store, " ").is_err());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+27
-41
@@ -1,6 +1,6 @@
|
|||||||
// unified content management for mods, resource packs, and shaders.
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
// all three content types share the same list/enable/disable workflow,
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
// just with different scanner functions plugged in.
|
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
@@ -8,7 +8,7 @@ use clap::ArgMatches;
|
|||||||
|
|
||||||
use super::utils::{require_instance, required_arg};
|
use super::utils::{require_instance, required_arg};
|
||||||
use crate::cli::output::print_table;
|
use crate::cli::output::print_table;
|
||||||
use crate::instance::ContentEntry;
|
use crate::instance::content::entry::ContentEntry;
|
||||||
|
|
||||||
type CliResult = Result<(), Box<dyn std::error::Error>>;
|
type CliResult = Result<(), Box<dyn std::error::Error>>;
|
||||||
type Scanner = fn(&Path, &str) -> Vec<ContentEntry>;
|
type Scanner = fn(&Path, &str) -> Vec<ContentEntry>;
|
||||||
@@ -58,14 +58,28 @@ fn handle_content(matches: &ArgMatches, kind: &str, scan: Scanner) -> CliResult
|
|||||||
pub(crate) fn find_entry_by_stem<'a>(
|
pub(crate) fn find_entry_by_stem<'a>(
|
||||||
entries: &'a [ContentEntry],
|
entries: &'a [ContentEntry],
|
||||||
target: &str,
|
target: &str,
|
||||||
) -> Option<&'a ContentEntry> {
|
) -> io::Result<Option<&'a ContentEntry>> {
|
||||||
entries
|
let exact = entries
|
||||||
.iter()
|
.iter()
|
||||||
.find(|entry| entry.file_stem.eq_ignore_ascii_case(target))
|
.any(|entry| entry.path.file_name().is_some_and(|name| name == target));
|
||||||
|
let mut matches = entries.iter().filter(|entry| {
|
||||||
|
if exact {
|
||||||
|
entry.path.file_name().is_some_and(|name| name == target)
|
||||||
|
} else {
|
||||||
|
entry.file_stem.eq_ignore_ascii_case(target)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let found = matches.next();
|
||||||
|
if matches.next().is_some() {
|
||||||
|
return Err(io::Error::other(format!(
|
||||||
|
"Content selector '{target}' is ambiguous; use its filename"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(found)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_entries(instance: &str, scan: Scanner) -> CliResult {
|
fn list_entries(instance: &str, scan: Scanner) -> CliResult {
|
||||||
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
|
let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
|
||||||
require_instance(&instances_dir, instance)?;
|
require_instance(&instances_dir, instance)?;
|
||||||
let rows = scan(&instances_dir, instance)
|
let rows = scan(&instances_dir, instance)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -92,10 +106,10 @@ fn toggle_entry(
|
|||||||
kind: &str,
|
kind: &str,
|
||||||
scan: Scanner,
|
scan: Scanner,
|
||||||
) -> CliResult {
|
) -> CliResult {
|
||||||
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
|
let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
|
||||||
require_instance(&instances_dir, instance)?;
|
require_instance(&instances_dir, instance)?;
|
||||||
let entries = scan(&instances_dir, instance);
|
let entries = scan(&instances_dir, instance);
|
||||||
let entry = find_entry_by_stem(&entries, target)
|
let entry = find_entry_by_stem(&entries, target)?
|
||||||
.ok_or_else(|| io::Error::other(format!("{} '{}' not found", kind, target)))?;
|
.ok_or_else(|| io::Error::other(format!("{} '{}' not found", kind, target)))?;
|
||||||
|
|
||||||
if entry.enabled == should_enable {
|
if entry.enabled == should_enable {
|
||||||
@@ -106,7 +120,7 @@ fn toggle_entry(
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
crate::instance::content::mods::toggle_entry(entry)?;
|
crate::instance::content::entry::toggle_entry(entry)?;
|
||||||
println!(
|
println!(
|
||||||
"{}d '{}'.",
|
"{}d '{}'.",
|
||||||
if should_enable { "Enable" } else { "Disable" },
|
if should_enable { "Enable" } else { "Disable" },
|
||||||
@@ -116,33 +130,5 @@ fn toggle_entry(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/content.rs"]
|
||||||
use super::find_entry_by_stem;
|
mod tests;
|
||||||
use crate::instance::ContentEntry;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
fn entry(file_stem: &str) -> ContentEntry {
|
|
||||||
ContentEntry {
|
|
||||||
file_stem: file_stem.to_string(),
|
|
||||||
name: file_stem.to_string(),
|
|
||||||
description: String::new(),
|
|
||||||
enabled: true,
|
|
||||||
icon_bytes: None,
|
|
||||||
path: PathBuf::from(file_stem),
|
|
||||||
icon_lines: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn matches_by_stem_case_insensitively() {
|
|
||||||
let entries = vec![entry("Sodium"), entry("Lithium")];
|
|
||||||
let found = find_entry_by_stem(&entries, "sOdIuM").expect("entry should match");
|
|
||||||
assert_eq!(found.file_stem, "Sodium");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn returns_none_for_missing_stem() {
|
|
||||||
let entries = vec![entry("Sodium")];
|
|
||||||
assert!(find_entry_by_stem(&entries, "iris").is_none());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+41
-30
@@ -1,34 +1,36 @@
|
|||||||
// modpack importing from modrinth (remote slug/url) or local .mrpack files.
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
// resolves the input, downloads if needed, then hands off to the import engine.
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
use clap::ArgMatches;
|
use clap::ArgMatches;
|
||||||
|
|
||||||
|
use super::utils::required_arg;
|
||||||
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>>;
|
||||||
|
|
||||||
pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
||||||
let input = matches.get_one::<String>("source").unwrap();
|
let input = required_arg(matches, "source")?;
|
||||||
let override_name = matches.get_one::<String>("name");
|
let override_name = matches.get_one::<String>("name");
|
||||||
let override_version = matches.get_one::<String>("version");
|
let override_version = matches.get_one::<String>("version");
|
||||||
|
|
||||||
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
|
let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
|
||||||
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
|
let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir();
|
||||||
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
|
||||||
@@ -39,18 +41,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
|||||||
.await
|
.await
|
||||||
.map_err(|e| format!("Failed to fetch versions: {e}"))?;
|
.map_err(|e| format!("Failed to fetch versions: {e}"))?;
|
||||||
|
|
||||||
if versions.is_empty() {
|
let version = select_version(&versions, override_version.map(String::as_str))?;
|
||||||
return Err("No versions found for this modpack".into());
|
|
||||||
}
|
|
||||||
|
|
||||||
let version = if let Some(version_name) = override_version {
|
|
||||||
versions
|
|
||||||
.iter()
|
|
||||||
.find(|v| v.version_number == *version_name || v.name == *version_name)
|
|
||||||
.ok_or_else(|| format!("Version '{version_name}' not found"))?
|
|
||||||
} else {
|
|
||||||
&versions[0]
|
|
||||||
};
|
|
||||||
|
|
||||||
println!(
|
println!(
|
||||||
"Using version {} ({})",
|
"Using version {} ({})",
|
||||||
@@ -58,13 +49,13 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
|||||||
version.game_versions.first().unwrap_or(&"?".to_string())
|
version.game_versions.first().unwrap_or(&"?".to_string())
|
||||||
);
|
);
|
||||||
|
|
||||||
let tmp_dir = manager.meta_dir.join("tmp");
|
let tmp_dir = crate::storage::MetadataPaths::new(&manager.meta_dir).temporary();
|
||||||
std::fs::create_dir_all(&tmp_dir)?;
|
std::fs::create_dir_all(&tmp_dir)?;
|
||||||
modrinth::download_mrpack(&client, version, &tmp_dir)
|
modrinth::download_mrpack(&client, version, &tmp_dir)
|
||||||
.await
|
.await
|
||||||
.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,
|
||||||
} => {
|
} => {
|
||||||
@@ -79,7 +70,7 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
|||||||
version.game_versions.first().unwrap_or(&"?".to_string())
|
version.game_versions.first().unwrap_or(&"?".to_string())
|
||||||
);
|
);
|
||||||
|
|
||||||
let tmp_dir = manager.meta_dir.join("tmp");
|
let tmp_dir = crate::storage::MetadataPaths::new(&manager.meta_dir).temporary();
|
||||||
std::fs::create_dir_all(&tmp_dir)?;
|
std::fs::create_dir_all(&tmp_dir)?;
|
||||||
modrinth::download_mrpack(&client, &version, &tmp_dir)
|
modrinth::download_mrpack(&client, &version, &tmp_dir)
|
||||||
.await
|
.await
|
||||||
@@ -87,10 +78,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 +86,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,
|
||||||
@@ -113,3 +101,26 @@ pub async fn handle_import(matches: &ArgMatches) -> CliResult {
|
|||||||
println!("Instance '{}' created successfully.", config.name);
|
println!("Instance '{}' created successfully.", config.name);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn select_version<'a>(
|
||||||
|
versions: &'a [modrinth::VersionInfo],
|
||||||
|
requested: Option<&str>,
|
||||||
|
) -> Result<&'a modrinth::VersionInfo, String> {
|
||||||
|
requested.map_or_else(
|
||||||
|
|| {
|
||||||
|
versions
|
||||||
|
.first()
|
||||||
|
.ok_or_else(|| "No versions found for this modpack".to_owned())
|
||||||
|
},
|
||||||
|
|name| {
|
||||||
|
versions
|
||||||
|
.iter()
|
||||||
|
.find(|version| version.version_number == name || version.name == name)
|
||||||
|
.ok_or_else(|| format!("Version '{name}' not found"))
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "tests/import.rs"]
|
||||||
|
mod tests;
|
||||||
+88
-64
@@ -1,5 +1,6 @@
|
|||||||
// instance lifecycle: create, delete, rename, launch, config, desktop shortcuts.
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
// the heaviest handler in the CLI since instances are the core concept.
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
@@ -7,10 +8,11 @@ use clap::ArgMatches;
|
|||||||
|
|
||||||
use super::utils::{confirm, required_arg};
|
use super::utils::{confirm, required_arg};
|
||||||
use crate::cli::output::{format_datetime, print_table};
|
use crate::cli::output::{format_datetime, print_table};
|
||||||
use crate::instance::{InstanceManager, ModLoader};
|
use crate::instance::runtime::RunState;
|
||||||
use crate::running::RunState;
|
use crate::instance::{InstanceManager, ModLoader, models::parse_resolution};
|
||||||
|
|
||||||
type CliResult = Result<(), Box<dyn std::error::Error>>;
|
type CliResult = Result<(), Box<dyn std::error::Error>>;
|
||||||
|
const LOCAL_CONFIG_PROFILE: &str = "instance default";
|
||||||
|
|
||||||
pub async fn handle_instance(matches: &ArgMatches) -> CliResult {
|
pub async fn handle_instance(matches: &ArgMatches) -> CliResult {
|
||||||
match matches.subcommand() {
|
match matches.subcommand() {
|
||||||
@@ -20,6 +22,7 @@ pub async fn handle_instance(matches: &ArgMatches) -> CliResult {
|
|||||||
Some(("rename", sub_matches)) => rename_instance(sub_matches),
|
Some(("rename", sub_matches)) => rename_instance(sub_matches),
|
||||||
Some(("launch", sub_matches)) => launch_instance(sub_matches).await,
|
Some(("launch", sub_matches)) => launch_instance(sub_matches).await,
|
||||||
Some(("config", sub_matches)) => config_instance(sub_matches),
|
Some(("config", sub_matches)) => config_instance(sub_matches),
|
||||||
|
Some(("profile", sub_matches)) => profile_instance(sub_matches, &manager()),
|
||||||
Some(("desktop", sub_matches)) => desktop_instance(sub_matches),
|
Some(("desktop", sub_matches)) => desktop_instance(sub_matches),
|
||||||
_ => Ok(()),
|
_ => Ok(()),
|
||||||
}
|
}
|
||||||
@@ -39,33 +42,15 @@ pub(crate) fn parse_loader(input: &str) -> Result<ModLoader, String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn parse_resolution(input: &str) -> Result<(u32, u32), String> {
|
|
||||||
let (width, height) = input
|
|
||||||
.split_once('x')
|
|
||||||
.ok_or_else(|| "resolution must be in WxH format".to_string())?;
|
|
||||||
let width = width
|
|
||||||
.parse::<u32>()
|
|
||||||
.map_err(|_| "resolution width must be a positive integer".to_string())?;
|
|
||||||
let height = height
|
|
||||||
.parse::<u32>()
|
|
||||||
.map_err(|_| "resolution height must be a positive integer".to_string())?;
|
|
||||||
|
|
||||||
if width == 0 || height == 0 {
|
|
||||||
return Err("resolution values must be greater than zero".to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok((width, height))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn manager() -> InstanceManager {
|
fn manager() -> InstanceManager {
|
||||||
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
|
let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
|
||||||
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
|
let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir();
|
||||||
InstanceManager::new(instances_dir, meta_dir)
|
InstanceManager::new(instances_dir, meta_dir)
|
||||||
}
|
}
|
||||||
|
|
||||||
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()
|
||||||
@@ -130,30 +115,26 @@ fn rename_instance(matches: &ArgMatches) -> CliResult {
|
|||||||
async fn launch_instance(matches: &ArgMatches) -> CliResult {
|
async fn launch_instance(matches: &ArgMatches) -> CliResult {
|
||||||
let name = required_arg(matches, "name")?;
|
let name = required_arg(matches, "name")?;
|
||||||
let manager = manager();
|
let manager = manager();
|
||||||
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
|
let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
|
||||||
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
|
let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir();
|
||||||
let config = manager.load_one(name)?;
|
let config = manager.load_one(name)?;
|
||||||
|
|
||||||
println!("Launching '{}'...", name);
|
crate::instance::launch::launch(&config, &instances_dir, &meta_dir, None)
|
||||||
crate::instance::launch::launch(&config, &instances_dir, &meta_dir)
|
|
||||||
.await
|
.await
|
||||||
.map_err(|error| io::Error::other(format!("Launch failed: {}", error)))?;
|
.map_err(|error| io::Error::other(format!("Launch failed: {}", error)))?;
|
||||||
|
|
||||||
// poll until the game process exits. in CLI mode this blocks here
|
// poll until the game process exits. in CLI mode this blocks here
|
||||||
// so the user gets a proper exit code at the end.
|
// so the user gets a proper exit code at the end.
|
||||||
loop {
|
loop {
|
||||||
match crate::running::get(name) {
|
match crate::instance::runtime::get(name) {
|
||||||
Some(RunState::Crashed(Some(code))) => {
|
Some(RunState::Crashed(Some(code))) => {
|
||||||
println!("Game exited with status {}.", code);
|
return Err(io::Error::other(format!("Game exited with status {code}")).into());
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
Some(RunState::Crashed(None)) => {
|
Some(RunState::Crashed(None)) => {
|
||||||
println!("Game was terminated.");
|
return Err(io::Error::other("Game was terminated without an exit code").into());
|
||||||
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -225,7 +206,7 @@ fn config_instance(matches: &ArgMatches) -> CliResult {
|
|||||||
if config.jvm_args.is_empty() {
|
if config.jvm_args.is_empty() {
|
||||||
"-".to_string()
|
"-".to_string()
|
||||||
} else {
|
} else {
|
||||||
config.jvm_args.join(" ")
|
crate::config::settings::format_tag_values(&config.jvm_args)
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
vec![
|
vec![
|
||||||
@@ -235,12 +216,68 @@ fn config_instance(matches: &ArgMatches) -> CliResult {
|
|||||||
.map(|(width, height)| format!("{}x{}", width, height))
|
.map(|(width, height)| format!("{}x{}", width, height))
|
||||||
.unwrap_or_else(|| "-".to_string()),
|
.unwrap_or_else(|| "-".to_string()),
|
||||||
],
|
],
|
||||||
|
vec![
|
||||||
|
"config-sync-profile".to_string(),
|
||||||
|
display_config_profile(config.config_sync_profile.as_deref()).to_string(),
|
||||||
|
],
|
||||||
];
|
];
|
||||||
|
|
||||||
print_table(&["Field", "Value"], &rows);
|
print_table(&["Field", "Value"], &rows);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn profile_instance(matches: &ArgMatches, manager: &InstanceManager) -> CliResult {
|
||||||
|
let name = required_arg(matches, "name")?;
|
||||||
|
let mut config = manager.load_one(name)?;
|
||||||
|
let profiles = crate::instance::config_sync::list_profiles(&manager.meta_dir)?;
|
||||||
|
|
||||||
|
let Some(profile) = matches.get_one::<String>("profile") else {
|
||||||
|
let rows = vec![
|
||||||
|
vec![
|
||||||
|
"current".to_string(),
|
||||||
|
display_config_profile(config.config_sync_profile.as_deref()).to_string(),
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
"available".to_string(),
|
||||||
|
if profiles.is_empty() {
|
||||||
|
LOCAL_CONFIG_PROFILE.to_string()
|
||||||
|
} else {
|
||||||
|
format!("{}, {}", LOCAL_CONFIG_PROFILE, profiles.join(", "))
|
||||||
|
},
|
||||||
|
],
|
||||||
|
];
|
||||||
|
print_table(&["Field", "Value"], &rows);
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
|
||||||
|
let target = if is_local_profile_alias(profile) {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(profile.as_str())
|
||||||
|
};
|
||||||
|
crate::instance::config_sync::switch_profile_and_save(manager, &mut config, target)?;
|
||||||
|
|
||||||
|
println!(
|
||||||
|
"Updated '{}' config profile to {}.",
|
||||||
|
name,
|
||||||
|
display_config_profile(config.config_sync_profile.as_deref())
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn display_config_profile(profile: Option<&str>) -> &str {
|
||||||
|
profile.unwrap_or(LOCAL_CONFIG_PROFILE)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_local_profile_alias(profile: &str) -> bool {
|
||||||
|
let profile = profile.trim();
|
||||||
|
profile.eq_ignore_ascii_case("none")
|
||||||
|
|| profile.eq_ignore_ascii_case("default")
|
||||||
|
|| profile.eq_ignore_ascii_case("local")
|
||||||
|
|| profile.eq_ignore_ascii_case("instance-default")
|
||||||
|
|| profile.eq_ignore_ascii_case("instance default")
|
||||||
|
}
|
||||||
|
|
||||||
// maps --set key=value pairs to config fields. empty value = clear the field.
|
// maps --set key=value pairs to config fields. empty value = clear the field.
|
||||||
fn apply_config_update(
|
fn apply_config_update(
|
||||||
config: &mut crate::instance::InstanceConfig,
|
config: &mut crate::instance::InstanceConfig,
|
||||||
@@ -249,18 +286,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 = parse_memory_update(value)?;
|
||||||
None
|
|
||||||
} else {
|
|
||||||
Some(value.to_string())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
"memory-min" => {
|
"memory-min" => {
|
||||||
config.memory_min = if value.is_empty() {
|
config.memory_min = parse_memory_update(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() {
|
||||||
@@ -270,7 +299,8 @@ fn apply_config_update(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
"jvm-args" => {
|
"jvm-args" => {
|
||||||
config.jvm_args = value.split_whitespace().map(String::from).collect();
|
config.jvm_args =
|
||||||
|
crate::config::settings::parse_tag_values(value).map_err(io::Error::other)?;
|
||||||
}
|
}
|
||||||
"resolution" => {
|
"resolution" => {
|
||||||
config.resolution = if value.is_empty() {
|
config.resolution = if value.is_empty() {
|
||||||
@@ -287,22 +317,16 @@ fn apply_config_update(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
fn parse_memory_update(value: &str) -> Result<Option<String>, io::Error> {
|
||||||
mod tests {
|
if value.is_empty() {
|
||||||
use super::parse_resolution;
|
Ok(None)
|
||||||
|
} else {
|
||||||
#[test]
|
crate::instance::normalize_memory_value(value)
|
||||||
fn parses_valid_resolution() {
|
.map(Some)
|
||||||
assert_eq!(
|
.ok_or_else(|| io::Error::other(format!("invalid memory size '{value}'")))
|
||||||
parse_resolution("1920x1080").expect("should parse"),
|
|
||||||
(1920, 1080)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rejects_invalid_resolution_format() {
|
|
||||||
assert!(parse_resolution("1920").is_err());
|
|
||||||
assert!(parse_resolution("1920xa").is_err());
|
|
||||||
assert!(parse_resolution("0x1080").is_err());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "tests/instance.rs"]
|
||||||
|
mod tests;
|
||||||
+57
-78
@@ -1,4 +1,6 @@
|
|||||||
// viewing minecraft log files from the CLI, with optional `--follow` for tailing
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@@ -18,9 +20,9 @@ pub async fn handle_log(matches: &ArgMatches) -> CliResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn list_logs(instance: &str) -> CliResult {
|
fn list_logs(instance: &str) -> CliResult {
|
||||||
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
|
let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
|
||||||
require_instance(&instances_dir, instance)?;
|
require_instance(&instances_dir, instance)?;
|
||||||
let rows = crate::instance::log_files::scan_log_files(&instances_dir, instance)
|
let rows = crate::instance::logs::files::scan_log_files(&instances_dir, instance)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|entry| {
|
.map(|entry| {
|
||||||
let size = std::fs::metadata(&entry.path)
|
let size = std::fs::metadata(&entry.path)
|
||||||
@@ -38,100 +40,77 @@ async fn show_log(matches: &ArgMatches) -> CliResult {
|
|||||||
let instance = required_arg(matches, "instance")?;
|
let instance = required_arg(matches, "instance")?;
|
||||||
let file = matches.get_one::<String>("file").map(String::as_str);
|
let file = matches.get_one::<String>("file").map(String::as_str);
|
||||||
let follow = matches.get_flag("follow");
|
let follow = matches.get_flag("follow");
|
||||||
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
|
let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
|
||||||
require_instance(&instances_dir, instance)?;
|
require_instance(&instances_dir, instance)?;
|
||||||
let path = resolve_log_path(&instances_dir, instance, file)?;
|
let path = resolve_log_path(&instances_dir, instance, file)?;
|
||||||
|
|
||||||
let lines = crate::instance::log_files::read_log_file(&path);
|
|
||||||
for line in &lines {
|
|
||||||
println!("{}", line);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ghetto tail -f: re-read the whole file and print new lines.
|
|
||||||
// not efficient, but log files are small and this is simple.
|
|
||||||
if follow {
|
if follow {
|
||||||
let mut last_len = lines.len();
|
use std::io::Write;
|
||||||
loop {
|
if path.extension().is_some_and(|extension| extension == "gz") {
|
||||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
return Err(io::Error::other("Cannot follow a compressed log").into());
|
||||||
let new_lines = crate::instance::log_files::read_log_file(&path);
|
|
||||||
for line in new_lines.iter().skip(last_len) {
|
|
||||||
println!("{}", line);
|
|
||||||
}
|
|
||||||
last_len = new_lines.len();
|
|
||||||
}
|
}
|
||||||
|
let mut offset = 0;
|
||||||
|
loop {
|
||||||
|
{
|
||||||
|
let bytes = read_new_log_bytes(&path, &mut offset)?;
|
||||||
|
let mut output = io::stdout().lock();
|
||||||
|
output.write_all(&bytes)?;
|
||||||
|
output.flush()?;
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for line in crate::instance::logs::files::read_log_file(&path) {
|
||||||
|
println!("{line}");
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
// if no file is specified, grab the most recent log (first from the sorted scan)
|
fn read_new_log_bytes(path: &Path, offset: &mut u64) -> io::Result<Vec<u8>> {
|
||||||
|
use std::io::{Read, Seek};
|
||||||
|
let mut file = std::fs::File::open(path)?;
|
||||||
|
if file.metadata()?.len() < *offset {
|
||||||
|
*offset = 0;
|
||||||
|
}
|
||||||
|
file.seek(io::SeekFrom::Start(*offset))?;
|
||||||
|
let mut bytes = Vec::new();
|
||||||
|
file.read_to_end(&mut bytes)?;
|
||||||
|
*offset += bytes.len() as u64;
|
||||||
|
Ok(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn resolve_log_path(
|
pub(crate) fn resolve_log_path(
|
||||||
instances_dir: &Path,
|
instances_dir: &Path,
|
||||||
instance: &str,
|
instance: &str,
|
||||||
file: Option<&str>,
|
file: Option<&str>,
|
||||||
) -> Result<PathBuf, io::Error> {
|
) -> Result<PathBuf, io::Error> {
|
||||||
if let Some(name) = file {
|
let log_dir = crate::instance::logs::files::log_dir(instances_dir, instance);
|
||||||
let path = crate::instance::log_files::log_dir(instances_dir, instance).join(name);
|
let path = if let Some(name) = file {
|
||||||
if !path.exists() {
|
let filename = Path::new(name);
|
||||||
return Err(io::Error::other(format!("log '{}' not found", name)));
|
if !crate::storage::safe_relative_path(filename) || filename.components().count() != 1 {
|
||||||
|
return Err(io::Error::other("log file must be a single filename"));
|
||||||
}
|
}
|
||||||
return Ok(path);
|
log_dir.join(filename)
|
||||||
|
} else {
|
||||||
|
crate::instance::logs::files::scan_log_files(instances_dir, instance)
|
||||||
|
.into_iter()
|
||||||
|
.next()
|
||||||
|
.map(|entry| entry.path)
|
||||||
|
.ok_or_else(|| io::Error::other(format!("no log files found for '{}'", instance)))?
|
||||||
|
};
|
||||||
|
let log_dir = std::fs::canonicalize(log_dir)?;
|
||||||
|
let path = std::fs::canonicalize(path)?;
|
||||||
|
if path.parent() != Some(log_dir.as_path()) || !path.is_file() {
|
||||||
|
return Err(io::Error::other(
|
||||||
|
"log file is outside the instance log directory",
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
Ok(path)
|
||||||
crate::instance::log_files::scan_log_files(instances_dir, instance)
|
|
||||||
.into_iter()
|
|
||||||
.next()
|
|
||||||
.map(|entry| entry.path)
|
|
||||||
.ok_or_else(|| io::Error::other(format!("no log files found for '{}'", instance)))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
use super::utils::{require_instance, required_arg};
|
use super::utils::{require_instance, required_arg};
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/log.rs"]
|
||||||
use super::resolve_log_path;
|
mod tests;
|
||||||
|
|
||||||
fn unique_temp_dir() -> std::path::PathBuf {
|
|
||||||
std::env::temp_dir().join(format!(
|
|
||||||
"mcl_cli_log_test_{}",
|
|
||||||
std::time::SystemTime::now()
|
|
||||||
.duration_since(std::time::UNIX_EPOCH)
|
|
||||||
.expect("time should work")
|
|
||||||
.as_nanos()
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolves_latest_log_when_no_file_is_given() {
|
|
||||||
let root = unique_temp_dir();
|
|
||||||
let dir = root.join("demo/.minecraft/logs/launches");
|
|
||||||
std::fs::create_dir_all(&dir).expect("log directory should exist");
|
|
||||||
std::fs::write(dir.join("2024-01-02_03-04-05.log"), "newer").expect("write newer log");
|
|
||||||
std::fs::write(dir.join("2024-01-01_03-04-05.log"), "older").expect("write older log");
|
|
||||||
|
|
||||||
let path = resolve_log_path(&root, "demo", None).expect("latest log should resolve");
|
|
||||||
assert_eq!(
|
|
||||||
path.file_name().and_then(|name| name.to_str()),
|
|
||||||
Some("2024-01-02_03-04-05.log")
|
|
||||||
);
|
|
||||||
|
|
||||||
let _ = std::fs::remove_dir_all(&root);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolves_named_log_file() {
|
|
||||||
let root = unique_temp_dir();
|
|
||||||
let dir = root.join("demo/.minecraft/logs/launches");
|
|
||||||
std::fs::create_dir_all(&dir).expect("log directory should exist");
|
|
||||||
std::fs::write(dir.join("latest.log"), "hello").expect("write named log");
|
|
||||||
|
|
||||||
let path =
|
|
||||||
resolve_log_path(&root, "demo", Some("latest.log")).expect("named log should resolve");
|
|
||||||
assert_eq!(
|
|
||||||
path.file_name().and_then(|name| name.to_str()),
|
|
||||||
Some("latest.log")
|
|
||||||
);
|
|
||||||
|
|
||||||
let _ = std::fs::remove_dir_all(&root);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+59
-17
@@ -1,5 +1,6 @@
|
|||||||
// cli entry point and clap command definitions.
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
// no subcommand = launch TUI, otherwise dispatch to the appropriate handler.
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
mod account;
|
mod account;
|
||||||
mod content;
|
mod content;
|
||||||
mod import;
|
mod import;
|
||||||
@@ -14,9 +15,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
|
|
||||||
if matches.subcommand().is_none() {
|
if matches.subcommand().is_none() {
|
||||||
// force-init the theme so it's ready before the TUI renders
|
|
||||||
let _ = &*crate::config::theme::THEME;
|
let _ = &*crate::config::theme::THEME;
|
||||||
if let Err(e) = crate::tui::show().await {
|
if let Err(e) = crate::tui::show().await {
|
||||||
tracing::error!("TUI error: {}", e);
|
tracing::error!("TUI error: {}", e);
|
||||||
@@ -24,6 +23,52 @@ pub async fn init() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !matches!(matches.subcommand_name(), Some("account" | "version")) {
|
||||||
|
let instances_dir = crate::config::SETTINGS.read().paths.resolve_instances_dir();
|
||||||
|
let meta_dir = crate::config::SETTINGS.read().paths.resolve_meta_dir();
|
||||||
|
let config = crate::config::get_config_path().join("config.toml");
|
||||||
|
if crate::layout_migration::is_needed(&instances_dir, &meta_dir) {
|
||||||
|
if let Err(error) =
|
||||||
|
crate::layout_migration::run(&instances_dir, &meta_dir, &config, |progress| {
|
||||||
|
eprintln!(
|
||||||
|
"{}: {} ({}/{})",
|
||||||
|
progress.phase, progress.item, progress.current, progress.total
|
||||||
|
);
|
||||||
|
})
|
||||||
|
{
|
||||||
|
eprintln!("error: layout migration failed safely: {error}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
} else if let Err(error) = crate::layout_migration::initialize_new_layout(&meta_dir) {
|
||||||
|
eprintln!("error: cannot initialize metadata layout: {error}");
|
||||||
|
std::process::exit(1);
|
||||||
|
} else if let Err(error) = crate::config::upgrade_config_file(&config) {
|
||||||
|
eprintln!("warning: cannot upgrade launcher config: {error}");
|
||||||
|
}
|
||||||
|
if crate::layout_migration::cache_rebuild_pending(&meta_dir) {
|
||||||
|
let manager = crate::instance::InstanceManager::new(&instances_dir, &meta_dir);
|
||||||
|
let instances = manager.load_all();
|
||||||
|
for (index, instance) in instances.iter().enumerate() {
|
||||||
|
eprintln!(
|
||||||
|
"Rebuilding runtime cache: {} ({}/{})",
|
||||||
|
instance.name,
|
||||||
|
index + 1,
|
||||||
|
instances.len()
|
||||||
|
);
|
||||||
|
if let Err(error) = manager.repair_runtime_cache(instance).await {
|
||||||
|
eprintln!(
|
||||||
|
"error: runtime cache rebuild stopped safely for '{}': {error}",
|
||||||
|
instance.name
|
||||||
|
);
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Err(error) = crate::layout_migration::finish_cache_rebuild(&meta_dir) {
|
||||||
|
eprintln!("error: cannot finish runtime cache migration: {error}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
let result = match matches.subcommand() {
|
let result = match matches.subcommand() {
|
||||||
Some(("instance", sub_matches)) => instance::handle_instance(sub_matches).await,
|
Some(("instance", sub_matches)) => instance::handle_instance(sub_matches).await,
|
||||||
Some(("mod", sub_matches)) => content::handle_mod(sub_matches),
|
Some(("mod", sub_matches)) => content::handle_mod(sub_matches),
|
||||||
@@ -43,7 +88,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)
|
||||||
@@ -104,6 +149,13 @@ fn build_command() -> Command {
|
|||||||
.arg(Arg::new("name").required(true).action(ArgAction::Set))
|
.arg(Arg::new("name").required(true).action(ArgAction::Set))
|
||||||
.arg(Arg::new("set").long("set").action(ArgAction::Set)),
|
.arg(Arg::new("set").long("set").action(ArgAction::Set)),
|
||||||
)
|
)
|
||||||
|
.subcommand(
|
||||||
|
Command::new("profile")
|
||||||
|
.about("Show or set an instance config-sync profile")
|
||||||
|
.arg_required_else_help(true)
|
||||||
|
.arg(Arg::new("name").required(true).action(ArgAction::Set))
|
||||||
|
.arg(Arg::new("profile").action(ArgAction::Set)),
|
||||||
|
)
|
||||||
.subcommand(
|
.subcommand(
|
||||||
Command::new("desktop")
|
Command::new("desktop")
|
||||||
.about("Toggle desktop shortcut for an instance")
|
.about("Toggle desktop shortcut for an instance")
|
||||||
@@ -210,7 +262,6 @@ fn build_command() -> Command {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// mods, resource packs, and shaders all share the same list/enable/disable shape
|
|
||||||
fn build_content_command(name: &'static str, about: &'static str) -> Command {
|
fn build_content_command(name: &'static str, about: &'static str) -> Command {
|
||||||
Command::new(name)
|
Command::new(name)
|
||||||
.about(format!("Manage {}", about))
|
.about(format!("Manage {}", about))
|
||||||
@@ -239,14 +290,5 @@ fn build_content_command(name: &'static str, about: &'static str) -> Command {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/arguments.rs"]
|
||||||
use super::build_command;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parses_instance_list_subcommand() {
|
|
||||||
let matches = build_command()
|
|
||||||
.try_get_matches_from(["mcl", "instance", "list"])
|
|
||||||
.expect("command should parse");
|
|
||||||
assert!(matches.subcommand_matches("instance").is_some());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+18
-42
@@ -1,6 +1,8 @@
|
|||||||
// plain-text table rendering for CLI output. no fancy box-drawing,
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
// just left-aligned columns with two-space gaps. keeps it pipeable.
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
|
use ratatui::text::Span;
|
||||||
|
|
||||||
pub fn print_table(headers: &[&str], rows: &[Vec<String>]) {
|
pub fn print_table(headers: &[&str], rows: &[Vec<String>]) {
|
||||||
print!("{}", render_table(headers, rows));
|
print!("{}", render_table(headers, rows));
|
||||||
@@ -34,16 +36,15 @@ 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 {
|
|
||||||
" "
|
fn display_width(value: &str) -> usize {
|
||||||
}
|
Span::raw(value).width()
|
||||||
}
|
}
|
||||||
|
|
||||||
// find the widest value in each column to pad everything evenly
|
|
||||||
fn column_widths(headers: &[&str], rows: &[Vec<String>]) -> Vec<usize> {
|
fn column_widths(headers: &[&str], rows: &[Vec<String>]) -> Vec<usize> {
|
||||||
let mut widths: Vec<usize> = headers.iter().map(|header| header.len()).collect();
|
let mut widths: Vec<usize> = headers.iter().map(|header| display_width(header)).collect();
|
||||||
|
|
||||||
for row in rows {
|
for row in rows {
|
||||||
if row.len() > widths.len() {
|
if row.len() > widths.len() {
|
||||||
@@ -51,7 +52,7 @@ fn column_widths(headers: &[&str], rows: &[Vec<String>]) -> Vec<usize> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (index, value) in row.iter().enumerate() {
|
for (index, value) in row.iter().enumerate() {
|
||||||
widths[index] = widths[index].max(value.len());
|
widths[index] = widths[index].max(display_width(value));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,11 +64,11 @@ fn render_row(row: &[String], widths: &[usize]) -> String {
|
|||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.map(|(index, width)| {
|
.map(|(index, width)| {
|
||||||
format!(
|
// Rust's width formatter counts characters rather than terminal cells.
|
||||||
"{:<width$}",
|
let value = row.get(index).map(String::as_str).unwrap_or("");
|
||||||
row.get(index).map(String::as_str).unwrap_or(""),
|
let mut cell = String::from(value);
|
||||||
width = width
|
cell.push_str(&" ".repeat(width.saturating_sub(display_width(value))));
|
||||||
)
|
cell
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.join(" ")
|
.join(" ")
|
||||||
@@ -82,30 +83,5 @@ fn render_separator(widths: &[usize]) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/output.rs"]
|
||||||
use super::{format_datetime, render_table};
|
mod tests;
|
||||||
use chrono::{TimeZone, Utc};
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn render_table_aligns_columns() {
|
|
||||||
let rendered = render_table(
|
|
||||||
&["Name", "State"],
|
|
||||||
&[
|
|
||||||
vec!["Alpha".to_string(), "enabled".to_string()],
|
|
||||||
vec!["Longer Name".to_string(), "off".to_string()],
|
|
||||||
],
|
|
||||||
);
|
|
||||||
|
|
||||||
let lines: Vec<&str> = rendered.lines().collect();
|
|
||||||
assert_eq!(lines[0], "Name State ");
|
|
||||||
assert_eq!(lines[1], "----------- -------");
|
|
||||||
assert_eq!(lines[2], "Alpha enabled");
|
|
||||||
assert_eq!(lines[3], "Longer Name off ");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn formats_datetime_consistently() {
|
|
||||||
let dt = Utc.with_ymd_and_hms(2024, 1, 2, 3, 4, 5).unwrap();
|
|
||||||
assert_eq!(format_datetime(&dt), "2024-01-02 03:04:05 UTC");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use super::add_offline_account;
|
||||||
|
use crate::auth::{Account, AccountStore, AccountType};
|
||||||
|
|
||||||
|
fn microsoft_account() -> Account {
|
||||||
|
Account {
|
||||||
|
uuid: "00000000-0000-0000-0000-000000000001".to_owned(),
|
||||||
|
username: "Owner".to_owned(),
|
||||||
|
account_type: AccountType::Microsoft,
|
||||||
|
active: false,
|
||||||
|
refresh_token: Some("refresh".to_owned()),
|
||||||
|
cached_mc_token: None,
|
||||||
|
cached_mc_token_expires_at: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn creates_offline_account_after_microsoft_account_exists() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json"));
|
||||||
|
store.add(microsoft_account()).unwrap();
|
||||||
|
add_offline_account(&mut store, "Steve").expect("offline account should be added");
|
||||||
|
|
||||||
|
assert_eq!(store.accounts.len(), 2);
|
||||||
|
assert_eq!(store.accounts[1].username, "Steve");
|
||||||
|
assert_eq!(store.accounts[1].account_type, AccountType::Offline);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_offline_account_before_microsoft_account_exists() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json"));
|
||||||
|
let err = add_offline_account(&mut store, "Steve")
|
||||||
|
.expect_err("offline account should require a microsoft account");
|
||||||
|
|
||||||
|
assert!(err.to_string().contains("Microsoft account"));
|
||||||
|
assert!(store.accounts.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_empty_offline_username() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json"));
|
||||||
|
assert!(add_offline_account(&mut store, " ").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn duplicate_usernames_require_a_unique_account_selector() {
|
||||||
|
let mut microsoft = microsoft_account();
|
||||||
|
microsoft.username = "Steve".to_owned();
|
||||||
|
let offline = crate::auth::create_offline_account("Steve");
|
||||||
|
let accounts = vec![microsoft, offline.clone()];
|
||||||
|
|
||||||
|
assert!(super::find_account_index(&accounts, "Steve").is_err());
|
||||||
|
assert_eq!(
|
||||||
|
super::find_account_index(&accounts, &offline.uuid).unwrap(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn device_code_failure_does_not_wait_for_a_code() {
|
||||||
|
let _guard = crate::tests::TEST_LOCK
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|error| error.into_inner());
|
||||||
|
let result = crate::auth::MicrosoftAuth::default();
|
||||||
|
*result.result.lock().unwrap() = Some(crate::auth::AuthResult::Error(
|
||||||
|
"device code failed".to_owned(),
|
||||||
|
));
|
||||||
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_time()
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
let error = runtime
|
||||||
|
.block_on(super::wait_for_device_code(&result))
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(error.to_string().contains("device code failed"));
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use super::build_command;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_instance_list_subcommand() {
|
||||||
|
let matches = build_command()
|
||||||
|
.try_get_matches_from(["rmcl", "instance", "list"])
|
||||||
|
.expect("command should parse");
|
||||||
|
let instance = matches
|
||||||
|
.subcommand_matches("instance")
|
||||||
|
.expect("instance subcommand should be present");
|
||||||
|
assert_eq!(
|
||||||
|
instance.subcommand_name(),
|
||||||
|
Some("list"),
|
||||||
|
"instance list should resolve to the list subcommand"
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use super::find_entry_by_stem;
|
||||||
|
use crate::instance::content::entry::ContentEntry;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
fn entry(file_stem: &str) -> ContentEntry {
|
||||||
|
ContentEntry {
|
||||||
|
file_stem: file_stem.to_string(),
|
||||||
|
name: file_stem.to_string(),
|
||||||
|
source_slug: None,
|
||||||
|
installed_path: None,
|
||||||
|
provider_project: None,
|
||||||
|
world_details: None,
|
||||||
|
title_suffix: None,
|
||||||
|
footer_label: None,
|
||||||
|
footer_change: None,
|
||||||
|
description: String::new(),
|
||||||
|
enabled: true,
|
||||||
|
icon_bytes: None,
|
||||||
|
provider_icon: false,
|
||||||
|
provider_description: false,
|
||||||
|
path: PathBuf::from(file_stem),
|
||||||
|
icon_lines: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn matches_by_stem_case_insensitively() {
|
||||||
|
let entries = vec![entry("Sodium"), entry("Lithium")];
|
||||||
|
let found = find_entry_by_stem(&entries, "sOdIuM")
|
||||||
|
.unwrap()
|
||||||
|
.expect("entry should match");
|
||||||
|
assert_eq!(found.file_stem, "Sodium");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn returns_none_for_missing_stem() {
|
||||||
|
let entries = vec![entry("Sodium")];
|
||||||
|
assert!(find_entry_by_stem(&entries, "iris").unwrap().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn colliding_enabled_and_disabled_files_require_an_exact_filename_and_cannot_overwrite() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let mut enabled = entry("same");
|
||||||
|
enabled.path = temp.path().join("same.jar");
|
||||||
|
let mut disabled = enabled.clone();
|
||||||
|
disabled.enabled = false;
|
||||||
|
disabled.path = temp.path().join("same.jar.disabled");
|
||||||
|
std::fs::write(&enabled.path, b"enabled").unwrap();
|
||||||
|
std::fs::write(&disabled.path, b"disabled").unwrap();
|
||||||
|
let entries = [enabled, disabled];
|
||||||
|
assert!(find_entry_by_stem(&entries, "same").is_err());
|
||||||
|
assert!(
|
||||||
|
!find_entry_by_stem(&entries, "same.jar.disabled")
|
||||||
|
.unwrap()
|
||||||
|
.unwrap()
|
||||||
|
.enabled
|
||||||
|
);
|
||||||
|
for entry in &entries {
|
||||||
|
assert!(crate::instance::content::entry::toggle_entry(entry).is_err());
|
||||||
|
}
|
||||||
|
assert_eq!(std::fs::read(&entries[0].path).unwrap(), b"enabled");
|
||||||
|
assert_eq!(std::fs::read(&entries[1].path).unwrap(), b"disabled");
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn version(name: &str, number: &str) -> modrinth::VersionInfo {
|
||||||
|
modrinth::VersionInfo {
|
||||||
|
id: number.to_owned(),
|
||||||
|
project_id: "project".to_owned(),
|
||||||
|
name: name.to_owned(),
|
||||||
|
version_number: number.to_owned(),
|
||||||
|
game_versions: vec!["1.21.1".to_owned()],
|
||||||
|
loaders: vec!["fabric".to_owned()],
|
||||||
|
version_type: modrinth::VersionType::Release,
|
||||||
|
dependencies: Vec::new(),
|
||||||
|
date_published: String::new(),
|
||||||
|
files: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn version_override_matches_name_or_number_and_rejects_unknown_values() {
|
||||||
|
let versions = vec![version("Stable", "1.0.0"), version("Beta", "2.0.0-beta")];
|
||||||
|
|
||||||
|
assert_eq!(select_version(&versions, None).unwrap().name, "Stable");
|
||||||
|
assert_eq!(
|
||||||
|
select_version(&versions, Some("Beta"))
|
||||||
|
.unwrap()
|
||||||
|
.version_number,
|
||||||
|
"2.0.0-beta"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
select_version(&versions, Some("1.0.0")).unwrap().name,
|
||||||
|
"Stable"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
select_version(&versions, Some("missing")).unwrap_err(),
|
||||||
|
"Version 'missing' not found"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn import_command_parses_name_and_version_overrides() {
|
||||||
|
let matches = crate::cli::build_command()
|
||||||
|
.try_get_matches_from([
|
||||||
|
"rmcl",
|
||||||
|
"import",
|
||||||
|
"example-pack",
|
||||||
|
"--name",
|
||||||
|
"Example",
|
||||||
|
"--version",
|
||||||
|
"1.2.3",
|
||||||
|
])
|
||||||
|
.unwrap();
|
||||||
|
let import = matches.subcommand_matches("import").unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
import.get_one::<String>("source").map(String::as_str),
|
||||||
|
Some("example-pack")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
import.get_one::<String>("name").map(String::as_str),
|
||||||
|
Some("Example")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
import.get_one::<String>("version").map(String::as_str),
|
||||||
|
Some("1.2.3")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn missing_local_pack_returns_a_file_not_found_error() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let missing = temp.path().join("missing.mrpack");
|
||||||
|
let source = missing.to_string_lossy().into_owned();
|
||||||
|
let matches = crate::cli::build_command()
|
||||||
|
.try_get_matches_from(["rmcl", "import", &source])
|
||||||
|
.unwrap();
|
||||||
|
let import = matches.subcommand_matches("import").unwrap();
|
||||||
|
|
||||||
|
let error = handle_import(import).await.unwrap_err().to_string();
|
||||||
|
|
||||||
|
assert_eq!(error, format!("File not found: {}", missing.display()));
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use super::parse_resolution;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_valid_resolution() {
|
||||||
|
assert_eq!(
|
||||||
|
parse_resolution("1920x1080").expect("should parse"),
|
||||||
|
(1920, 1080)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_invalid_resolution_format() {
|
||||||
|
assert!(parse_resolution("1920").is_err());
|
||||||
|
assert!(parse_resolution("1920xa").is_err());
|
||||||
|
assert!(parse_resolution("0x1080").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_memory_update_keeps_existing_setting() {
|
||||||
|
let mut config: crate::instance::InstanceConfig = serde_json::from_value(serde_json::json!({
|
||||||
|
"name": "test", "game_version": "1.21.1", "loader": "vanilla",
|
||||||
|
"loader_version": null, "created": "2026-01-01T00:00:00Z", "memory_max": "8G"
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert!(super::apply_config_update(&mut config, "memory-max", "garbage").is_err());
|
||||||
|
assert_eq!(config.memory_max.as_deref(), Some("8G"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn jvm_argument_updates_preserve_quoted_paths_and_repeated_options() {
|
||||||
|
let mut config: crate::instance::InstanceConfig = serde_json::from_value(serde_json::json!({
|
||||||
|
"name": "test", "game_version": "1.21.1", "loader": "vanilla",
|
||||||
|
"loader_version": null, "created": "2026-01-01T00:00:00Z"
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
super::apply_config_update(&mut config, "jvm-args", r#""-Dpath=C:\Program Files\Java" --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED"#).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
config.jvm_args,
|
||||||
|
[
|
||||||
|
r"-Dpath=C:\Program Files\Java",
|
||||||
|
"--add-opens",
|
||||||
|
"java.base/java.lang=ALL-UNNAMED",
|
||||||
|
"--add-opens",
|
||||||
|
"java.base/java.util=ALL-UNNAMED"
|
||||||
|
]
|
||||||
|
);
|
||||||
|
let previous = config.jvm_args.clone();
|
||||||
|
assert!(super::apply_config_update(&mut config, "jvm-args", "\"unterminated").is_err());
|
||||||
|
assert_eq!(config.jvm_args, previous);
|
||||||
|
super::apply_config_update(&mut config, "jvm-args", "").unwrap();
|
||||||
|
assert!(config.jvm_args.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_sync_profile_display_is_read_only_and_deleted_profiles_restore_local_defaults() {
|
||||||
|
for target in ["default", "other"] {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let manager = crate::instance::InstanceManager::new(
|
||||||
|
tmp.path().join("instances"),
|
||||||
|
tmp.path().join("meta"),
|
||||||
|
);
|
||||||
|
let instance = manager.instances_dir.join("inst");
|
||||||
|
let minecraft = crate::storage::InstancePaths::new(&instance).minecraft();
|
||||||
|
std::fs::create_dir_all(minecraft.join("config")).unwrap();
|
||||||
|
std::fs::write(minecraft.join("options.txt"), b"local-default").unwrap();
|
||||||
|
std::fs::write(minecraft.join("config/value"), b"local-default").unwrap();
|
||||||
|
let mut config = serde_json::from_value(serde_json::json!({
|
||||||
|
"name": "inst", "game_version": "1.21.1", "loader": "vanilla", "loader_version": null,
|
||||||
|
"created": "2026-01-01T00:00:00Z"
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
manager.save(&config).unwrap();
|
||||||
|
crate::instance::config_sync::switch_profile_and_save(&manager, &mut config, Some("main"))
|
||||||
|
.unwrap();
|
||||||
|
std::fs::write(minecraft.join("options.txt"), b"profile-options").unwrap();
|
||||||
|
crate::instance::config_sync::delete_profile(&manager.meta_dir, "main").unwrap();
|
||||||
|
crate::instance::config_sync::create_profile(&manager.meta_dir, "other").unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
crate::storage::MetadataPaths::new(&manager.meta_dir)
|
||||||
|
.profiles()
|
||||||
|
.join("other/options.txt"),
|
||||||
|
b"other-options",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let original_config = std::fs::read(instance.join("instance.json")).unwrap();
|
||||||
|
let matches = crate::cli::build_command()
|
||||||
|
.try_get_matches_from(["rmcl", "instance", "profile", "inst"])
|
||||||
|
.unwrap();
|
||||||
|
let profile_matches = matches
|
||||||
|
.subcommand_matches("instance")
|
||||||
|
.unwrap()
|
||||||
|
.subcommand_matches("profile")
|
||||||
|
.unwrap();
|
||||||
|
super::profile_instance(profile_matches, &manager).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(instance.join("instance.json")).unwrap(),
|
||||||
|
original_config
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(minecraft.join("options.txt")).unwrap(),
|
||||||
|
b"profile-options"
|
||||||
|
);
|
||||||
|
|
||||||
|
let matches = crate::cli::build_command()
|
||||||
|
.try_get_matches_from(["rmcl", "instance", "profile", "inst", target])
|
||||||
|
.unwrap();
|
||||||
|
let profile_matches = matches
|
||||||
|
.subcommand_matches("instance")
|
||||||
|
.unwrap()
|
||||||
|
.subcommand_matches("profile")
|
||||||
|
.unwrap();
|
||||||
|
super::profile_instance(profile_matches, &manager).unwrap();
|
||||||
|
if target == "other" {
|
||||||
|
assert_eq!(
|
||||||
|
manager
|
||||||
|
.load_one("inst")
|
||||||
|
.unwrap()
|
||||||
|
.config_sync_profile
|
||||||
|
.as_deref(),
|
||||||
|
Some("other")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(minecraft.join("options.txt")).unwrap(),
|
||||||
|
b"other-options"
|
||||||
|
);
|
||||||
|
let matches = crate::cli::build_command()
|
||||||
|
.try_get_matches_from(["rmcl", "instance", "profile", "inst", "default"])
|
||||||
|
.unwrap();
|
||||||
|
let profile_matches = matches
|
||||||
|
.subcommand_matches("instance")
|
||||||
|
.unwrap()
|
||||||
|
.subcommand_matches("profile")
|
||||||
|
.unwrap();
|
||||||
|
super::profile_instance(profile_matches, &manager).unwrap();
|
||||||
|
}
|
||||||
|
assert_eq!(manager.load_one("inst").unwrap().config_sync_profile, None);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(minecraft.join("options.txt")).unwrap(),
|
||||||
|
b"local-default"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(minecraft.join("config/value")).unwrap(),
|
||||||
|
b"local-default"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!crate::storage::MetadataPaths::new(&manager.meta_dir)
|
||||||
|
.profiles()
|
||||||
|
.join("main")
|
||||||
|
.exists()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn following_log_bytes_keeps_partial_lines_and_handles_truncation() {
|
||||||
|
use super::read_new_log_bytes;
|
||||||
|
use std::io::Write;
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let path = temp.path().join("latest.log");
|
||||||
|
std::fs::write(&path, b"abc").unwrap();
|
||||||
|
let mut offset = 0;
|
||||||
|
assert_eq!(read_new_log_bytes(&path, &mut offset).unwrap(), b"abc");
|
||||||
|
let mut file = std::fs::OpenOptions::new()
|
||||||
|
.append(true)
|
||||||
|
.open(&path)
|
||||||
|
.unwrap();
|
||||||
|
file.write_all(b"def\nnext\n").unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
read_new_log_bytes(&path, &mut offset).unwrap(),
|
||||||
|
b"def\nnext\n"
|
||||||
|
);
|
||||||
|
assert!(read_new_log_bytes(&path, &mut offset).unwrap().is_empty());
|
||||||
|
std::fs::write(&path, b"new\n").unwrap();
|
||||||
|
assert_eq!(read_new_log_bytes(&path, &mut offset).unwrap(), b"new\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
use super::resolve_log_path;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolves_latest_log_when_no_file_is_given() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = tmp.path().join("demo/minecraft/logs/launches");
|
||||||
|
std::fs::create_dir_all(&dir).expect("log directory should exist");
|
||||||
|
std::fs::write(dir.join("2024-01-02_03-04-05.log"), "newer").expect("write newer log");
|
||||||
|
std::fs::write(dir.join("2024-01-01_03-04-05.log"), "older").expect("write older log");
|
||||||
|
|
||||||
|
let path = resolve_log_path(tmp.path(), "demo", None).expect("latest log should resolve");
|
||||||
|
assert_eq!(
|
||||||
|
path.file_name().and_then(|name| name.to_str()),
|
||||||
|
Some("2024-01-02_03-04-05.log")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolves_named_log_file() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = tmp.path().join("demo/minecraft/logs/launches");
|
||||||
|
std::fs::create_dir_all(&dir).expect("log directory should exist");
|
||||||
|
std::fs::write(dir.join("latest.log"), "hello").expect("write named log");
|
||||||
|
|
||||||
|
let path =
|
||||||
|
resolve_log_path(tmp.path(), "demo", Some("latest.log")).expect("named log should resolve");
|
||||||
|
assert_eq!(
|
||||||
|
path.file_name().and_then(|name| name.to_str()),
|
||||||
|
Some("latest.log")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_log_paths_outside_the_instance() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let dir = tmp.path().join("demo/minecraft/logs/launches");
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
let outside = tmp.path().join("outside.txt");
|
||||||
|
std::fs::write(&outside, "private").unwrap();
|
||||||
|
|
||||||
|
assert!(resolve_log_path(tmp.path(), "demo", Some(outside.to_str().unwrap())).is_err());
|
||||||
|
assert!(resolve_log_path(tmp.path(), "demo", Some("../../outside.txt")).is_err());
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
std::os::unix::fs::symlink(&outside, dir.join("escape.log")).unwrap();
|
||||||
|
assert!(resolve_log_path(tmp.path(), "demo", Some("escape.log")).is_err());
|
||||||
|
assert!(resolve_log_path(tmp.path(), "demo", None).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use super::{format_datetime, render_table};
|
||||||
|
use chrono::{TimeZone, Utc};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_table_aligns_columns() {
|
||||||
|
let rendered = render_table(
|
||||||
|
&["Name", "State"],
|
||||||
|
&[
|
||||||
|
vec!["Alpha".to_string(), "enabled".to_string()],
|
||||||
|
vec!["Longer Name".to_string(), "off".to_string()],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
let lines: Vec<&str> = rendered.lines().collect();
|
||||||
|
assert_eq!(lines[0], "Name State ");
|
||||||
|
assert_eq!(lines[1], "----------- -------");
|
||||||
|
assert_eq!(lines[2], "Alpha enabled");
|
||||||
|
assert_eq!(lines[3], "Longer Name off ");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_table_aligns_multibyte_names() {
|
||||||
|
// padding must use display width, not byte length: "Öctra" is 6 bytes
|
||||||
|
// but 5 columns wide, and byte-based padding pushed every later column.
|
||||||
|
let rendered = render_table(
|
||||||
|
&["Name", "State"],
|
||||||
|
&[
|
||||||
|
vec!["Öctra".to_string(), "enabled".to_string()],
|
||||||
|
vec!["Longer Name".to_string(), "off".to_string()],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
let lines: Vec<&str> = rendered.lines().collect();
|
||||||
|
assert_eq!(lines[0], "Name State ");
|
||||||
|
assert_eq!(lines[2], "Öctra enabled");
|
||||||
|
assert_eq!(lines[3], "Longer Name off ");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn formats_datetime_consistently() {
|
||||||
|
let dt = Utc.with_ymd_and_hms(2024, 1, 2, 3, 4, 5).unwrap();
|
||||||
|
assert_eq!(format_datetime(&dt), "2024-01-02 03:04:05 UTC");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn table_padding_uses_cells_for_wide_and_combining_names() {
|
||||||
|
let table = render_table(
|
||||||
|
&["Name", "State"],
|
||||||
|
&[
|
||||||
|
vec!["界界界".to_owned(), "first".to_owned()],
|
||||||
|
vec!["e\u{301}".to_owned(), "second".to_owned()],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
let rows = table.lines().skip(2).collect::<Vec<_>>();
|
||||||
|
for row in rows {
|
||||||
|
let start = row.find(['f', 's']).unwrap();
|
||||||
|
assert_eq!(ratatui::text::Span::raw(&row[..start]).width(), 8);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use super::filter_manifest_versions;
|
||||||
|
use crate::net::mojang::{LatestVersions, VersionEntry, VersionManifest};
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
fn manifest() -> VersionManifest {
|
||||||
|
VersionManifest {
|
||||||
|
latest: LatestVersions {
|
||||||
|
release: "1.20.1".to_string(),
|
||||||
|
snapshot: "24w01a".to_string(),
|
||||||
|
},
|
||||||
|
versions: vec![
|
||||||
|
VersionEntry {
|
||||||
|
id: "1.20.1".to_string(),
|
||||||
|
version_type: "release".to_string(),
|
||||||
|
url: "https://example.com/release".to_string(),
|
||||||
|
sha1: "a".to_string(),
|
||||||
|
},
|
||||||
|
VersionEntry {
|
||||||
|
id: "24w01a".to_string(),
|
||||||
|
version_type: "snapshot".to_string(),
|
||||||
|
url: "https://example.com/snapshot".to_string(),
|
||||||
|
sha1: "b".to_string(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn filters_out_snapshots_by_default() {
|
||||||
|
let rows = filter_manifest_versions(&manifest(), None, false);
|
||||||
|
assert_eq!(rows.len(), 1);
|
||||||
|
assert_eq!(rows[0].id, "1.20.1");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn intersects_supported_versions() {
|
||||||
|
let supported = HashSet::from(["24w01a".to_string()]);
|
||||||
|
let rows = filter_manifest_versions(&manifest(), Some(&supported), true);
|
||||||
|
assert_eq!(rows.len(), 1);
|
||||||
|
assert_eq!(rows[0].id, "24w01a");
|
||||||
|
}
|
||||||
+5
-3
@@ -1,4 +1,6 @@
|
|||||||
// shared CLI helpers: confirmation prompts, arg extraction, instance validation
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
use std::io::{self, Write};
|
use std::io::{self, Write};
|
||||||
|
|
||||||
use clap::ArgMatches;
|
use clap::ArgMatches;
|
||||||
@@ -18,9 +20,9 @@ pub fn required_arg<'a>(matches: &'a ArgMatches, name: &str) -> Result<&'a str,
|
|||||||
.ok_or_else(|| io::Error::other(format!("missing required argument '{name}'")))
|
.ok_or_else(|| io::Error::other(format!("missing required argument '{name}'")))
|
||||||
}
|
}
|
||||||
|
|
||||||
// checks for instance.json rather than just the directory, since a folder
|
// A directory without instance.json is not an instance.
|
||||||
// without config is just a sad empty directory pretending to be an instance
|
|
||||||
pub fn require_instance(instances_dir: &std::path::Path, name: &str) -> Result<(), io::Error> {
|
pub fn require_instance(instances_dir: &std::path::Path, name: &str) -> Result<(), io::Error> {
|
||||||
|
crate::instance::manager::validate_name(name).map_err(io::Error::other)?;
|
||||||
if !instances_dir.join(name).join("instance.json").exists() {
|
if !instances_dir.join(name).join("instance.json").exists() {
|
||||||
return Err(io::Error::other(format!("Instance '{name}' not found")));
|
return Err(io::Error::other(format!("Instance '{name}' not found")));
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-70
@@ -1,6 +1,6 @@
|
|||||||
// lists available game versions, optionally filtered by mod loader support.
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
// fetches the mojang manifest and cross-references with loader APIs
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
// to show only versions that actually work with a given loader.
|
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::io;
|
use std::io;
|
||||||
|
|
||||||
@@ -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>>;
|
||||||
|
|
||||||
@@ -50,29 +50,12 @@ async fn fetch_supported_versions(
|
|||||||
client: &HttpClient,
|
client: &HttpClient,
|
||||||
loader: ModLoader,
|
loader: ModLoader,
|
||||||
) -> Result<HashSet<String>, Box<dyn std::error::Error>> {
|
) -> Result<HashSet<String>, Box<dyn std::error::Error>> {
|
||||||
let versions: HashSet<String> = match loader {
|
let versions = crate::instance::loader::get_installer(loader)
|
||||||
ModLoader::Vanilla => HashSet::new(),
|
.get_game_versions(client)
|
||||||
ModLoader::Fabric => crate::net::fabric::fetch_fabric_game_versions(client)
|
.await?
|
||||||
.await?
|
.into_iter()
|
||||||
.into_iter()
|
.map(|version| version.id)
|
||||||
.map(|version| version.id)
|
.collect();
|
||||||
.collect::<HashSet<_>>(),
|
|
||||||
ModLoader::Forge => crate::net::forge::fetch_forge_game_versions(client)
|
|
||||||
.await?
|
|
||||||
.into_iter()
|
|
||||||
.map(|version| version.id)
|
|
||||||
.collect::<HashSet<_>>(),
|
|
||||||
ModLoader::NeoForge => crate::net::neoforge::fetch_neoforge_game_versions(client)
|
|
||||||
.await?
|
|
||||||
.into_iter()
|
|
||||||
.map(|version| version.id)
|
|
||||||
.collect::<HashSet<_>>(),
|
|
||||||
ModLoader::Quilt => crate::net::quilt::fetch_quilt_game_versions(client)
|
|
||||||
.await?
|
|
||||||
.into_iter()
|
|
||||||
.map(|version| version.id)
|
|
||||||
.collect::<HashSet<_>>(),
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(versions)
|
Ok(versions)
|
||||||
}
|
}
|
||||||
@@ -96,46 +79,5 @@ fn filter_manifest_versions(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/version.rs"]
|
||||||
use super::filter_manifest_versions;
|
mod tests;
|
||||||
use crate::net::mojang::{LatestVersions, VersionEntry, VersionManifest};
|
|
||||||
use std::collections::HashSet;
|
|
||||||
|
|
||||||
fn manifest() -> VersionManifest {
|
|
||||||
VersionManifest {
|
|
||||||
latest: LatestVersions {
|
|
||||||
release: "1.20.1".to_string(),
|
|
||||||
snapshot: "24w01a".to_string(),
|
|
||||||
},
|
|
||||||
versions: vec![
|
|
||||||
VersionEntry {
|
|
||||||
id: "1.20.1".to_string(),
|
|
||||||
version_type: "release".to_string(),
|
|
||||||
url: "https://example.com/release".to_string(),
|
|
||||||
sha1: "a".to_string(),
|
|
||||||
},
|
|
||||||
VersionEntry {
|
|
||||||
id: "24w01a".to_string(),
|
|
||||||
version_type: "snapshot".to_string(),
|
|
||||||
url: "https://example.com/snapshot".to_string(),
|
|
||||||
sha1: "b".to_string(),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn filters_out_snapshots_by_default() {
|
|
||||||
let rows = filter_manifest_versions(&manifest(), None, false);
|
|
||||||
assert_eq!(rows.len(), 1);
|
|
||||||
assert_eq!(rows[0].id, "1.20.1");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn intersects_supported_versions() {
|
|
||||||
let supported = HashSet::from(["24w01a".to_string()]);
|
|
||||||
let rows = filter_manifest_versions(&manifest(), Some(&supported), true);
|
|
||||||
assert_eq!(rows.len(), 1);
|
|
||||||
assert_eq!(rows[0].id, "24w01a");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+326
-69
@@ -1,10 +1,11 @@
|
|||||||
// config loading: reads config.toml from the platform config dir, creates defaults if missing.
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
// everything lands in the SETTINGS static so the rest of the app can just grab it.
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
use config::{Config as ConfigLoader, ConfigError, File};
|
use config::{Config as ConfigLoader, ConfigError, File};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
|
use std::io;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::LazyLock;
|
use std::sync::{LazyLock, RwLock, RwLockReadGuard};
|
||||||
|
|
||||||
pub mod settings;
|
pub mod settings;
|
||||||
pub mod theme;
|
pub mod theme;
|
||||||
@@ -13,94 +14,350 @@ pub use settings::Config;
|
|||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn get_config_path() -> PathBuf {
|
pub fn get_config_path() -> PathBuf {
|
||||||
dirs_next::config_dir()
|
dirs::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
|
|
||||||
fn ensure_config_exists() -> PathBuf {
|
fn ensure_config_exists() -> PathBuf {
|
||||||
let config_path = get_config_path().join("config.toml");
|
let config_path = get_config_path().join("config.toml");
|
||||||
if !config_path.exists() {
|
if !config_path.exists() {
|
||||||
if let Some(parent) = config_path.parent() {
|
if let Some(parent) = config_path.parent()
|
||||||
let _ = fs::create_dir_all(parent);
|
&& let Err(e) = fs::create_dir_all(parent)
|
||||||
|
{
|
||||||
|
tracing::warn!(
|
||||||
|
"Failed to create config directory {}: {}",
|
||||||
|
parent.display(),
|
||||||
|
e
|
||||||
|
);
|
||||||
}
|
}
|
||||||
let _ = fs::write(&config_path, include_str!("../../assets/config.toml"));
|
match fs::write(&config_path, include_str!("../../assets/config.toml")) {
|
||||||
|
Ok(()) => tracing::debug!("Wrote default config to {}", config_path.display()),
|
||||||
|
Err(e) => tracing::warn!(
|
||||||
|
"Failed to write default config to {}: {}",
|
||||||
|
config_path.display(),
|
||||||
|
e
|
||||||
|
),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
tracing::trace!("Using existing config at {}", config_path.display());
|
||||||
}
|
}
|
||||||
config_path
|
config_path
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn load_config(config_path: &std::path::Path) -> Result<Config, ConfigError> {
|
pub fn load_config(config_path: &std::path::Path) -> Result<Config, ConfigError> {
|
||||||
|
tracing::debug!("Loading config from {}", config_path.display());
|
||||||
ConfigLoader::builder()
|
ConfigLoader::builder()
|
||||||
.add_source(File::from(config_path).required(false))
|
.add_source(File::from(config_path).required(false))
|
||||||
.build()?
|
.build()?
|
||||||
.try_deserialize()
|
.try_deserialize::<Config>()
|
||||||
|
.map(Config::normalize)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub static SETTINGS: LazyLock<Config> = LazyLock::new(|| {
|
pub(crate) fn upgrade_config_file(path: &std::path::Path) -> io::Result<bool> {
|
||||||
let path = ensure_config_exists();
|
let source = match fs::read_to_string(path) {
|
||||||
load_config(&path).unwrap_or_else(|e| {
|
Ok(source) => source,
|
||||||
tracing::error!("Config load failed, using defaults: {}", e);
|
Err(error) if error.kind() == io::ErrorKind::NotFound => {
|
||||||
Config {
|
crate::storage::write_atomic(
|
||||||
general: settings::General::default(),
|
path,
|
||||||
paths: settings::Paths::default(),
|
include_str!("../../assets/config.toml").as_bytes(),
|
||||||
defaults: settings::Defaults::default(),
|
)?;
|
||||||
ui: settings::Ui::default(),
|
return Ok(true);
|
||||||
}
|
}
|
||||||
})
|
Err(error) => return Err(error),
|
||||||
|
};
|
||||||
|
let mut document = parse_toml_document(path, &source)?;
|
||||||
|
let template = include_str!("../../assets/config.toml")
|
||||||
|
.parse::<toml_edit::DocumentMut>()
|
||||||
|
.map_err(io::Error::other)?;
|
||||||
|
merge_missing_table(document.as_table_mut(), template.as_table());
|
||||||
|
let upgraded = document.to_string();
|
||||||
|
toml::from_str::<Config>(&upgraded).map_err(|error| {
|
||||||
|
io::Error::new(
|
||||||
|
io::ErrorKind::InvalidData,
|
||||||
|
format!("cannot upgrade {}: {error}", path.display()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
if upgraded == source {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
crate::storage::write_atomic(path, upgraded.as_bytes())?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn migrate_legacy_data_paths(path: &std::path::Path) -> io::Result<bool> {
|
||||||
|
let Some(data_dir) = dirs::data_dir() else {
|
||||||
|
return Ok(false);
|
||||||
|
};
|
||||||
|
migrate_legacy_data_paths_from(path, &data_dir)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn migrate_legacy_data_paths_from(
|
||||||
|
path: &std::path::Path,
|
||||||
|
data_dir: &std::path::Path,
|
||||||
|
) -> io::Result<bool> {
|
||||||
|
let source = match fs::read_to_string(path) {
|
||||||
|
Ok(source) => source,
|
||||||
|
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
|
||||||
|
Err(error) => return Err(error),
|
||||||
|
};
|
||||||
|
let mut document = parse_toml_document(path, &source)?;
|
||||||
|
let Some(paths) = document
|
||||||
|
.get_mut("paths")
|
||||||
|
.and_then(toml_edit::Item::as_table_mut)
|
||||||
|
else {
|
||||||
|
return Ok(false);
|
||||||
|
};
|
||||||
|
let old_root = data_dir.join("mcl");
|
||||||
|
let new_root = data_dir.join("rmcl");
|
||||||
|
let mut changed = false;
|
||||||
|
for (key, old_path, replacement) in [
|
||||||
|
(
|
||||||
|
"instances_dir",
|
||||||
|
old_root.join("instances"),
|
||||||
|
new_root.join("instances"),
|
||||||
|
),
|
||||||
|
("meta_dir", old_root.join("meta"), new_root.join("meta")),
|
||||||
|
] {
|
||||||
|
let Some(value) = paths.get_mut(key).and_then(toml_edit::Item::as_value_mut) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if value
|
||||||
|
.as_str()
|
||||||
|
.is_some_and(|raw| settings::resolve_path(raw) == old_path)
|
||||||
|
{
|
||||||
|
let decor = value.decor().clone();
|
||||||
|
*value = toml_edit::Value::from(replacement.to_string_lossy().into_owned());
|
||||||
|
*value.decor_mut() = decor;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if changed {
|
||||||
|
crate::storage::write_atomic(path, document.to_string().as_bytes())?;
|
||||||
|
}
|
||||||
|
Ok(changed)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct LauncherSettingsSave {
|
||||||
|
pub restart_required: bool,
|
||||||
|
pub restart_changed: bool,
|
||||||
|
pub provider_changed: bool,
|
||||||
|
pub modpack_updates_enabled: bool,
|
||||||
|
pub content_updates_enabled: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ConfigStore(RwLock<Config>);
|
||||||
|
|
||||||
|
impl ConfigStore {
|
||||||
|
pub fn read(&self) -> RwLockReadGuard<'_, Config> {
|
||||||
|
self.0
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save_launcher_settings(&self, edited: Config) -> io::Result<LauncherSettingsSave> {
|
||||||
|
let path = get_config_path().join("config.toml");
|
||||||
|
let current = self.read().clone();
|
||||||
|
let edited = edited.normalize();
|
||||||
|
let persisted = load_config(&path).unwrap_or_else(|_| current.clone());
|
||||||
|
let restart_required = current.paths.instances_dir != edited.paths.instances_dir
|
||||||
|
|| current.paths.meta_dir != edited.paths.meta_dir
|
||||||
|
|| current.ui.image_protocol != edited.ui.image_protocol;
|
||||||
|
let restart_changed = persisted.paths.instances_dir != edited.paths.instances_dir
|
||||||
|
|| persisted.paths.meta_dir != edited.paths.meta_dir
|
||||||
|
|| persisted.ui.image_protocol != edited.ui.image_protocol;
|
||||||
|
let provider_changed = current.content.preferred_provider
|
||||||
|
!= edited.content.preferred_provider
|
||||||
|
|| current.content.preferred_provider_only != edited.content.preferred_provider_only;
|
||||||
|
let modpack_updates_enabled =
|
||||||
|
!current.general.check_modpack_updates && edited.general.check_modpack_updates;
|
||||||
|
let content_updates_enabled =
|
||||||
|
!current.general.check_content_updates && edited.general.check_content_updates;
|
||||||
|
write_config_document(&path, &edited)?;
|
||||||
|
|
||||||
|
let mut runtime = edited;
|
||||||
|
runtime
|
||||||
|
.paths
|
||||||
|
.instances_dir
|
||||||
|
.clone_from(¤t.paths.instances_dir);
|
||||||
|
runtime.paths.meta_dir.clone_from(¤t.paths.meta_dir);
|
||||||
|
runtime.ui.image_protocol = current.ui.image_protocol;
|
||||||
|
*self
|
||||||
|
.0
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner) = runtime;
|
||||||
|
crate::feedback::errors::set_max_error_events(self.read().ui.max_error_events);
|
||||||
|
Ok(LauncherSettingsSave {
|
||||||
|
restart_required,
|
||||||
|
restart_changed,
|
||||||
|
provider_changed,
|
||||||
|
modpack_updates_enabled,
|
||||||
|
content_updates_enabled,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reload(&self) -> Result<LauncherSettingsSave, ConfigError> {
|
||||||
|
let mut config = load_config(&get_config_path().join("config.toml"))?;
|
||||||
|
let outcome = {
|
||||||
|
let current = self.read();
|
||||||
|
let restart_required = current.paths.instances_dir != config.paths.instances_dir
|
||||||
|
|| current.paths.meta_dir != config.paths.meta_dir
|
||||||
|
|| current.ui.image_protocol != config.ui.image_protocol;
|
||||||
|
let provider_changed = current.content.preferred_provider
|
||||||
|
!= config.content.preferred_provider
|
||||||
|
|| current.content.preferred_provider_only
|
||||||
|
!= config.content.preferred_provider_only;
|
||||||
|
let modpack_updates_enabled =
|
||||||
|
!current.general.check_modpack_updates && config.general.check_modpack_updates;
|
||||||
|
let content_updates_enabled =
|
||||||
|
!current.general.check_content_updates && config.general.check_content_updates;
|
||||||
|
// App owns a manager and several watchers rooted at these paths.
|
||||||
|
// Keep them stable for this process; persisted path edits apply on restart.
|
||||||
|
config
|
||||||
|
.paths
|
||||||
|
.instances_dir
|
||||||
|
.clone_from(¤t.paths.instances_dir);
|
||||||
|
config.paths.meta_dir.clone_from(¤t.paths.meta_dir);
|
||||||
|
config.ui.image_protocol = current.ui.image_protocol;
|
||||||
|
LauncherSettingsSave {
|
||||||
|
restart_required,
|
||||||
|
restart_changed: restart_required,
|
||||||
|
provider_changed,
|
||||||
|
modpack_updates_enabled,
|
||||||
|
content_updates_enabled,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
*self
|
||||||
|
.0
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner) = config;
|
||||||
|
crate::feedback::errors::set_max_error_events(self.read().ui.max_error_events);
|
||||||
|
Ok(outcome)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub static SETTINGS: LazyLock<ConfigStore> = LazyLock::new(|| {
|
||||||
|
let config = {
|
||||||
|
let path = ensure_config_exists();
|
||||||
|
load_config(&path).unwrap_or_else(|e| {
|
||||||
|
tracing::error!("Config load failed, using defaults: {}", e);
|
||||||
|
Config::default()
|
||||||
|
})
|
||||||
|
};
|
||||||
|
crate::feedback::errors::set_max_error_events(config.ui.max_error_events);
|
||||||
|
ConfigStore(RwLock::new(config))
|
||||||
});
|
});
|
||||||
|
|
||||||
#[cfg(test)]
|
fn write_config_document(path: &std::path::Path, config: &Config) -> io::Result<()> {
|
||||||
mod tests {
|
write_merged_toml_document(path, config, |document| {
|
||||||
use super::*;
|
if let Some(environment) = document
|
||||||
|
.get_mut("defaults")
|
||||||
|
.and_then(|defaults| defaults.get_mut("environment"))
|
||||||
|
.and_then(toml_edit::Item::as_table_mut)
|
||||||
|
{
|
||||||
|
environment.retain(|key, _| config.defaults.environment.contains_key(key));
|
||||||
|
}
|
||||||
|
if config.paths.java_path.is_none()
|
||||||
|
&& let Some(paths) = document
|
||||||
|
.get_mut("paths")
|
||||||
|
.and_then(|item| item.as_table_mut())
|
||||||
|
{
|
||||||
|
paths.remove("java_path");
|
||||||
|
}
|
||||||
|
let default_paths = settings::Paths::default();
|
||||||
|
if let Some(paths) = document
|
||||||
|
.get_mut("paths")
|
||||||
|
.and_then(|item| item.as_table_mut())
|
||||||
|
{
|
||||||
|
if config.paths.instances_dir == default_paths.instances_dir {
|
||||||
|
paths.remove("instances_dir");
|
||||||
|
}
|
||||||
|
if config.paths.meta_dir == default_paths.meta_dir {
|
||||||
|
paths.remove("meta_dir");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if config.defaults.resolution.is_none()
|
||||||
|
&& let Some(defaults) = document
|
||||||
|
.get_mut("defaults")
|
||||||
|
.and_then(|item| item.as_table_mut())
|
||||||
|
{
|
||||||
|
defaults.remove("resolution");
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
pub(crate) fn write_merged_toml_document<T, F>(
|
||||||
fn load_config_from_valid_toml() {
|
path: &std::path::Path,
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
value: &T,
|
||||||
let path = tmp.path().join("config.toml");
|
edit: F,
|
||||||
std::fs::write(
|
) -> io::Result<()>
|
||||||
&path,
|
where
|
||||||
r#"
|
T: serde::Serialize,
|
||||||
[defaults]
|
F: FnOnce(&mut toml_edit::DocumentMut),
|
||||||
memory_max = "4G"
|
{
|
||||||
"#,
|
let source = match fs::read_to_string(path) {
|
||||||
|
Ok(source) => source,
|
||||||
|
Err(error) if error.kind() == io::ErrorKind::NotFound => String::new(),
|
||||||
|
Err(error) => return Err(error),
|
||||||
|
};
|
||||||
|
let mut document = parse_toml_document(path, &source)?;
|
||||||
|
let generated = toml::to_string_pretty(value)
|
||||||
|
.map_err(io::Error::other)?
|
||||||
|
.parse::<toml_edit::DocumentMut>()
|
||||||
|
.map_err(io::Error::other)?;
|
||||||
|
merge_table(document.as_table_mut(), generated.as_table());
|
||||||
|
edit(&mut document);
|
||||||
|
crate::storage::write_atomic(path, document.to_string().as_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_toml_document(path: &std::path::Path, source: &str) -> io::Result<toml_edit::DocumentMut> {
|
||||||
|
source.parse::<toml_edit::DocumentMut>().map_err(|error| {
|
||||||
|
io::Error::new(
|
||||||
|
io::ErrorKind::InvalidData,
|
||||||
|
format!("cannot update {}: {error}", path.display()),
|
||||||
)
|
)
|
||||||
.unwrap();
|
})
|
||||||
let config = load_config(&path).unwrap();
|
}
|
||||||
assert_eq!(config.defaults.memory_max, "4G");
|
|
||||||
assert_eq!(config.defaults.memory_min, "512M");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
fn merge_table(target: &mut toml_edit::Table, source: &toml_edit::Table) {
|
||||||
fn load_config_from_empty_file() {
|
for (key, source_item) in source {
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
if let Some(target_item) = target.get_mut(key) {
|
||||||
let path = tmp.path().join("config.toml");
|
if let (Some(target_table), Some(source_table)) =
|
||||||
std::fs::write(&path, "").unwrap();
|
(target_item.as_table_mut(), source_item.as_table())
|
||||||
let config = load_config(&path).unwrap();
|
{
|
||||||
assert_eq!(config.defaults.memory_max, "2G");
|
merge_table(target_table, source_table);
|
||||||
}
|
continue;
|
||||||
|
}
|
||||||
#[test]
|
if let (Some(target_value), Some(source_value)) =
|
||||||
fn load_config_missing_file_uses_defaults() {
|
(target_item.as_value_mut(), source_item.as_value())
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
{
|
||||||
let path = tmp.path().join("nonexistent.toml");
|
let decor = target_value.decor().clone();
|
||||||
load_config(&path).unwrap();
|
*target_value = source_value.clone();
|
||||||
}
|
*target_value.decor_mut() = decor;
|
||||||
|
continue;
|
||||||
#[test]
|
}
|
||||||
fn load_config_partial_sections() {
|
*target_item = source_item.clone();
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
} else {
|
||||||
let path = tmp.path().join("config.toml");
|
target.insert(key, source_item.clone());
|
||||||
std::fs::write(
|
}
|
||||||
&path,
|
|
||||||
r#"
|
|
||||||
[paths]
|
|
||||||
instances_dir = "/custom/path"
|
|
||||||
"#,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let config = load_config(&path).unwrap();
|
|
||||||
assert_eq!(config.paths.instances_dir, "/custom/path");
|
|
||||||
assert!(config.paths.java_path.is_none());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn merge_missing_table(target: &mut toml_edit::Table, defaults: &toml_edit::Table) {
|
||||||
|
for (key, default_item) in defaults {
|
||||||
|
if let Some(target_item) = target.get_mut(key) {
|
||||||
|
if let (Some(target_table), Some(default_table)) =
|
||||||
|
(target_item.as_table_mut(), default_item.as_table())
|
||||||
|
{
|
||||||
|
merge_missing_table(target_table, default_table);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
target.insert(key, default_item.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "tests/loading.rs"]
|
||||||
|
mod tests;
|
||||||
+389
-127
@@ -1,41 +1,242 @@
|
|||||||
// all the config structs that map to sections in config.toml.
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
// everything has sane defaults so a blank file (or no file) still works.
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
use std::path::PathBuf;
|
use std::{
|
||||||
|
collections::{BTreeMap, BTreeSet},
|
||||||
|
fmt,
|
||||||
|
path::PathBuf,
|
||||||
|
};
|
||||||
|
|
||||||
use serde::Deserialize;
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Default)]
|
use crate::instance::models::{WindowMode, memory_kib, normalize_memory_value};
|
||||||
pub struct General {}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
pub const DEFAULT_RESOLUTION: (u32, u32) = (854, 480);
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize, Default, Clone, Copy, PartialEq, Eq)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum ImageProtocol {
|
||||||
|
#[default]
|
||||||
|
Auto,
|
||||||
|
Halfblocks,
|
||||||
|
Quadrants,
|
||||||
|
Kitty,
|
||||||
|
Iterm2,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum ShortcutHintScope {
|
||||||
|
All,
|
||||||
|
Main,
|
||||||
|
Instances,
|
||||||
|
Content,
|
||||||
|
Accounts,
|
||||||
|
Settings,
|
||||||
|
Popups,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ShortcutHintScope {
|
||||||
|
pub const AREAS: [Self; 5] = [
|
||||||
|
Self::Instances,
|
||||||
|
Self::Content,
|
||||||
|
Self::Accounts,
|
||||||
|
Self::Settings,
|
||||||
|
Self::Popups,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for ImageProtocol {
|
||||||
|
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Auto => formatter.write_str("auto"),
|
||||||
|
Self::Halfblocks => formatter.write_str("halfblocks"),
|
||||||
|
Self::Quadrants => formatter.write_str("quadrants"),
|
||||||
|
Self::Kitty => formatter.write_str("kitty"),
|
||||||
|
Self::Iterm2 => formatter.write_str("iterm2"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct General {
|
||||||
|
#[serde(default = "default_true")]
|
||||||
|
pub check_modpack_updates: bool,
|
||||||
|
#[serde(default = "default_true")]
|
||||||
|
pub check_content_updates: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for General {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
check_modpack_updates: true,
|
||||||
|
check_content_updates: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum ContentProvider {
|
||||||
|
#[default]
|
||||||
|
Modrinth,
|
||||||
|
CurseForge,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for ContentProvider {
|
||||||
|
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Modrinth => formatter.write_str("Modrinth"),
|
||||||
|
Self::CurseForge => formatter.write_str("CurseForge"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct Content {
|
||||||
|
#[serde(default = "default_true")]
|
||||||
|
pub ask_on_provider_conflict: bool,
|
||||||
|
#[serde(default, deserialize_with = "deserialize_content_provider")]
|
||||||
|
pub preferred_provider: ContentProvider,
|
||||||
|
#[serde(default)]
|
||||||
|
pub preferred_provider_only: bool,
|
||||||
|
#[serde(default = "default_unmatched_retry_hours")]
|
||||||
|
pub unmatched_retry_hours: u64,
|
||||||
|
#[serde(default = "default_max_fingerprint_size_mib")]
|
||||||
|
pub max_fingerprint_size_mib: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_true() -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize_content_provider<'de, D>(deserializer: D) -> Result<ContentProvider, D::Error>
|
||||||
|
where
|
||||||
|
D: serde::Deserializer<'de>,
|
||||||
|
{
|
||||||
|
let value = String::deserialize(deserializer)?;
|
||||||
|
Ok(if value.eq_ignore_ascii_case("curseforge") {
|
||||||
|
ContentProvider::CurseForge
|
||||||
|
} else {
|
||||||
|
ContentProvider::Modrinth
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_unmatched_retry_hours() -> u64 {
|
||||||
|
24
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_max_fingerprint_size_mib() -> u64 {
|
||||||
|
512
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Content {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
ask_on_provider_conflict: true,
|
||||||
|
preferred_provider: ContentProvider::default(),
|
||||||
|
preferred_provider_only: false,
|
||||||
|
unmatched_retry_hours: default_unmatched_retry_hours(),
|
||||||
|
max_fingerprint_size_mib: default_max_fingerprint_size_mib(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Content {
|
||||||
|
pub fn preferred_provider(&self) -> &str {
|
||||||
|
self.preferred_provider_with_curseforge(crate::net::curseforge::api_key().is_some())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn discovery_provider_enabled(&self, provider: &str) -> bool {
|
||||||
|
self.discovery_provider_enabled_with_curseforge(
|
||||||
|
provider,
|
||||||
|
crate::net::curseforge::api_key().is_some(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn discovery_provider_label(&self) -> &'static str {
|
||||||
|
self.discovery_provider_label_with_curseforge(crate::net::curseforge::api_key().is_some())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn preferred_provider_with_curseforge(&self, curseforge_available: bool) -> &'static str {
|
||||||
|
if self.preferred_provider == ContentProvider::CurseForge && curseforge_available {
|
||||||
|
"curseforge"
|
||||||
|
} else {
|
||||||
|
"modrinth"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn discovery_provider_enabled_with_curseforge(
|
||||||
|
&self,
|
||||||
|
provider: &str,
|
||||||
|
curseforge_available: bool,
|
||||||
|
) -> bool {
|
||||||
|
match provider {
|
||||||
|
"modrinth" => {
|
||||||
|
!self.preferred_provider_only
|
||||||
|
|| self.preferred_provider_with_curseforge(curseforge_available) == "modrinth"
|
||||||
|
}
|
||||||
|
"curseforge" => {
|
||||||
|
curseforge_available
|
||||||
|
&& (!self.preferred_provider_only
|
||||||
|
|| self.preferred_provider_with_curseforge(curseforge_available)
|
||||||
|
== "curseforge")
|
||||||
|
}
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn discovery_provider_label_with_curseforge(&self, curseforge_available: bool) -> &'static str {
|
||||||
|
match (
|
||||||
|
self.discovery_provider_enabled_with_curseforge("modrinth", curseforge_available),
|
||||||
|
self.discovery_provider_enabled_with_curseforge("curseforge", curseforge_available),
|
||||||
|
) {
|
||||||
|
(true, true) => "providers",
|
||||||
|
(false, true) => "CurseForge",
|
||||||
|
_ => "Modrinth",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct Paths {
|
pub struct Paths {
|
||||||
#[serde(default = "default_instances_dir")]
|
#[serde(default = "default_instances_dir")]
|
||||||
|
#[serde(skip_serializing_if = "is_default_instances_dir")]
|
||||||
pub instances_dir: String,
|
pub instances_dir: String,
|
||||||
#[serde(default = "default_meta_dir")]
|
#[serde(default = "default_meta_dir")]
|
||||||
|
#[serde(skip_serializing_if = "is_default_meta_dir")]
|
||||||
pub meta_dir: String,
|
pub meta_dir: String,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub java_path: Option<String>,
|
pub java_path: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_instances_dir() -> String {
|
fn default_instances_dir() -> String {
|
||||||
dirs_next::data_dir()
|
dirs::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()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn is_default_instances_dir(path: &str) -> bool {
|
||||||
|
path == default_instances_dir()
|
||||||
|
}
|
||||||
|
|
||||||
fn default_meta_dir() -> String {
|
fn default_meta_dir() -> String {
|
||||||
dirs_next::data_dir()
|
dirs::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()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn is_default_meta_dir(path: &str) -> bool {
|
||||||
|
path == default_meta_dir()
|
||||||
|
}
|
||||||
|
|
||||||
impl Default for Paths {
|
impl Default for Paths {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
@@ -46,16 +247,16 @@ impl Default for Paths {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// expand ~ in paths since toml doesn't do that for us
|
|
||||||
pub fn resolve_path(raw: &str) -> PathBuf {
|
pub fn resolve_path(raw: &str) -> PathBuf {
|
||||||
if let Some(stripped) = raw.strip_prefix("~/") {
|
if let Some(stripped) = raw.strip_prefix("~/").or_else(|| raw.strip_prefix("~\\")) {
|
||||||
if let Some(home) = dirs_next::home_dir() {
|
if let Some(home) = dirs::home_dir() {
|
||||||
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::home_dir()
|
||||||
return home;
|
{
|
||||||
}
|
return home;
|
||||||
|
}
|
||||||
PathBuf::from(raw)
|
PathBuf::from(raw)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,12 +274,21 @@ impl Paths {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct Defaults {
|
pub struct Defaults {
|
||||||
#[serde(default = "default_memory_min")]
|
#[serde(default = "default_memory_min")]
|
||||||
pub memory_min: String,
|
pub memory_min: String,
|
||||||
#[serde(default = "default_memory_max")]
|
#[serde(default = "default_memory_max")]
|
||||||
pub memory_max: String,
|
pub memory_max: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub jvm_args: Vec<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub environment: BTreeMap<String, String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub window_mode: WindowMode,
|
||||||
|
#[serde(default = "default_resolution")]
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub resolution: Option<(u32, u32)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_memory_min() -> String {
|
fn default_memory_min() -> String {
|
||||||
@@ -88,19 +298,97 @@ fn default_memory_max() -> String {
|
|||||||
"2G".to_owned()
|
"2G".to_owned()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn default_resolution() -> Option<(u32, u32)> {
|
||||||
|
Some(DEFAULT_RESOLUTION)
|
||||||
|
}
|
||||||
|
|
||||||
impl Default for Defaults {
|
impl Default for Defaults {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
memory_min: default_memory_min(),
|
memory_min: default_memory_min(),
|
||||||
memory_max: default_memory_max(),
|
memory_max: default_memory_max(),
|
||||||
|
jvm_args: Vec::new(),
|
||||||
|
environment: BTreeMap::new(),
|
||||||
|
window_mode: WindowMode::default(),
|
||||||
|
resolution: default_resolution(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
pub(crate) fn parse_tag_values(input: &str) -> Result<Vec<String>, String> {
|
||||||
// timing knobs for the error toast animation: show for 5s, start sliding at 3.5s,
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
// fly off screen over 300ms. tweak these if the toasts feel too fast or slow.
|
enum Quote {
|
||||||
|
None,
|
||||||
|
Single,
|
||||||
|
Double,
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut values = Vec::new();
|
||||||
|
let mut current = String::new();
|
||||||
|
let mut quote = Quote::None;
|
||||||
|
let mut started = false;
|
||||||
|
let mut characters = input.chars().peekable();
|
||||||
|
while let Some(character) = characters.next() {
|
||||||
|
match (quote, character) {
|
||||||
|
(Quote::None, character) if character.is_whitespace() => {
|
||||||
|
if started {
|
||||||
|
values.push(std::mem::take(&mut current));
|
||||||
|
started = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(Quote::None, '\'') => {
|
||||||
|
quote = Quote::Single;
|
||||||
|
started = true;
|
||||||
|
}
|
||||||
|
(Quote::None, '"') => {
|
||||||
|
quote = Quote::Double;
|
||||||
|
started = true;
|
||||||
|
}
|
||||||
|
(Quote::Single, '\'') => quote = Quote::None,
|
||||||
|
(Quote::Double, '"') => quote = Quote::None,
|
||||||
|
(Quote::Double, '\\') if matches!(characters.peek(), Some('"' | '\\')) => {
|
||||||
|
current.push(characters.next().unwrap_or_default());
|
||||||
|
started = true;
|
||||||
|
}
|
||||||
|
(_, character) => {
|
||||||
|
current.push(character);
|
||||||
|
started = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if quote != Quote::None {
|
||||||
|
return Err("Quoted value is missing its closing quote.".to_owned());
|
||||||
|
}
|
||||||
|
if started {
|
||||||
|
values.push(current);
|
||||||
|
}
|
||||||
|
Ok(values)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn format_tag_values(values: &[String]) -> String {
|
||||||
|
values
|
||||||
|
.iter()
|
||||||
|
.map(|value| {
|
||||||
|
if !value.is_empty()
|
||||||
|
&& !value
|
||||||
|
.chars()
|
||||||
|
.any(|character| character.is_whitespace() || matches!(character, '\'' | '"'))
|
||||||
|
{
|
||||||
|
value.clone()
|
||||||
|
} else {
|
||||||
|
format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(" ")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct Ui {
|
pub struct Ui {
|
||||||
|
#[serde(default)]
|
||||||
|
pub image_protocol: ImageProtocol,
|
||||||
|
#[serde(default)]
|
||||||
|
pub hidden_shortcut_hints: BTreeSet<ShortcutHintScope>,
|
||||||
#[serde(default = "default_error_auto_dismiss_ms")]
|
#[serde(default = "default_error_auto_dismiss_ms")]
|
||||||
pub error_auto_dismiss_ms: u64,
|
pub error_auto_dismiss_ms: u64,
|
||||||
#[serde(default = "default_error_slide_start_ms")]
|
#[serde(default = "default_error_slide_start_ms")]
|
||||||
@@ -127,6 +415,8 @@ fn default_max_error_events() -> usize {
|
|||||||
impl Default for Ui {
|
impl Default for Ui {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
image_protocol: ImageProtocol::default(),
|
||||||
|
hidden_shortcut_hints: BTreeSet::new(),
|
||||||
error_auto_dismiss_ms: default_error_auto_dismiss_ms(),
|
error_auto_dismiss_ms: default_error_auto_dismiss_ms(),
|
||||||
error_slide_start_ms: default_error_slide_start_ms(),
|
error_slide_start_ms: default_error_slide_start_ms(),
|
||||||
error_fly_out_ms: default_error_fly_out_ms(),
|
error_fly_out_ms: default_error_fly_out_ms(),
|
||||||
@@ -135,7 +425,40 @@ impl Default for Ui {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
impl Ui {
|
||||||
|
pub fn show_shortcut_hints(&self, scope: ShortcutHintScope) -> bool {
|
||||||
|
!self.hidden_shortcut_hints.contains(&ShortcutHintScope::All)
|
||||||
|
&& !(scope != ShortcutHintScope::Popups
|
||||||
|
&& self
|
||||||
|
.hidden_shortcut_hints
|
||||||
|
.contains(&ShortcutHintScope::Main))
|
||||||
|
&& !self.hidden_shortcut_hints.contains(&scope)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_shortcut_hints(&mut self, scope: ShortcutHintScope, visible: bool) {
|
||||||
|
let mut hidden = ShortcutHintScope::AREAS
|
||||||
|
.into_iter()
|
||||||
|
.filter(|area| !self.show_shortcut_hints(*area))
|
||||||
|
.collect::<BTreeSet<_>>();
|
||||||
|
if visible {
|
||||||
|
hidden.remove(&scope);
|
||||||
|
} else {
|
||||||
|
hidden.insert(scope);
|
||||||
|
}
|
||||||
|
self.hidden_shortcut_hints = if hidden.len() == ShortcutHintScope::AREAS.len() {
|
||||||
|
[ShortcutHintScope::All].into_iter().collect()
|
||||||
|
} else if ShortcutHintScope::AREAS[..4]
|
||||||
|
.iter()
|
||||||
|
.all(|area| hidden.contains(area))
|
||||||
|
{
|
||||||
|
[ShortcutHintScope::Main].into_iter().collect()
|
||||||
|
} else {
|
||||||
|
hidden
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub general: General,
|
pub general: General,
|
||||||
@@ -145,111 +468,50 @@ pub struct Config {
|
|||||||
pub defaults: Defaults,
|
pub defaults: Defaults,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub ui: Ui,
|
pub ui: Ui,
|
||||||
|
#[serde(default)]
|
||||||
|
pub content: Content,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Config {
|
||||||
|
pub fn normalize(mut self) -> Self {
|
||||||
|
if self.paths.instances_dir.trim().is_empty() {
|
||||||
|
self.paths.instances_dir = default_instances_dir();
|
||||||
|
}
|
||||||
|
if self.paths.meta_dir.trim().is_empty() {
|
||||||
|
self.paths.meta_dir = default_meta_dir();
|
||||||
|
}
|
||||||
|
self.paths.java_path = self
|
||||||
|
.paths
|
||||||
|
.java_path
|
||||||
|
.take()
|
||||||
|
.and_then(|path| (!path.trim().is_empty()).then(|| path.trim().to_owned()));
|
||||||
|
self.defaults.memory_min =
|
||||||
|
normalize_memory_value(&self.defaults.memory_min).unwrap_or_else(default_memory_min);
|
||||||
|
self.defaults.memory_max =
|
||||||
|
normalize_memory_value(&self.defaults.memory_max).unwrap_or_else(default_memory_max);
|
||||||
|
if memory_kib(&self.defaults.memory_min) > memory_kib(&self.defaults.memory_max) {
|
||||||
|
self.defaults
|
||||||
|
.memory_max
|
||||||
|
.clone_from(&self.defaults.memory_min);
|
||||||
|
}
|
||||||
|
if self
|
||||||
|
.defaults
|
||||||
|
.resolution
|
||||||
|
.is_none_or(|(width, height)| width == 0 || height == 0)
|
||||||
|
{
|
||||||
|
self.defaults.resolution = default_resolution();
|
||||||
|
}
|
||||||
|
self.ui.error_auto_dismiss_ms = self.ui.error_auto_dismiss_ms.max(1);
|
||||||
|
self.ui.error_slide_start_ms = self
|
||||||
|
.ui
|
||||||
|
.error_slide_start_ms
|
||||||
|
.min(self.ui.error_auto_dismiss_ms);
|
||||||
|
self.ui.error_fly_out_ms = self.ui.error_fly_out_ms.min(self.ui.error_auto_dismiss_ms);
|
||||||
|
self.ui.max_error_events = self.ui.max_error_events.max(1);
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/settings.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn effective_java_path_none_when_absent() {
|
|
||||||
let paths = Paths {
|
|
||||||
java_path: None,
|
|
||||||
..Paths::default()
|
|
||||||
};
|
|
||||||
assert!(paths.effective_java_path().is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn effective_java_path_none_when_empty() {
|
|
||||||
let paths = Paths {
|
|
||||||
java_path: Some(String::new()),
|
|
||||||
..Paths::default()
|
|
||||||
};
|
|
||||||
assert!(paths.effective_java_path().is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn effective_java_path_some_when_set() {
|
|
||||||
let paths = Paths {
|
|
||||||
java_path: Some("/usr/bin/java".to_owned()),
|
|
||||||
..Paths::default()
|
|
||||||
};
|
|
||||||
assert_eq!(paths.effective_java_path(), Some("/usr/bin/java"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolve_path_absolute() {
|
|
||||||
assert_eq!(resolve_path("/opt/mcl"), PathBuf::from("/opt/mcl"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolve_path_tilde_prefix() {
|
|
||||||
let resolved = resolve_path("~/games/mcl");
|
|
||||||
assert!(!resolved.to_string_lossy().starts_with('~'));
|
|
||||||
assert!(resolved.to_string_lossy().ends_with("games/mcl"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolve_path_bare_tilde() {
|
|
||||||
let resolved = resolve_path("~");
|
|
||||||
assert!(!resolved.to_string_lossy().starts_with('~'));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolve_instances_dir_absolute() {
|
|
||||||
let paths = Paths {
|
|
||||||
instances_dir: "/opt/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]
|
|
||||||
fn config_deserializes_from_empty_toml() {
|
|
||||||
let config: Config = toml::from_str("").unwrap();
|
|
||||||
assert_eq!(config.defaults.memory_max, "2G");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn config_deserializes_partial_toml() {
|
|
||||||
let toml_str = r#"
|
|
||||||
[general]
|
|
||||||
debug = true
|
|
||||||
|
|
||||||
[defaults]
|
|
||||||
memory_max = "8G"
|
|
||||||
"#;
|
|
||||||
let config: Config = toml::from_str(toml_str).unwrap();
|
|
||||||
assert_eq!(config.defaults.memory_max, "8G");
|
|
||||||
assert_eq!(config.defaults.memory_min, "512M");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn saving_settings_removes_deleted_environment_keys_and_keeps_retained_comments() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let path = temp.path().join("config.toml");
|
||||||
|
std::fs::write(
|
||||||
|
&path,
|
||||||
|
"[defaults.environment]\nKEEP = 'old' # retained\nREMOVE = 'gone'\n[unknown]\nvalue = 1\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let mut config = Config::default();
|
||||||
|
config
|
||||||
|
.defaults
|
||||||
|
.environment
|
||||||
|
.insert("KEEP".to_owned(), "new".to_owned());
|
||||||
|
write_config_document(&path, &config).unwrap();
|
||||||
|
let source = std::fs::read_to_string(&path).unwrap();
|
||||||
|
assert!(!source.contains("REMOVE"));
|
||||||
|
assert!(source.contains("# retained"));
|
||||||
|
assert!(source.contains("[unknown]"));
|
||||||
|
assert_eq!(load_config(&path).unwrap().defaults.environment.len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_config_from_valid_toml() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let path = tmp.path().join("config.toml");
|
||||||
|
std::fs::write(
|
||||||
|
&path,
|
||||||
|
r#"
|
||||||
|
[defaults]
|
||||||
|
memory_max = "4G"
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let config = load_config(&path).unwrap();
|
||||||
|
assert_eq!(config.defaults.memory_max, "4G");
|
||||||
|
assert_eq!(config.defaults.memory_min, "512M");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_config_from_empty_file() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let path = tmp.path().join("config.toml");
|
||||||
|
std::fs::write(&path, "").unwrap();
|
||||||
|
let config = load_config(&path).unwrap();
|
||||||
|
assert_eq!(config.defaults.memory_max, "2G");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_config_missing_file_uses_defaults() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let path = tmp.path().join("nonexistent.toml");
|
||||||
|
let config = load_config(&path).unwrap();
|
||||||
|
assert_eq!(config.defaults.memory_max, "2G");
|
||||||
|
assert_eq!(config.defaults.memory_min, "512M");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_config_partial_sections() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let path = tmp.path().join("config.toml");
|
||||||
|
std::fs::write(
|
||||||
|
&path,
|
||||||
|
r#"
|
||||||
|
[paths]
|
||||||
|
instances_dir = "/custom/path"
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let config = load_config(&path).unwrap();
|
||||||
|
assert_eq!(config.paths.instances_dir, "/custom/path");
|
||||||
|
assert!(config.paths.java_path.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bundled_config_uses_platform_paths_and_automatic_java() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let path = tmp.path().join("config.toml");
|
||||||
|
std::fs::write(&path, include_str!("../../../assets/config.toml")).unwrap();
|
||||||
|
let config = load_config(&path).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
config.paths.instances_dir,
|
||||||
|
settings::Paths::default().instances_dir
|
||||||
|
);
|
||||||
|
assert_eq!(config.paths.meta_dir, settings::Paths::default().meta_dir);
|
||||||
|
assert!(config.paths.java_path.is_none());
|
||||||
|
assert_eq!(config.ui.image_protocol, settings::ImageProtocol::Auto);
|
||||||
|
assert_eq!(
|
||||||
|
config.defaults.resolution,
|
||||||
|
Some(settings::DEFAULT_RESOLUTION)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_normalizes_memory_java_and_notification_bounds() {
|
||||||
|
let config = Config {
|
||||||
|
paths: settings::Paths {
|
||||||
|
instances_dir: String::new(),
|
||||||
|
meta_dir: " ".to_owned(),
|
||||||
|
java_path: Some(" ".to_owned()),
|
||||||
|
},
|
||||||
|
defaults: settings::Defaults {
|
||||||
|
memory_min: "invalid".to_owned(),
|
||||||
|
memory_max: "1G".to_owned(),
|
||||||
|
resolution: Some((0, 1080)),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
ui: settings::Ui {
|
||||||
|
error_auto_dismiss_ms: 100,
|
||||||
|
error_slide_start_ms: 200,
|
||||||
|
error_fly_out_ms: 300,
|
||||||
|
max_error_events: 0,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
.normalize();
|
||||||
|
assert_eq!(
|
||||||
|
config.paths.instances_dir,
|
||||||
|
settings::Paths::default().instances_dir
|
||||||
|
);
|
||||||
|
assert_eq!(config.paths.meta_dir, settings::Paths::default().meta_dir);
|
||||||
|
assert!(config.paths.java_path.is_none());
|
||||||
|
assert_eq!(config.defaults.memory_min, "512M");
|
||||||
|
assert_eq!(config.defaults.memory_max, "1G");
|
||||||
|
assert_eq!(
|
||||||
|
config.defaults.resolution,
|
||||||
|
Some(settings::DEFAULT_RESOLUTION)
|
||||||
|
);
|
||||||
|
assert_eq!(config.ui.error_slide_start_ms, 100);
|
||||||
|
assert_eq!(config.ui.error_fly_out_ms, 100);
|
||||||
|
assert_eq!(config.ui.max_error_events, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn settings_writer_preserves_comments_and_unknown_keys() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let path = tmp.path().join("config.toml");
|
||||||
|
std::fs::write(
|
||||||
|
&path,
|
||||||
|
"# keep this comment\n[defaults]\n# heap comment\nmemory_max = \"2G\"\n\n[future]\nvalue = 42\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let mut config = Config::default();
|
||||||
|
config.defaults.memory_max = "8G".to_owned();
|
||||||
|
write_config_document(&path, &config).unwrap();
|
||||||
|
let saved = std::fs::read_to_string(path).unwrap();
|
||||||
|
assert!(saved.contains("# keep this comment"), "{saved}");
|
||||||
|
assert!(saved.contains("# heap comment"), "{saved}");
|
||||||
|
assert!(saved.contains("memory_max = \"8G\""));
|
||||||
|
assert!(saved.contains("[future]"));
|
||||||
|
assert!(saved.contains("value = 42"));
|
||||||
|
assert!(!saved.contains("instances_dir"));
|
||||||
|
assert!(!saved.contains("meta_dir"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_upgrade_adds_new_defaults_without_replacing_old_values() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let path = tmp.path().join("config.toml");
|
||||||
|
let old = r#"# user comment
|
||||||
|
[paths]
|
||||||
|
instances_dir = "/custom/instances"
|
||||||
|
meta_dir = "/custom/meta"
|
||||||
|
java_path = "/custom/java"
|
||||||
|
|
||||||
|
[defaults]
|
||||||
|
memory_min = "1G"
|
||||||
|
memory_max = "8G"
|
||||||
|
|
||||||
|
[ui]
|
||||||
|
image_protocol = "kitty"
|
||||||
|
|
||||||
|
[future]
|
||||||
|
value = 42
|
||||||
|
"#;
|
||||||
|
std::fs::write(&path, old).unwrap();
|
||||||
|
|
||||||
|
assert!(upgrade_config_file(&path).unwrap());
|
||||||
|
let upgraded = std::fs::read_to_string(&path).unwrap();
|
||||||
|
let config = load_config(&path).unwrap();
|
||||||
|
|
||||||
|
assert!(upgraded.contains("# user comment"), "{upgraded}");
|
||||||
|
assert!(upgraded.contains("[future]"), "{upgraded}");
|
||||||
|
assert!(upgraded.contains("value = 42"), "{upgraded}");
|
||||||
|
assert!(upgraded.contains("jvm_args = []"), "{upgraded}");
|
||||||
|
assert!(
|
||||||
|
upgraded.contains("check_modpack_updates = true"),
|
||||||
|
"{upgraded}"
|
||||||
|
);
|
||||||
|
assert_eq!(config.paths.instances_dir, "/custom/instances");
|
||||||
|
assert_eq!(config.paths.meta_dir, "/custom/meta");
|
||||||
|
assert_eq!(config.paths.java_path.as_deref(), Some("/custom/java"));
|
||||||
|
assert_eq!(config.defaults.memory_min, "1G");
|
||||||
|
assert_eq!(config.defaults.memory_max, "8G");
|
||||||
|
assert_eq!(config.ui.image_protocol, settings::ImageProtocol::Kitty);
|
||||||
|
|
||||||
|
assert!(!upgrade_config_file(&path).unwrap());
|
||||||
|
assert_eq!(std::fs::read_to_string(path).unwrap(), upgraded);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_default_data_paths_follow_the_renamed_data_directory() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let path = tmp.path().join("config.toml");
|
||||||
|
let data = tmp.path().join("data");
|
||||||
|
std::fs::write(
|
||||||
|
&path,
|
||||||
|
format!(
|
||||||
|
"[paths]\ninstances_dir = {:?}\nmeta_dir = {:?}\n",
|
||||||
|
data.join("mcl/instances").to_string_lossy(),
|
||||||
|
data.join("mcl/meta").to_string_lossy()
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert!(migrate_legacy_data_paths_from(&path, &data).unwrap());
|
||||||
|
let migrated = std::fs::read_to_string(&path).unwrap();
|
||||||
|
let config = load_config(&path).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
settings::resolve_path(&config.paths.instances_dir),
|
||||||
|
data.join("rmcl").join("instances"),
|
||||||
|
"{migrated}"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
settings::resolve_path(&config.paths.meta_dir),
|
||||||
|
data.join("rmcl").join("meta"),
|
||||||
|
"{migrated}"
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn effective_java_path_none_when_absent() {
|
||||||
|
let paths = Paths {
|
||||||
|
java_path: None,
|
||||||
|
..Paths::default()
|
||||||
|
};
|
||||||
|
assert!(paths.effective_java_path().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn effective_java_path_none_when_empty() {
|
||||||
|
let paths = Paths {
|
||||||
|
java_path: Some(String::new()),
|
||||||
|
..Paths::default()
|
||||||
|
};
|
||||||
|
assert!(paths.effective_java_path().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn effective_java_path_some_when_set() {
|
||||||
|
let paths = Paths {
|
||||||
|
java_path: Some("/usr/bin/java".to_owned()),
|
||||||
|
..Paths::default()
|
||||||
|
};
|
||||||
|
assert_eq!(paths.effective_java_path(), Some("/usr/bin/java"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn content_provider_settings_are_normalized() {
|
||||||
|
let content: Content =
|
||||||
|
toml::from_str("preferred_provider = \"curseforge\"\npreferred_provider_only = true")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
content.preferred_provider_with_curseforge(false),
|
||||||
|
"modrinth"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
content.preferred_provider_with_curseforge(true),
|
||||||
|
"curseforge"
|
||||||
|
);
|
||||||
|
assert!(content.preferred_provider_only);
|
||||||
|
assert!(content.discovery_provider_enabled_with_curseforge("modrinth", false));
|
||||||
|
assert!(!content.discovery_provider_enabled_with_curseforge("curseforge", false));
|
||||||
|
assert!(!content.discovery_provider_enabled_with_curseforge("modrinth", true));
|
||||||
|
assert!(content.discovery_provider_enabled_with_curseforge("curseforge", true));
|
||||||
|
assert_eq!(
|
||||||
|
content.discovery_provider_label_with_curseforge(false),
|
||||||
|
"Modrinth"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
content.discovery_provider_label_with_curseforge(true),
|
||||||
|
"CurseForge"
|
||||||
|
);
|
||||||
|
|
||||||
|
let merged = Content::default();
|
||||||
|
assert_eq!(
|
||||||
|
merged.discovery_provider_label_with_curseforge(false),
|
||||||
|
"Modrinth"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
merged.discovery_provider_label_with_curseforge(true),
|
||||||
|
"providers"
|
||||||
|
);
|
||||||
|
|
||||||
|
let legacy: Content = toml::from_str("preferred_provider = \"CurseForge\"").unwrap();
|
||||||
|
assert_eq!(legacy.preferred_provider, ContentProvider::CurseForge);
|
||||||
|
let unknown: Content = toml::from_str("preferred_provider = \"unknown\"").unwrap();
|
||||||
|
assert_eq!(unknown.preferred_provider, ContentProvider::Modrinth);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn discovery_provider_only_disables_the_other_provider() {
|
||||||
|
for preferred_provider in [ContentProvider::Modrinth, ContentProvider::CurseForge] {
|
||||||
|
let mut content = Content {
|
||||||
|
preferred_provider,
|
||||||
|
preferred_provider_only: true,
|
||||||
|
..Content::default()
|
||||||
|
};
|
||||||
|
for provider in ["modrinth", "curseforge"] {
|
||||||
|
assert_eq!(
|
||||||
|
content.discovery_provider_enabled_with_curseforge(provider, true),
|
||||||
|
provider == content.preferred_provider_with_curseforge(true)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
content.preferred_provider_only = false;
|
||||||
|
assert!(content.discovery_provider_enabled_with_curseforge("modrinth", true));
|
||||||
|
assert!(content.discovery_provider_enabled_with_curseforge("curseforge", true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolve_path_absolute() {
|
||||||
|
assert_eq!(resolve_path("/opt/rmcl"), PathBuf::from("/opt/rmcl"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolve_path_tilde_prefix() {
|
||||||
|
let home = dirs::home_dir().expect("test environment has a home directory");
|
||||||
|
for path in ["~/games/rmcl", r"~\games/rmcl"] {
|
||||||
|
assert_eq!(resolve_path(path), home.join("games/rmcl"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolve_path_bare_tilde() {
|
||||||
|
assert_eq!(
|
||||||
|
resolve_path("~"),
|
||||||
|
dirs::home_dir().expect("test environment has a home directory")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_deserializes_from_empty_toml() {
|
||||||
|
let config: Config = toml::from_str("").unwrap();
|
||||||
|
assert_eq!(config.defaults.memory_max, "2G");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_deserializes_partial_toml() {
|
||||||
|
let toml_str = r#"
|
||||||
|
[general]
|
||||||
|
debug = true
|
||||||
|
|
||||||
|
[defaults]
|
||||||
|
memory_max = "8G"
|
||||||
|
"#;
|
||||||
|
let config: Config = toml::from_str(toml_str).unwrap();
|
||||||
|
assert_eq!(config.defaults.memory_max, "8G");
|
||||||
|
assert_eq!(config.defaults.memory_min, "512M");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shortcut_hints_support_global_main_and_selective_hiding() {
|
||||||
|
let mut ui: Ui = toml::from_str("hidden_shortcut_hints = []").unwrap();
|
||||||
|
assert!(
|
||||||
|
ShortcutHintScope::AREAS
|
||||||
|
.iter()
|
||||||
|
.all(|scope| ui.show_shortcut_hints(*scope))
|
||||||
|
);
|
||||||
|
|
||||||
|
ui = toml::from_str("hidden_shortcut_hints = [\"main\"]").unwrap();
|
||||||
|
assert!(!ui.show_shortcut_hints(ShortcutHintScope::Instances));
|
||||||
|
assert!(ui.show_shortcut_hints(ShortcutHintScope::Popups));
|
||||||
|
|
||||||
|
ui.set_shortcut_hints(ShortcutHintScope::Content, true);
|
||||||
|
assert!(ui.show_shortcut_hints(ShortcutHintScope::Content));
|
||||||
|
assert!(!ui.show_shortcut_hints(ShortcutHintScope::Accounts));
|
||||||
|
|
||||||
|
ui.hidden_shortcut_hints = [ShortcutHintScope::All].into_iter().collect();
|
||||||
|
assert!(
|
||||||
|
ShortcutHintScope::AREAS
|
||||||
|
.iter()
|
||||||
|
.all(|scope| !ui.show_shortcut_hints(*scope))
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[rstest::rstest]
|
||||||
|
#[case::plain(BorderStyle::Plain, BorderType::Plain)]
|
||||||
|
#[case::rounded(BorderStyle::Rounded, BorderType::Rounded)]
|
||||||
|
#[case::double(BorderStyle::Double, BorderType::Double)]
|
||||||
|
#[case::thick(BorderStyle::Thick, BorderType::Thick)]
|
||||||
|
fn border_style_roundtrip(#[case] style: BorderStyle, #[case] expected: BorderType) {
|
||||||
|
assert_eq!(style.to_border_type(), expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn theme_config_deserialize_builtin() {
|
||||||
|
let toml_str = r#"
|
||||||
|
theme = "dracula"
|
||||||
|
border_style = "plain"
|
||||||
|
"#;
|
||||||
|
let config: ThemeConfig = toml::from_str(toml_str).unwrap();
|
||||||
|
assert_eq!(config.theme, "dracula");
|
||||||
|
assert_eq!(config.border_style, BorderStyle::Plain);
|
||||||
|
assert!(config.custom.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn theme_config_with_partial_overrides() {
|
||||||
|
let toml_str = r#"
|
||||||
|
theme = "dracula"
|
||||||
|
|
||||||
|
[custom]
|
||||||
|
accent = "Red"
|
||||||
|
"#;
|
||||||
|
let config: ThemeConfig = toml::from_str(toml_str).unwrap();
|
||||||
|
assert_eq!(config.theme, "dracula");
|
||||||
|
let overrides = config.custom.unwrap();
|
||||||
|
assert_eq!(overrides.accent, Some(Color::Red));
|
||||||
|
assert!(overrides.text.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolve_with_overrides_keeps_base() {
|
||||||
|
let config = ThemeConfig {
|
||||||
|
theme: "dracula".to_owned(),
|
||||||
|
custom: Some(ThemeOverrides {
|
||||||
|
accent: Some(Color::Red),
|
||||||
|
..ThemeOverrides::default()
|
||||||
|
}),
|
||||||
|
..ThemeConfig::default()
|
||||||
|
};
|
||||||
|
let theme = resolve_app_theme(&config).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
theme.accent(),
|
||||||
|
if ratatui_themekit::no_color_active() {
|
||||||
|
resolve_theme("dracula").accent()
|
||||||
|
} else {
|
||||||
|
Color::Red
|
||||||
|
}
|
||||||
|
);
|
||||||
|
let base = resolve_theme("dracula");
|
||||||
|
assert_eq!(theme.text(), base.text());
|
||||||
|
assert_eq!(theme.error(), base.error());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_and_invalid_custom_themes_are_errors() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let path = temp.path().join("theme.toml");
|
||||||
|
let config = ThemeConfig {
|
||||||
|
theme: path.to_string_lossy().into_owned(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert!(resolve_app_theme(&config).is_err());
|
||||||
|
std::fs::write(&path, "bad theme").unwrap();
|
||||||
|
assert!(resolve_app_theme(&config).is_err());
|
||||||
|
std::fs::write(&path, include_str!("../../../assets/example-theme.toml")).unwrap();
|
||||||
|
let theme = resolve_app_theme(&config).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
theme.id(),
|
||||||
|
if ratatui_themekit::no_color_active() {
|
||||||
|
"no-color"
|
||||||
|
} else {
|
||||||
|
"my-theme"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolve_builtin_theme() {
|
||||||
|
let theme = resolve_theme("dracula");
|
||||||
|
let expected = if std::env::var_os("NO_COLOR").is_some() {
|
||||||
|
"no-color"
|
||||||
|
} else {
|
||||||
|
"dracula"
|
||||||
|
};
|
||||||
|
assert_eq!(theme.id(), expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
// a theme file in config/theme/ is a flat CustomTheme: name/id/accent are
|
||||||
|
// required, everything else falls back to themekit defaults.
|
||||||
|
#[test]
|
||||||
|
fn custom_theme_file_parses() {
|
||||||
|
let full = toml::from_str::<CustomTheme>(include_str!("../../../assets/example-theme.toml"))
|
||||||
|
.expect("bundled example theme must parse");
|
||||||
|
assert_eq!(full.id, "my-theme");
|
||||||
|
assert_eq!(full.accent, Color::Rgb(249, 115, 22));
|
||||||
|
assert_eq!(full.text, Color::Rgb(205, 214, 244));
|
||||||
|
|
||||||
|
let minimal =
|
||||||
|
toml::from_str::<CustomTheme>("name = \"X\"\nid = \"x\"\naccent = \"#f97316\"\n").unwrap();
|
||||||
|
assert_eq!(minimal.accent, Color::Rgb(249, 115, 22));
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
toml::from_str::<CustomTheme>("[theme]\nname = \"X\"\nid = \"x\"\naccent = \"Red\"\n")
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(toml::from_str::<CustomTheme>("accent = \"Red\"\n").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn theme_config_empty_toml_uses_defaults() {
|
||||||
|
let config: ThemeConfig = toml::from_str("").unwrap();
|
||||||
|
assert_eq!(config.theme, "catppuccin");
|
||||||
|
assert_eq!(config.border_style, BorderStyle::Rounded);
|
||||||
|
}
|
||||||
+146
-106
@@ -1,9 +1,8 @@
|
|||||||
// theme resolution: loads theme.toml, picks a base theme (builtin or custom file),
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
// then layers user color overrides on top. supports loading .toml themes from the
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
// config/theme/ directory or by absolute path.
|
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::sync::LazyLock;
|
use std::sync::{Arc, LazyLock, RwLock};
|
||||||
|
|
||||||
use ratatui::style::Color;
|
use ratatui::style::Color;
|
||||||
use ratatui::widgets::BorderType;
|
use ratatui::widgets::BorderType;
|
||||||
@@ -31,7 +30,7 @@ impl BorderStyle {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Default)]
|
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||||
pub struct ThemeOverrides {
|
pub struct ThemeOverrides {
|
||||||
pub accent: Option<Color>,
|
pub accent: Option<Color>,
|
||||||
pub accent_dim: Option<Color>,
|
pub accent_dim: Option<Color>,
|
||||||
@@ -50,7 +49,7 @@ pub struct ThemeOverrides {
|
|||||||
pub background: Option<Color>,
|
pub background: Option<Color>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct ThemeConfig {
|
pub struct ThemeConfig {
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub border_style: BorderStyle,
|
pub border_style: BorderStyle,
|
||||||
@@ -74,6 +73,7 @@ impl Default for ThemeConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(not(test))]
|
||||||
fn load_theme_config() -> ThemeConfig {
|
fn load_theme_config() -> ThemeConfig {
|
||||||
let path = super::get_config_path().join("theme.toml");
|
let path = super::get_config_path().join("theme.toml");
|
||||||
ensure_theme_exists(&path);
|
ensure_theme_exists(&path);
|
||||||
@@ -86,6 +86,7 @@ fn load_theme_config() -> ThemeConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(not(test))]
|
||||||
fn ensure_theme_exists(path: &Path) {
|
fn ensure_theme_exists(path: &Path) {
|
||||||
if path.exists() {
|
if path.exists() {
|
||||||
return;
|
return;
|
||||||
@@ -96,15 +97,17 @@ fn ensure_theme_exists(path: &Path) {
|
|||||||
let _ = std::fs::write(path, include_str!("../../assets/theme.toml"));
|
let _ = std::fs::write(path, include_str!("../../assets/theme.toml"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// start from a base theme, then override individual colors if the user specified any
|
fn resolve_app_theme(config: &ThemeConfig) -> std::io::Result<Box<dyn Theme>> {
|
||||||
fn resolve_app_theme(config: &ThemeConfig) -> Box<dyn Theme> {
|
let base = load_base_theme(&config.theme)?;
|
||||||
let base = load_base_theme(&config.theme);
|
if ratatui_themekit::no_color_active() {
|
||||||
|
return Ok(resolve_theme("catppuccin"));
|
||||||
|
}
|
||||||
|
|
||||||
let Some(overrides) = &config.custom else {
|
let Some(overrides) = &config.custom else {
|
||||||
return base;
|
return Ok(base);
|
||||||
};
|
};
|
||||||
|
|
||||||
Box::new(CustomTheme {
|
Ok(Box::new(CustomTheme {
|
||||||
name: format!("{} (customized)", base.name()),
|
name: format!("{} (customized)", base.name()),
|
||||||
id: base.id().to_owned(),
|
id: base.id().to_owned(),
|
||||||
accent: overrides.accent.unwrap_or_else(|| base.accent()),
|
accent: overrides.accent.unwrap_or_else(|| base.accent()),
|
||||||
@@ -126,11 +129,10 @@ fn resolve_app_theme(config: &ThemeConfig) -> Box<dyn Theme> {
|
|||||||
border: overrides.border.unwrap_or_else(|| base.border()),
|
border: overrides.border.unwrap_or_else(|| base.border()),
|
||||||
surface: overrides.surface.unwrap_or_else(|| base.surface()),
|
surface: overrides.surface.unwrap_or_else(|| base.surface()),
|
||||||
background: overrides.background.unwrap_or_else(|| base.background()),
|
background: overrides.background.unwrap_or_else(|| base.background()),
|
||||||
})
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
// tries to find the theme: absolute path > config/theme/<name> > config/theme/<name>.toml > builtin
|
fn load_base_theme(name: &str) -> std::io::Result<Box<dyn Theme>> {
|
||||||
fn load_base_theme(name: &str) -> Box<dyn Theme> {
|
|
||||||
let path = if Path::new(name).is_absolute() {
|
let path = if Path::new(name).is_absolute() {
|
||||||
Some(std::path::PathBuf::from(name))
|
Some(std::path::PathBuf::from(name))
|
||||||
} else {
|
} else {
|
||||||
@@ -148,102 +150,140 @@ fn load_base_theme(name: &str) -> Box<dyn Theme> {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Some(path) = path
|
if path.is_none() && ratatui_themekit::available_theme_ids().contains(&name) {
|
||||||
&& let Ok(content) = std::fs::read_to_string(&path)
|
return Ok(resolve_theme(name));
|
||||||
{
|
|
||||||
if let Ok(custom) = toml::from_str::<CustomTheme>(&content) {
|
|
||||||
return Box::new(custom);
|
|
||||||
} else {
|
|
||||||
tracing::warn!("Failed to parse theme file: {}", path.display());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
let path = path.unwrap_or_else(|| {
|
||||||
resolve_theme(name)
|
super::get_config_path()
|
||||||
|
.join("theme")
|
||||||
|
.join(format!("{name}.toml"))
|
||||||
|
});
|
||||||
|
let content = std::fs::read_to_string(&path).map_err(|error| {
|
||||||
|
std::io::Error::new(
|
||||||
|
error.kind(),
|
||||||
|
format!("failed to load theme {}: {error}", path.display()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let custom = toml::from_str::<CustomTheme>(&content).map_err(|error| {
|
||||||
|
std::io::Error::new(
|
||||||
|
std::io::ErrorKind::InvalidData,
|
||||||
|
format!("invalid theme {}: {error}", path.display()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
Ok(Box::new(custom))
|
||||||
}
|
}
|
||||||
|
|
||||||
static THEME_CONFIG: LazyLock<ThemeConfig> = LazyLock::new(load_theme_config);
|
pub struct ThemeStore(RwLock<Arc<dyn Theme>>);
|
||||||
|
|
||||||
pub static THEME: LazyLock<Box<dyn Theme>> = LazyLock::new(|| resolve_app_theme(&THEME_CONFIG));
|
impl ThemeStore {
|
||||||
|
pub fn as_ref(&self) -> Arc<dyn Theme> {
|
||||||
|
self.0
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.clone()
|
||||||
|
}
|
||||||
|
|
||||||
pub static BORDER_STYLE: LazyLock<BorderStyle> =
|
fn set(&self, theme: Box<dyn Theme>) {
|
||||||
LazyLock::new(|| THEME_CONFIG.border_style.clone());
|
*self
|
||||||
|
.0
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::from(theme);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct BorderStyleStore(RwLock<BorderStyle>);
|
||||||
|
|
||||||
|
impl BorderStyleStore {
|
||||||
|
pub fn to_border_type(&self) -> BorderType {
|
||||||
|
self.current().to_border_type()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn current(&self) -> BorderStyle {
|
||||||
|
self.0
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set(&self, style: BorderStyle) {
|
||||||
|
*self
|
||||||
|
.0
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner) = style;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static THEME_CONFIG: LazyLock<RwLock<ThemeConfig>> = LazyLock::new(|| {
|
||||||
|
#[cfg(test)]
|
||||||
|
let config = ThemeConfig::default();
|
||||||
|
#[cfg(not(test))]
|
||||||
|
let config = load_theme_config();
|
||||||
|
RwLock::new(config)
|
||||||
|
});
|
||||||
|
|
||||||
|
pub static THEME: LazyLock<ThemeStore> = LazyLock::new(|| {
|
||||||
|
let config = THEME_CONFIG
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
let theme = resolve_app_theme(&config).unwrap_or_else(|error| {
|
||||||
|
tracing::error!("Could not load theme: {error}");
|
||||||
|
resolve_theme("catppuccin")
|
||||||
|
});
|
||||||
|
ThemeStore(RwLock::new(Arc::from(theme)))
|
||||||
|
});
|
||||||
|
|
||||||
|
pub static BORDER_STYLE: LazyLock<BorderStyleStore> = LazyLock::new(|| {
|
||||||
|
let config = THEME_CONFIG
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
BorderStyleStore(RwLock::new(config.border_style.clone()))
|
||||||
|
});
|
||||||
|
|
||||||
|
pub fn current_theme_config() -> ThemeConfig {
|
||||||
|
THEME_CONFIG
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn apply_theme(theme: String, border_style: BorderStyle) -> std::io::Result<()> {
|
||||||
|
let mut config = current_theme_config();
|
||||||
|
config.theme = theme;
|
||||||
|
config.border_style = border_style.clone();
|
||||||
|
let resolved = resolve_app_theme(&config)?;
|
||||||
|
super::write_merged_toml_document(
|
||||||
|
&super::get_config_path().join("theme.toml"),
|
||||||
|
&config,
|
||||||
|
|document| {
|
||||||
|
if config.custom.is_none() {
|
||||||
|
document.as_table_mut().remove("custom");
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
THEME.set(resolved);
|
||||||
|
BORDER_STYLE.set(border_style);
|
||||||
|
*THEME_CONFIG
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner) = config;
|
||||||
|
crate::feedback::request_redraw();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reload_theme() -> std::io::Result<()> {
|
||||||
|
let path = super::get_config_path().join("theme.toml");
|
||||||
|
let content = std::fs::read_to_string(path)?;
|
||||||
|
let config: ThemeConfig = toml::from_str(&content)
|
||||||
|
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
|
||||||
|
let resolved = resolve_app_theme(&config)?;
|
||||||
|
THEME.set(resolved);
|
||||||
|
BORDER_STYLE.set(config.border_style.clone());
|
||||||
|
*THEME_CONFIG
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner) = config;
|
||||||
|
crate::feedback::request_redraw();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/theme.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn default_theme_config() {
|
|
||||||
let config = ThemeConfig::default();
|
|
||||||
assert_eq!(config.theme, "catppuccin");
|
|
||||||
assert_eq!(config.border_style, BorderStyle::Rounded);
|
|
||||||
assert!(config.custom.is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn border_style_roundtrip() {
|
|
||||||
let style = BorderStyle::Double;
|
|
||||||
assert_eq!(style.to_border_type(), BorderType::Double);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn theme_config_deserialize_builtin() {
|
|
||||||
let toml_str = r#"
|
|
||||||
theme = "dracula"
|
|
||||||
border_style = "plain"
|
|
||||||
"#;
|
|
||||||
let config: ThemeConfig = toml::from_str(toml_str).unwrap();
|
|
||||||
assert_eq!(config.theme, "dracula");
|
|
||||||
assert_eq!(config.border_style, BorderStyle::Plain);
|
|
||||||
assert!(config.custom.is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn theme_config_with_partial_overrides() {
|
|
||||||
let toml_str = r#"
|
|
||||||
theme = "dracula"
|
|
||||||
|
|
||||||
[custom]
|
|
||||||
accent = "Red"
|
|
||||||
"#;
|
|
||||||
let config: ThemeConfig = toml::from_str(toml_str).unwrap();
|
|
||||||
assert_eq!(config.theme, "dracula");
|
|
||||||
let overrides = config.custom.unwrap();
|
|
||||||
assert_eq!(overrides.accent, Some(Color::Red));
|
|
||||||
assert!(overrides.text.is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolve_with_overrides_keeps_base() {
|
|
||||||
let config = ThemeConfig {
|
|
||||||
theme: "dracula".to_owned(),
|
|
||||||
custom: Some(ThemeOverrides {
|
|
||||||
accent: Some(Color::Red),
|
|
||||||
..ThemeOverrides::default()
|
|
||||||
}),
|
|
||||||
..ThemeConfig::default()
|
|
||||||
};
|
|
||||||
let theme = resolve_app_theme(&config);
|
|
||||||
assert_eq!(theme.accent(), Color::Red);
|
|
||||||
let base = resolve_theme("dracula");
|
|
||||||
assert_eq!(theme.text(), base.text());
|
|
||||||
assert_eq!(theme.error(), base.error());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolve_builtin_theme() {
|
|
||||||
let config = ThemeConfig {
|
|
||||||
theme: "dracula".to_owned(),
|
|
||||||
..ThemeConfig::default()
|
|
||||||
};
|
|
||||||
let theme = resolve_app_theme(&config);
|
|
||||||
assert_eq!(theme.id(), "dracula");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn theme_config_empty_toml_uses_defaults() {
|
|
||||||
let config: ThemeConfig = toml::from_str("").unwrap();
|
|
||||||
assert_eq!(config.theme, "catppuccin");
|
|
||||||
assert_eq!(config.border_style, BorderStyle::Rounded);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
// callers pass id: 0 and push_error assigns a real unique id. the id is
|
||||||
|
// used by the render layer to track per-toast animation state.
|
||||||
|
|
||||||
|
use std::collections::VecDeque;
|
||||||
|
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use std::sync::LazyLock;
|
||||||
|
use tracing::Level;
|
||||||
|
|
||||||
|
static NEXT_ERROR_ID: AtomicU64 = AtomicU64::new(1);
|
||||||
|
static MAX_ERROR_EVENTS: AtomicUsize = AtomicUsize::new(50);
|
||||||
|
|
||||||
|
pub(crate) fn set_max_error_events(max_events: usize) {
|
||||||
|
let max_events = max_events.max(1);
|
||||||
|
MAX_ERROR_EVENTS.store(max_events, Ordering::Relaxed);
|
||||||
|
if let Ok(mut events) = ERROR_EVENTS.lock() {
|
||||||
|
while events.len() > max_events {
|
||||||
|
events.pop_front();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ErrorEvent {
|
||||||
|
pub id: u64,
|
||||||
|
pub level: Level,
|
||||||
|
pub message: String,
|
||||||
|
pub pushed_at: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub static ERROR_EVENTS: LazyLock<Arc<Mutex<VecDeque<ErrorEvent>>>> =
|
||||||
|
LazyLock::new(|| Arc::new(Mutex::new(VecDeque::new())));
|
||||||
|
|
||||||
|
pub fn push_error(event: ErrorEvent) {
|
||||||
|
match ERROR_EVENTS.lock() {
|
||||||
|
Ok(mut events) => {
|
||||||
|
let mut event = event;
|
||||||
|
event.id = NEXT_ERROR_ID.fetch_add(1, Ordering::Relaxed);
|
||||||
|
|
||||||
|
events.push_back(event);
|
||||||
|
|
||||||
|
let max_events = MAX_ERROR_EVENTS.load(Ordering::Relaxed);
|
||||||
|
while events.len() > max_events {
|
||||||
|
events.pop_front();
|
||||||
|
}
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Error buffer lock poisoned: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn push_message(level: Level, message: impl Into<String>) {
|
||||||
|
push_error(ErrorEvent {
|
||||||
|
id: 0,
|
||||||
|
level,
|
||||||
|
message: message.into(),
|
||||||
|
pushed_at: Instant::now(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn has_errors() -> bool {
|
||||||
|
match ERROR_EVENTS.lock() {
|
||||||
|
Ok(events) => !events.is_empty(),
|
||||||
|
Err(_) => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn pop_error() -> Option<ErrorEvent> {
|
||||||
|
match ERROR_EVENTS.lock() {
|
||||||
|
Ok(mut events) => {
|
||||||
|
let event = events.pop_front();
|
||||||
|
if event.is_some() {
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
event
|
||||||
|
}
|
||||||
|
Err(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn peek_error() -> Option<ErrorEvent> {
|
||||||
|
match ERROR_EVENTS.lock() {
|
||||||
|
Ok(events) => events.front().cloned(),
|
||||||
|
Err(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
// returned in reverse order (newest first) so they stack top-down in the UI
|
||||||
|
pub fn peek_all_errors() -> Vec<ErrorEvent> {
|
||||||
|
match ERROR_EVENTS.lock() {
|
||||||
|
Ok(events) => events.iter().rev().cloned().collect(),
|
||||||
|
Err(_) => Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "tests/errors.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
|
||||||
|
pub mod errors;
|
||||||
|
pub mod progress;
|
||||||
|
|
||||||
|
static REDRAW_REQUESTED: AtomicBool = AtomicBool::new(true);
|
||||||
|
|
||||||
|
pub fn request_redraw() {
|
||||||
|
REDRAW_REQUESTED.store(true, Ordering::Release);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn take_redraw_request() -> bool {
|
||||||
|
REDRAW_REQUESTED.swap(false, Ordering::AcqRel)
|
||||||
|
}
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::sync::LazyLock;
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Clone)]
|
||||||
|
pub struct ProgressState {
|
||||||
|
pub current_action: Option<String>,
|
||||||
|
pub progress: Option<(u64, u64)>,
|
||||||
|
pub sub_action: Option<String>,
|
||||||
|
tasks: BTreeMap<u64, TaskState>,
|
||||||
|
legacy: Option<TaskState>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
struct TaskState {
|
||||||
|
action: String,
|
||||||
|
sub_action: Option<String>,
|
||||||
|
progress: Option<(u64, u64)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub static PROGRESS: LazyLock<Arc<Mutex<ProgressState>>> =
|
||||||
|
LazyLock::new(|| Arc::new(Mutex::new(ProgressState::default())));
|
||||||
|
static NEXT_TASK_ID: AtomicU64 = AtomicU64::new(1);
|
||||||
|
|
||||||
|
pub struct ProgressTask {
|
||||||
|
id: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ProgressTaskHandle {
|
||||||
|
id: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProgressTask {
|
||||||
|
pub fn start(action: impl Into<String>) -> Self {
|
||||||
|
let id = NEXT_TASK_ID.fetch_add(1, Ordering::Relaxed);
|
||||||
|
let action = action.into();
|
||||||
|
if let Ok(mut state) = PROGRESS.lock() {
|
||||||
|
state.tasks.insert(
|
||||||
|
id,
|
||||||
|
TaskState {
|
||||||
|
action: action.clone(),
|
||||||
|
sub_action: None,
|
||||||
|
progress: None,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
refresh_visible(&mut state);
|
||||||
|
}
|
||||||
|
tracing::info!("{}", action);
|
||||||
|
super::request_redraw();
|
||||||
|
Self { id }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn handle(&self) -> ProgressTaskHandle {
|
||||||
|
ProgressTaskHandle { id: self.id }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_action(&self, text: impl Into<String>) {
|
||||||
|
update_task_action(self.id, text.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_sub_action(&self, text: impl Into<String>) {
|
||||||
|
update_task_sub_action(self.id, text.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_progress(&self, current: u64, total: u64) {
|
||||||
|
update_task_progress(self.id, current, total);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn finish(self) {
|
||||||
|
drop(self);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fail(self, error: impl std::fmt::Display) {
|
||||||
|
tracing::debug!("Progress task failed: {error}");
|
||||||
|
drop(self);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove(&self) {
|
||||||
|
if let Ok(mut state) = PROGRESS.lock() {
|
||||||
|
state.tasks.remove(&self.id);
|
||||||
|
refresh_visible(&mut state);
|
||||||
|
}
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProgressTaskHandle {
|
||||||
|
pub fn set_sub_action(&self, text: impl Into<String>) {
|
||||||
|
update_task_sub_action(self.id, text.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_progress(&self, current: u64, total: u64) {
|
||||||
|
update_task_progress(self.id, current, total);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_task_action(id: u64, text: String) {
|
||||||
|
if let Ok(mut state) = PROGRESS.lock() {
|
||||||
|
if let Some(task) = state.tasks.get_mut(&id) {
|
||||||
|
task.action = text;
|
||||||
|
task.progress = None;
|
||||||
|
}
|
||||||
|
refresh_visible(&mut state);
|
||||||
|
}
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_task_sub_action(id: u64, text: String) {
|
||||||
|
if let Ok(mut state) = PROGRESS.lock() {
|
||||||
|
if let Some(task) = state.tasks.get_mut(&id) {
|
||||||
|
task.sub_action = Some(text);
|
||||||
|
}
|
||||||
|
refresh_visible(&mut state);
|
||||||
|
}
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_task_progress(id: u64, current: u64, total: u64) {
|
||||||
|
if let Ok(mut state) = PROGRESS.lock() {
|
||||||
|
if let Some(task) = state.tasks.get_mut(&id) {
|
||||||
|
task.progress = Some((current, total));
|
||||||
|
}
|
||||||
|
refresh_visible(&mut state);
|
||||||
|
}
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for ProgressTask {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refresh_visible(state: &mut ProgressState) {
|
||||||
|
if let Some(task) = state
|
||||||
|
.tasks
|
||||||
|
.last_key_value()
|
||||||
|
.map(|(_, task)| task)
|
||||||
|
.or(state.legacy.as_ref())
|
||||||
|
{
|
||||||
|
state.current_action = Some(task.action.clone());
|
||||||
|
state.sub_action.clone_from(&task.sub_action);
|
||||||
|
state.progress = task.progress;
|
||||||
|
} else {
|
||||||
|
state.current_action = None;
|
||||||
|
state.sub_action = None;
|
||||||
|
state.progress = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_action(text: impl Into<String>) {
|
||||||
|
let text = text.into();
|
||||||
|
match PROGRESS.lock() {
|
||||||
|
Ok(mut state) => {
|
||||||
|
let sub_action = state
|
||||||
|
.legacy
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|task| task.sub_action.clone());
|
||||||
|
state.legacy = Some(TaskState {
|
||||||
|
action: text.clone(),
|
||||||
|
sub_action,
|
||||||
|
progress: None,
|
||||||
|
});
|
||||||
|
refresh_visible(&mut state);
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Progress lock poisoned: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tracing::info!("{}", text);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_progress(current: u64, total: u64) {
|
||||||
|
match PROGRESS.lock() {
|
||||||
|
Ok(mut state) => {
|
||||||
|
if let Some(task) = state.legacy.as_mut() {
|
||||||
|
task.progress = Some((current, total));
|
||||||
|
}
|
||||||
|
refresh_visible(&mut state);
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Progress lock poisoned: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_sub_action(text: impl Into<String>) {
|
||||||
|
let text = text.into();
|
||||||
|
match PROGRESS.lock() {
|
||||||
|
Ok(mut state) => {
|
||||||
|
if let Some(task) = state.legacy.as_mut() {
|
||||||
|
task.sub_action = Some(text.clone());
|
||||||
|
}
|
||||||
|
refresh_visible(&mut state);
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Progress lock poisoned: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tracing::debug!(" {}", text);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear() {
|
||||||
|
match PROGRESS.lock() {
|
||||||
|
Ok(mut state) => {
|
||||||
|
state.legacy = None;
|
||||||
|
refresh_visible(&mut state);
|
||||||
|
super::request_redraw();
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Progress lock poisoned: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_active() -> bool {
|
||||||
|
PROGRESS
|
||||||
|
.lock()
|
||||||
|
.is_ok_and(|state| state.current_action.is_some())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "tests/progress.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::tests::TEST_LOCK;
|
||||||
|
|
||||||
|
fn clear_errors_for_test() {
|
||||||
|
ERROR_EVENTS.lock().unwrap().clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn make_event(msg: &str) -> ErrorEvent {
|
||||||
|
ErrorEvent {
|
||||||
|
id: 0,
|
||||||
|
level: Level::ERROR,
|
||||||
|
message: msg.to_string(),
|
||||||
|
pushed_at: Instant::now(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn peek_does_not_remove() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear_errors_for_test();
|
||||||
|
|
||||||
|
push_error(make_event("peek-test"));
|
||||||
|
|
||||||
|
let count_before = peek_all_errors().len();
|
||||||
|
let peeked = peek_error();
|
||||||
|
let count_after = peek_all_errors().len();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
count_before, count_after,
|
||||||
|
"peek should not change queue length"
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(peeked.is_some());
|
||||||
|
assert_eq!(peeked.unwrap().message, "peek-test");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn peek_all_returns_newest_first() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear_errors_for_test();
|
||||||
|
|
||||||
|
push_error(make_event("newest_a"));
|
||||||
|
push_error(make_event("newest_b"));
|
||||||
|
|
||||||
|
let all = peek_all_errors();
|
||||||
|
|
||||||
|
assert_eq!(all.len(), 2);
|
||||||
|
assert!(all[0].message.ends_with("_b"));
|
||||||
|
assert!(all[1].message.ends_with("_a"));
|
||||||
|
assert!(all[0].id > all[1].id);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn auto_assigned_ids_are_unique() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear_errors_for_test();
|
||||||
|
|
||||||
|
push_error(make_event("unique_1"));
|
||||||
|
push_error(make_event("unique_2"));
|
||||||
|
|
||||||
|
let all = peek_all_errors();
|
||||||
|
|
||||||
|
assert_eq!(all.len(), 2);
|
||||||
|
assert_ne!(all[0].id, all[1].id);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn overflow_drops_oldest() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear_errors_for_test();
|
||||||
|
|
||||||
|
let max_error_events = 50;
|
||||||
|
set_max_error_events(max_error_events);
|
||||||
|
for i in 0..(max_error_events + 10) {
|
||||||
|
push_error(make_event(&format!("overflow_{i}")));
|
||||||
|
}
|
||||||
|
|
||||||
|
let all = peek_all_errors();
|
||||||
|
|
||||||
|
assert_eq!(all.len(), max_error_events);
|
||||||
|
|
||||||
|
assert!(!all.iter().any(|e| e.message == "overflow_0"));
|
||||||
|
assert!(!all.iter().any(|e| e.message == "overflow_9"));
|
||||||
|
|
||||||
|
assert!(all.iter().any(|e| e.message == "overflow_10"));
|
||||||
|
assert!(all.iter().any(|e| e.message == "overflow_59"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lowering_limit_trims_existing_events_immediately() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear_errors_for_test();
|
||||||
|
set_max_error_events(5);
|
||||||
|
for i in 0..5 {
|
||||||
|
push_error(make_event(&format!("trim_{i}")));
|
||||||
|
}
|
||||||
|
|
||||||
|
set_max_error_events(2);
|
||||||
|
let all = peek_all_errors();
|
||||||
|
|
||||||
|
assert_eq!(all.len(), 2);
|
||||||
|
assert_eq!(all[0].message, "trim_4");
|
||||||
|
assert_eq!(all[1].message, "trim_3");
|
||||||
|
set_max_error_events(50);
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::tests::TEST_LOCK;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn newest_task_is_visible_and_drop_restores_previous_task() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear();
|
||||||
|
let first = ProgressTask::start("first");
|
||||||
|
first.set_progress(1, 2);
|
||||||
|
{
|
||||||
|
let second = ProgressTask::start("second");
|
||||||
|
second.set_sub_action("working");
|
||||||
|
let state = PROGRESS.lock().unwrap();
|
||||||
|
assert_eq!(state.current_action.as_deref(), Some("second"));
|
||||||
|
assert_eq!(state.sub_action.as_deref(), Some("working"));
|
||||||
|
}
|
||||||
|
let state = PROGRESS.lock().unwrap();
|
||||||
|
assert_eq!(state.current_action.as_deref(), Some("first"));
|
||||||
|
assert_eq!(state.progress, Some((1, 2)));
|
||||||
|
drop(state);
|
||||||
|
first.finish();
|
||||||
|
clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn changing_phase_resets_progress_to_indeterminate() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear();
|
||||||
|
let task = ProgressTask::start("inventory");
|
||||||
|
task.set_progress(4, 10);
|
||||||
|
task.set_action("provider matching");
|
||||||
|
|
||||||
|
let state = PROGRESS.lock().unwrap();
|
||||||
|
assert_eq!(state.current_action.as_deref(), Some("provider matching"));
|
||||||
|
assert_eq!(state.progress, None);
|
||||||
|
drop(state);
|
||||||
|
|
||||||
|
task.finish();
|
||||||
|
assert!(!is_active());
|
||||||
|
clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn clearing_legacy_progress_keeps_owned_tasks() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear();
|
||||||
|
let task = ProgressTask::start("indexing");
|
||||||
|
set_action("legacy download");
|
||||||
|
clear();
|
||||||
|
|
||||||
|
let state = PROGRESS.lock().unwrap();
|
||||||
|
assert_eq!(state.current_action.as_deref(), Some("indexing"));
|
||||||
|
drop(state);
|
||||||
|
|
||||||
|
task.finish();
|
||||||
|
clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn owned_tasks_restore_legacy_progress_and_legacy_updates_do_not_cover_them() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear();
|
||||||
|
set_action("legacy");
|
||||||
|
set_sub_action("download");
|
||||||
|
set_progress(1, 3);
|
||||||
|
let task = ProgressTask::start("owned");
|
||||||
|
set_progress(2, 3);
|
||||||
|
assert_eq!(
|
||||||
|
PROGRESS.lock().unwrap().current_action.as_deref(),
|
||||||
|
Some("owned")
|
||||||
|
);
|
||||||
|
task.finish();
|
||||||
|
let state = PROGRESS.lock().unwrap();
|
||||||
|
assert_eq!(state.current_action.as_deref(), Some("legacy"));
|
||||||
|
assert_eq!(state.sub_action.as_deref(), Some("download"));
|
||||||
|
assert_eq!(state.progress, Some((2, 3)));
|
||||||
|
drop(state);
|
||||||
|
clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_new_legacy_action_does_not_reuse_the_previous_phase_progress() {
|
||||||
|
let _guard = TEST_LOCK.lock().unwrap();
|
||||||
|
clear();
|
||||||
|
set_action("Downloading installer");
|
||||||
|
set_progress(1, 1);
|
||||||
|
|
||||||
|
set_action("Running installer");
|
||||||
|
|
||||||
|
let state = PROGRESS.lock().unwrap();
|
||||||
|
assert_eq!(state.current_action.as_deref(), Some("Running installer"));
|
||||||
|
assert_eq!(state.progress, None);
|
||||||
|
drop(state);
|
||||||
|
clear();
|
||||||
|
}
|
||||||
@@ -0,0 +1,926 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use thiserror::Error;
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum ConfigSyncError {
|
||||||
|
#[error("Invalid config sync profile: {0}")]
|
||||||
|
InvalidProfile(String),
|
||||||
|
#[error("Cannot switch config profiles while '{instance}' is running")]
|
||||||
|
InstanceRunning { instance: String },
|
||||||
|
#[error("Config profile '{0}' is in use by another instance")]
|
||||||
|
ProfileInUse(String),
|
||||||
|
#[error("Config profile '{}' and local settings '{}' have diverged; both were kept", profile.display(), minecraft.display())]
|
||||||
|
Conflict {
|
||||||
|
profile: PathBuf,
|
||||||
|
minecraft: PathBuf,
|
||||||
|
},
|
||||||
|
#[error("IO error: {0}")]
|
||||||
|
Io(#[from] std::io::Error),
|
||||||
|
#[error("Failed to save config profile: {0}")]
|
||||||
|
Save(String),
|
||||||
|
#[error("Config sync failed ({save}) and rollback failed ({rollback})")]
|
||||||
|
SaveRollback { save: String, rollback: String },
|
||||||
|
#[error(transparent)]
|
||||||
|
Instance(#[from] crate::instance::InstanceError),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ConfigSyncLock {
|
||||||
|
file: std::fs::File,
|
||||||
|
profile_dir: PathBuf,
|
||||||
|
recovered_source: Option<PathBuf>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize)]
|
||||||
|
struct PayloadBaseline {
|
||||||
|
profile: PathBuf,
|
||||||
|
// External relative links are re-anchored on import, so these hashes can differ.
|
||||||
|
local: String,
|
||||||
|
shared: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for ConfigSyncLock {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Err(e) = self.file.unlock() {
|
||||||
|
tracing::warn!("Failed to release config sync lock: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn prepare(
|
||||||
|
profile: Option<&str>,
|
||||||
|
meta_dir: &Path,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
) -> Result<bool, ConfigSyncError> {
|
||||||
|
Ok(prepare_for_launch(profile, meta_dir, minecraft_dir)?.is_some())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn prepare_for_launch(
|
||||||
|
profile: Option<&str>,
|
||||||
|
meta_dir: &Path,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
) -> Result<Option<ConfigSyncLock>, ConfigSyncError> {
|
||||||
|
let Some(profile) = profile.and_then(normalize_profile) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
validate_profile(profile)?;
|
||||||
|
|
||||||
|
let profile_dir = profile_dir(meta_dir, profile);
|
||||||
|
if !profile_exists(&profile_dir)? {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let lock = acquire_lock(&profile_dir)?;
|
||||||
|
prepare_locked(lock, minecraft_dir)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prepare_locked(
|
||||||
|
lock: ConfigSyncLock,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
) -> Result<Option<ConfigSyncLock>, ConfigSyncError> {
|
||||||
|
let profile_dir = &lock.profile_dir;
|
||||||
|
if !profile_exists(profile_dir)? {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
if !profile_payload_exists(profile_dir)? {
|
||||||
|
publish_current(minecraft_dir, profile_dir, false)?;
|
||||||
|
persist_with_baseline(minecraft_dir, Some(profile_dir), || {
|
||||||
|
mark_unsynced(profile_dir, minecraft_dir)
|
||||||
|
})?;
|
||||||
|
} else {
|
||||||
|
let identity = std::fs::canonicalize(profile_dir)?;
|
||||||
|
if read_baseline(minecraft_dir)?.is_some_and(|baseline| baseline.profile == identity) {
|
||||||
|
publish_current(minecraft_dir, profile_dir, false)?;
|
||||||
|
}
|
||||||
|
mirror_payload(profile_dir, minecraft_dir, true, || {
|
||||||
|
persist_with_baseline(minecraft_dir, Some(profile_dir), || {
|
||||||
|
mark_unsynced(profile_dir, minecraft_dir)
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Some(lock))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn finish_launch(lock: ConfigSyncLock, minecraft_dir: &Path) -> Result<(), ConfigSyncError> {
|
||||||
|
let allow_untracked = match &lock.recovered_source {
|
||||||
|
Some(source) => std::fs::canonicalize(source)? == std::fs::canonicalize(minecraft_dir)?,
|
||||||
|
None => true,
|
||||||
|
};
|
||||||
|
publish_current(minecraft_dir, &lock.profile_dir, allow_untracked)?;
|
||||||
|
remove_if_exists(&unsynced_marker(&lock.profile_dir))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn finish(
|
||||||
|
profile: Option<&str>,
|
||||||
|
meta_dir: &Path,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
) -> Result<(), ConfigSyncError> {
|
||||||
|
let Some(profile) = profile.and_then(normalize_profile) else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
validate_profile(profile)?;
|
||||||
|
|
||||||
|
let profile_dir = profile_dir(meta_dir, profile);
|
||||||
|
finish_launch(acquire_lock(&profile_dir)?, minecraft_dir)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn list_profiles(meta_dir: &Path) -> Result<Vec<String>, ConfigSyncError> {
|
||||||
|
let root = profiles_dir(meta_dir);
|
||||||
|
let mut profiles = Vec::new();
|
||||||
|
if !entry_exists(&root)? {
|
||||||
|
return Ok(profiles);
|
||||||
|
}
|
||||||
|
|
||||||
|
for entry in std::fs::read_dir(root)? {
|
||||||
|
let entry = entry?;
|
||||||
|
if entry.file_type()?.is_dir() {
|
||||||
|
let name = entry.file_name().to_string_lossy().to_string();
|
||||||
|
if validate_profile(&name).is_ok() {
|
||||||
|
profiles.push(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
profiles.sort_unstable();
|
||||||
|
Ok(profiles)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_profile(meta_dir: &Path, profile: &str) -> Result<String, ConfigSyncError> {
|
||||||
|
let Some(profile) = normalize_profile(profile) else {
|
||||||
|
return Err(ConfigSyncError::InvalidProfile(profile.to_string()));
|
||||||
|
};
|
||||||
|
validate_profile(profile)?;
|
||||||
|
let _lock = acquire_lock(&profile_dir(meta_dir, profile))?;
|
||||||
|
std::fs::create_dir_all(profile_dir(meta_dir, profile))?;
|
||||||
|
Ok(profile.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn delete_profile(meta_dir: &Path, profile: &str) -> Result<(), ConfigSyncError> {
|
||||||
|
validate_profile(profile)?;
|
||||||
|
let dir = profile_dir(meta_dir, profile);
|
||||||
|
if profile_exists(&dir)? {
|
||||||
|
let _lock = acquire_lock(&dir)?;
|
||||||
|
if profile_exists(&dir)? {
|
||||||
|
remove_path(&dir)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
fn switch_profile(
|
||||||
|
instance_name: &str,
|
||||||
|
current_profile: Option<&str>,
|
||||||
|
target_profile: Option<&str>,
|
||||||
|
meta_dir: &Path,
|
||||||
|
instance_dir: &Path,
|
||||||
|
) -> Result<Option<String>, ConfigSyncError> {
|
||||||
|
switch_profile_and_persist(
|
||||||
|
instance_name,
|
||||||
|
current_profile,
|
||||||
|
target_profile,
|
||||||
|
meta_dir,
|
||||||
|
instance_dir,
|
||||||
|
|_| Ok::<(), std::io::Error>(()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn switch_profile_and_save(
|
||||||
|
manager: &crate::instance::InstanceManager,
|
||||||
|
config: &mut crate::instance::InstanceConfig,
|
||||||
|
target_profile: Option<&str>,
|
||||||
|
) -> Result<(), ConfigSyncError> {
|
||||||
|
let _instance_lock =
|
||||||
|
crate::instance::runtime::lock_instance(&manager.instances_dir, &config.name)?;
|
||||||
|
let current = manager.load_one(&config.name)?;
|
||||||
|
let instance_dir = manager.instances_dir.join(¤t.name);
|
||||||
|
let mut saved = None;
|
||||||
|
switch_profile_and_persist(
|
||||||
|
¤t.name,
|
||||||
|
current.config_sync_profile.as_deref(),
|
||||||
|
target_profile,
|
||||||
|
&manager.meta_dir,
|
||||||
|
&instance_dir,
|
||||||
|
|selected| {
|
||||||
|
saved =
|
||||||
|
Some(manager.save_config_sync_profile(¤t.name, selected.map(str::to_owned))?);
|
||||||
|
Ok::<(), crate::instance::InstanceError>(())
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
*config = saved.expect("successful profile switch persisted its selection");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn switch_profile_and_persist<E>(
|
||||||
|
instance_name: &str,
|
||||||
|
current_profile: Option<&str>,
|
||||||
|
target_profile: Option<&str>,
|
||||||
|
meta_dir: &Path,
|
||||||
|
instance_dir: &Path,
|
||||||
|
persist: impl FnOnce(Option<&str>) -> Result<(), E>,
|
||||||
|
) -> Result<Option<String>, ConfigSyncError>
|
||||||
|
where
|
||||||
|
E: std::fmt::Display,
|
||||||
|
{
|
||||||
|
if crate::instance::runtime::is_active(instance_name) {
|
||||||
|
return Err(ConfigSyncError::InstanceRunning {
|
||||||
|
instance: instance_name.to_owned(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let current = current_profile.and_then(normalize_profile);
|
||||||
|
let target = target_profile.and_then(normalize_profile);
|
||||||
|
for profile in [current, target].into_iter().flatten() {
|
||||||
|
validate_profile(profile)?;
|
||||||
|
profile_exists(&profile_dir(meta_dir, profile))?;
|
||||||
|
}
|
||||||
|
let save =
|
||||||
|
|selected| persist(selected).map_err(|error| ConfigSyncError::Save(error.to_string()));
|
||||||
|
if current == target {
|
||||||
|
save(current)?;
|
||||||
|
return Ok(current.map(str::to_owned));
|
||||||
|
}
|
||||||
|
let minecraft = minecraft_dir(instance_dir);
|
||||||
|
if let Some(profile) = current {
|
||||||
|
let dir = profile_dir(meta_dir, profile);
|
||||||
|
if profile_exists(&dir)? {
|
||||||
|
let _lock = acquire_lock(&dir)?;
|
||||||
|
if profile_exists(&dir)? {
|
||||||
|
publish_current(&minecraft, &dir, false)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let local = local_backup_dir(instance_dir);
|
||||||
|
if current.is_none() && target.is_some() {
|
||||||
|
sync_to_profile(&minecraft, &local)?;
|
||||||
|
}
|
||||||
|
let Some(profile) = target else {
|
||||||
|
if current.is_some() && entry_exists(&local)? {
|
||||||
|
return mirror_payload(&local, &minecraft, true, || {
|
||||||
|
persist_with_baseline(&minecraft, None, || save(None))?;
|
||||||
|
Ok(None)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
persist_with_baseline(&minecraft, None, || save(None))?;
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let dir = profile_dir(meta_dir, profile);
|
||||||
|
let _lock = acquire_lock(&dir)?;
|
||||||
|
if !profile_payload_exists(&dir)? {
|
||||||
|
sync_to_profile(&minecraft, &dir)?;
|
||||||
|
}
|
||||||
|
mirror_payload(&dir, &minecraft, true, || {
|
||||||
|
persist_with_baseline(&minecraft, Some(&dir), || save(Some(profile)))?;
|
||||||
|
Ok(Some(profile.to_owned()))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_profile(profile: &str) -> Option<&str> {
|
||||||
|
let trimmed = profile.trim();
|
||||||
|
if trimmed.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(trimmed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn validate_profile(profile: &str) -> Result<(), ConfigSyncError> {
|
||||||
|
if profile.is_empty()
|
||||||
|
|| profile.len() > 64
|
||||||
|
|| profile.starts_with('.')
|
||||||
|
|| !crate::instance::manager::portable_component(profile)
|
||||||
|
|| profile.eq_ignore_ascii_case("default")
|
||||||
|
|| profile.eq_ignore_ascii_case("none")
|
||||||
|
|| profile.eq_ignore_ascii_case("local")
|
||||||
|
|| profile.eq_ignore_ascii_case("instance default")
|
||||||
|
|| profile.eq_ignore_ascii_case("local default")
|
||||||
|
{
|
||||||
|
return Err(ConfigSyncError::InvalidProfile(profile.to_string()));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn profile_dir(meta_dir: &Path, profile: &str) -> PathBuf {
|
||||||
|
profiles_dir(meta_dir).join(profile)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn profiles_dir(meta_dir: &Path) -> PathBuf {
|
||||||
|
crate::storage::MetadataPaths::new(meta_dir).profiles()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn minecraft_dir(instance_dir: &Path) -> PathBuf {
|
||||||
|
instance_dir.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn local_backup_dir(instance_dir: &Path) -> PathBuf {
|
||||||
|
crate::storage::InstancePaths::new(instance_dir).local_config()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn acquire_lock(profile_dir: &Path) -> Result<ConfigSyncLock, ConfigSyncError> {
|
||||||
|
let parent = profile_dir
|
||||||
|
.parent()
|
||||||
|
.ok_or_else(|| std::io::Error::other("Config profile has no parent"))?;
|
||||||
|
std::fs::create_dir_all(parent)?;
|
||||||
|
// Keep locks outside deletable profiles so recreating a profile cannot bypass an old handle.
|
||||||
|
let path = parent.join(format!(
|
||||||
|
".{}.lock",
|
||||||
|
profile_dir
|
||||||
|
.file_name()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.to_string_lossy()
|
||||||
|
));
|
||||||
|
let file = std::fs::OpenOptions::new()
|
||||||
|
.read(true)
|
||||||
|
.write(true)
|
||||||
|
.create(true)
|
||||||
|
.truncate(false)
|
||||||
|
.open(path)?;
|
||||||
|
match file.try_lock() {
|
||||||
|
Ok(()) => {}
|
||||||
|
Err(std::fs::TryLockError::WouldBlock) => {
|
||||||
|
return Err(ConfigSyncError::ProfileInUse(
|
||||||
|
profile_dir
|
||||||
|
.file_name()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.to_string_lossy()
|
||||||
|
.into_owned(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Err(std::fs::TryLockError::Error(error)) => return Err(error.into()),
|
||||||
|
}
|
||||||
|
let mut lock = ConfigSyncLock {
|
||||||
|
file,
|
||||||
|
profile_dir: profile_dir.to_owned(),
|
||||||
|
recovered_source: None,
|
||||||
|
};
|
||||||
|
profile_exists(profile_dir)?;
|
||||||
|
lock.recovered_source = recover_unsynced(profile_dir)?;
|
||||||
|
Ok(lock)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unsynced_marker(profile: &Path) -> PathBuf {
|
||||||
|
profile.join(".unsynced.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mark_unsynced(profile: &Path, minecraft: &Path) -> Result<(), ConfigSyncError> {
|
||||||
|
let source = std::path::absolute(minecraft)?;
|
||||||
|
if !std::fs::metadata(&source)?.is_dir() {
|
||||||
|
return Err(std::io::Error::other("Config sync source is not a directory").into());
|
||||||
|
}
|
||||||
|
let bytes = serde_json::to_vec(&source).map_err(std::io::Error::other)?;
|
||||||
|
crate::storage::write_atomic(&unsynced_marker(profile), &bytes)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn recover_unsynced(profile: &Path) -> Result<Option<PathBuf>, ConfigSyncError> {
|
||||||
|
let marker = unsynced_marker(profile);
|
||||||
|
let bytes = match std::fs::read(&marker) {
|
||||||
|
Ok(bytes) => bytes,
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||||
|
Err(error) => return Err(error.into()),
|
||||||
|
};
|
||||||
|
let source: PathBuf = serde_json::from_slice(&bytes).map_err(|error| {
|
||||||
|
std::io::Error::new(
|
||||||
|
std::io::ErrorKind::InvalidData,
|
||||||
|
format!("Invalid config sync marker '{}': {error}", marker.display()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
if !source.is_absolute() || !std::fs::metadata(&source)?.is_dir() {
|
||||||
|
return Err(std::io::Error::other(format!(
|
||||||
|
"Invalid unsynced config source '{}'",
|
||||||
|
source.display()
|
||||||
|
))
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
publish_current(&source, profile, true)?;
|
||||||
|
std::fs::remove_file(marker)?;
|
||||||
|
Ok(Some(source))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn baseline_path(minecraft: &Path) -> Result<PathBuf, ConfigSyncError> {
|
||||||
|
let instance = minecraft
|
||||||
|
.parent()
|
||||||
|
.ok_or_else(|| std::io::Error::other("Config sync source has no parent"))?;
|
||||||
|
Ok(crate::storage::InstancePaths::new(instance)
|
||||||
|
.state()
|
||||||
|
.join("config-sync.json"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_baseline(minecraft: &Path) -> Result<Option<PayloadBaseline>, ConfigSyncError> {
|
||||||
|
let path = baseline_path(minecraft)?;
|
||||||
|
match std::fs::read(&path) {
|
||||||
|
Ok(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|error| {
|
||||||
|
std::io::Error::new(
|
||||||
|
std::io::ErrorKind::InvalidData,
|
||||||
|
format!("Invalid config sync baseline '{}': {error}", path.display()),
|
||||||
|
)
|
||||||
|
.into()
|
||||||
|
}),
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||||
|
Err(error) => Err(error.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn baseline_bytes(
|
||||||
|
profile: &Path,
|
||||||
|
local: String,
|
||||||
|
shared: String,
|
||||||
|
) -> Result<Vec<u8>, ConfigSyncError> {
|
||||||
|
let baseline = PayloadBaseline {
|
||||||
|
profile: std::fs::canonicalize(profile)?,
|
||||||
|
local,
|
||||||
|
shared,
|
||||||
|
};
|
||||||
|
Ok(serde_json::to_vec(&baseline).map_err(std::io::Error::other)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn persist_with_baseline<T>(
|
||||||
|
minecraft: &Path,
|
||||||
|
profile: Option<&Path>,
|
||||||
|
persist: impl FnOnce() -> Result<T, ConfigSyncError>,
|
||||||
|
) -> Result<T, ConfigSyncError> {
|
||||||
|
let path = baseline_path(minecraft)?;
|
||||||
|
let previous = match std::fs::read(&path) {
|
||||||
|
Ok(bytes) => Some(bytes),
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
|
||||||
|
Err(error) => return Err(error.into()),
|
||||||
|
};
|
||||||
|
if let Some(profile) = profile {
|
||||||
|
crate::storage::write_atomic(
|
||||||
|
&path,
|
||||||
|
&baseline_bytes(profile, payload_hash(minecraft)?, payload_hash(profile)?)?,
|
||||||
|
)?;
|
||||||
|
} else {
|
||||||
|
remove_if_exists(&path)?;
|
||||||
|
}
|
||||||
|
match persist() {
|
||||||
|
Ok(value) => Ok(value),
|
||||||
|
Err(error) => {
|
||||||
|
let rollback = match previous {
|
||||||
|
Some(bytes) => {
|
||||||
|
crate::storage::write_atomic(&path, &bytes).map_err(ConfigSyncError::from)
|
||||||
|
}
|
||||||
|
None => remove_if_exists(&path),
|
||||||
|
};
|
||||||
|
match rollback {
|
||||||
|
Ok(()) => Err(error),
|
||||||
|
Err(rollback) => Err(ConfigSyncError::SaveRollback {
|
||||||
|
save: error.to_string(),
|
||||||
|
rollback: format!("Restoring baseline '{}': {rollback}", path.display()),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn publish_current(
|
||||||
|
minecraft: &Path,
|
||||||
|
profile: &Path,
|
||||||
|
allow_untracked: bool,
|
||||||
|
) -> Result<(), ConfigSyncError> {
|
||||||
|
let local = payload_hash(minecraft)?;
|
||||||
|
let shared = payload_hash(profile)?;
|
||||||
|
let identity = std::fs::canonicalize(profile)?;
|
||||||
|
let baseline = read_baseline(minecraft)?.filter(|baseline| baseline.profile == identity);
|
||||||
|
let needs_export = local != shared;
|
||||||
|
if needs_export {
|
||||||
|
match baseline {
|
||||||
|
Some(baseline) if local == baseline.local => return Ok(()),
|
||||||
|
Some(baseline) if shared == baseline.shared => {}
|
||||||
|
None if allow_untracked || !profile_payload_exists(profile)? => {}
|
||||||
|
_ => {
|
||||||
|
return Err(ConfigSyncError::Conflict {
|
||||||
|
profile: profile.to_owned(),
|
||||||
|
minecraft: minecraft.to_owned(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let persist = |shared| {
|
||||||
|
crate::storage::write_atomic(
|
||||||
|
&baseline_path(minecraft)?,
|
||||||
|
&baseline_bytes(profile, local, shared)?,
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
};
|
||||||
|
if needs_export {
|
||||||
|
mirror_payload(minecraft, profile, true, || persist(payload_hash(profile)?))
|
||||||
|
} else {
|
||||||
|
persist(shared)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn payload_hash(dir: &Path) -> Result<String, ConfigSyncError> {
|
||||||
|
use sha2::Digest;
|
||||||
|
require_source_dir(dir)?;
|
||||||
|
check_config_root(dir)?;
|
||||||
|
let mut hash = sha2::Sha256::new();
|
||||||
|
for name in payload_names(dir, true)? {
|
||||||
|
hash_payload_entry(&dir.join(name), dir, &mut hash)?;
|
||||||
|
}
|
||||||
|
Ok(format!("{:x}", hash.finalize()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hash_payload_entry(
|
||||||
|
path: &Path,
|
||||||
|
root: &Path,
|
||||||
|
hash: &mut sha2::Sha256,
|
||||||
|
) -> Result<(), ConfigSyncError> {
|
||||||
|
use sha2::Digest;
|
||||||
|
let relative = path.strip_prefix(root).map_err(std::io::Error::other)?;
|
||||||
|
let bytes = relative.as_os_str().as_encoded_bytes();
|
||||||
|
hash.update((bytes.len() as u64).to_le_bytes());
|
||||||
|
hash.update(bytes);
|
||||||
|
let kind = std::fs::symlink_metadata(path)?.file_type();
|
||||||
|
if kind.is_symlink() {
|
||||||
|
hash.update(b"link");
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
use std::os::windows::fs::FileTypeExt;
|
||||||
|
hash.update([u8::from(kind.is_symlink_dir())]);
|
||||||
|
}
|
||||||
|
let target = std::fs::read_link(path)?;
|
||||||
|
let bytes = target.as_os_str().as_encoded_bytes();
|
||||||
|
hash.update((bytes.len() as u64).to_le_bytes());
|
||||||
|
hash.update(bytes);
|
||||||
|
} else if kind.is_file() {
|
||||||
|
hash.update(b"file");
|
||||||
|
hash.update(
|
||||||
|
crate::instance::content::manifest::fingerprint(path)?.hashes["sha512"].as_bytes(),
|
||||||
|
);
|
||||||
|
} else if kind.is_dir() {
|
||||||
|
hash.update(b"dir");
|
||||||
|
let mut entries = std::fs::read_dir(path)?
|
||||||
|
.map(|entry| entry.map(|entry| entry.path()))
|
||||||
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
|
entries.sort();
|
||||||
|
for entry in entries {
|
||||||
|
hash_payload_entry(&entry, root, hash)?;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Err(std::io::Error::other(format!(
|
||||||
|
"Unsupported config entry '{}'",
|
||||||
|
path.display()
|
||||||
|
))
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn profile_exists(dir: &Path) -> Result<bool, ConfigSyncError> {
|
||||||
|
match std::fs::symlink_metadata(dir) {
|
||||||
|
Ok(metadata) if metadata.is_dir() && !metadata.file_type().is_symlink() => Ok(true),
|
||||||
|
Ok(_) => Err(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::InvalidInput,
|
||||||
|
format!(
|
||||||
|
"Config profile must be a real directory: '{}'",
|
||||||
|
dir.display()
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.into()),
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
|
||||||
|
Err(error) => Err(error.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn require_source_dir(src: &Path) -> Result<(), ConfigSyncError> {
|
||||||
|
let metadata = std::fs::metadata(src).map_err(|error| {
|
||||||
|
std::io::Error::new(
|
||||||
|
error.kind(),
|
||||||
|
format!(
|
||||||
|
"Cannot read config sync source '{}': {error}",
|
||||||
|
src.display()
|
||||||
|
),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
if !metadata.is_dir() {
|
||||||
|
return Err(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::InvalidInput,
|
||||||
|
format!("Config sync source is not a directory: '{}'", src.display()),
|
||||||
|
)
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_config_root(dir: &Path) -> Result<(), ConfigSyncError> {
|
||||||
|
let config = dir.join("config");
|
||||||
|
if entry_exists(&config)? && std::fs::symlink_metadata(&config)?.file_type().is_symlink() {
|
||||||
|
return Err(std::io::Error::other(format!(
|
||||||
|
"Cannot mirror symlinked config directory '{}'",
|
||||||
|
config.display()
|
||||||
|
))
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sync_to_profile(minecraft_dir: &Path, profile_dir: &Path) -> Result<(), ConfigSyncError> {
|
||||||
|
mirror_payload(minecraft_dir, profile_dir, true, || Ok(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
fn sync_from_profile(profile_dir: &Path, minecraft_dir: &Path) -> Result<(), ConfigSyncError> {
|
||||||
|
mirror_payload(profile_dir, minecraft_dir, true, || Ok(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn profile_payload_exists(profile_dir: &Path) -> Result<bool, ConfigSyncError> {
|
||||||
|
Ok(!payload_names(profile_dir, true)?.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
fn mirror_options(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> {
|
||||||
|
mirror_payload(src, dst, false, || Ok(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn entry_exists(path: &Path) -> Result<bool, ConfigSyncError> {
|
||||||
|
match std::fs::symlink_metadata(path) {
|
||||||
|
Ok(_) => Ok(true),
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
|
||||||
|
Err(error) => Err(error.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove_if_exists(path: &Path) -> Result<(), ConfigSyncError> {
|
||||||
|
if entry_exists(path)? {
|
||||||
|
remove_path(path)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cleanup_sync_path(path: &Path) {
|
||||||
|
if let Err(error) = remove_if_exists(path) {
|
||||||
|
tracing::warn!(
|
||||||
|
"Could not remove config sync staging/backup '{}': {error}",
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn payload_names(
|
||||||
|
dir: &Path,
|
||||||
|
include_config: bool,
|
||||||
|
) -> Result<Vec<std::ffi::OsString>, ConfigSyncError> {
|
||||||
|
if !entry_exists(dir)? {
|
||||||
|
return Ok(Vec::new());
|
||||||
|
}
|
||||||
|
let mut names = Vec::new();
|
||||||
|
for entry in std::fs::read_dir(dir)? {
|
||||||
|
let entry = entry?;
|
||||||
|
let name = entry.file_name();
|
||||||
|
let kind = entry.file_type()?;
|
||||||
|
if include_config && name == "config"
|
||||||
|
|| is_options_file(&name.to_string_lossy()) && (kind.is_file() || kind.is_symlink())
|
||||||
|
{
|
||||||
|
names.push(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
names.sort();
|
||||||
|
Ok(names)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rollback_payload(
|
||||||
|
dst: &Path,
|
||||||
|
backup: &Path,
|
||||||
|
installed: &[std::ffi::OsString],
|
||||||
|
moved: &[std::ffi::OsString],
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let mut errors = Vec::new();
|
||||||
|
for name in installed.iter().rev() {
|
||||||
|
if let Err(error) = remove_if_exists(&dst.join(name)) {
|
||||||
|
errors.push(format!("Removing '{}': {error}", dst.join(name).display()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for name in moved.iter().rev() {
|
||||||
|
let target = dst.join(name);
|
||||||
|
match entry_exists(&target) {
|
||||||
|
Ok(false) => {
|
||||||
|
if let Err(error) = std::fs::rename(backup.join(name), &target) {
|
||||||
|
errors.push(format!("Restoring '{}': {error}", target.display()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(true) => errors.push(format!("Cannot restore occupied '{}'", target.display())),
|
||||||
|
Err(error) => errors.push(format!("Inspecting '{}': {error}", target.display())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if errors.is_empty() {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(errors.join("; "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mirror_payload<T>(
|
||||||
|
src: &Path,
|
||||||
|
dst: &Path,
|
||||||
|
include_config: bool,
|
||||||
|
commit: impl FnOnce() -> Result<T, ConfigSyncError>,
|
||||||
|
) -> Result<T, ConfigSyncError> {
|
||||||
|
require_source_dir(src)?;
|
||||||
|
let parent = dst
|
||||||
|
.parent()
|
||||||
|
.filter(|parent| !parent.as_os_str().is_empty())
|
||||||
|
.ok_or_else(|| std::io::Error::other(format!("No parent for '{}'", dst.display())))?;
|
||||||
|
std::fs::create_dir_all(dst)?;
|
||||||
|
if include_config {
|
||||||
|
check_config_root(src)?;
|
||||||
|
check_config_root(dst)?;
|
||||||
|
let old_backup = dst.join(".config.mirror-backup");
|
||||||
|
if entry_exists(&old_backup)? {
|
||||||
|
return Err(std::io::Error::other(format!(
|
||||||
|
"Previous config backup remains at '{}'",
|
||||||
|
old_backup.display()
|
||||||
|
))
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let name = dst
|
||||||
|
.file_name()
|
||||||
|
.and_then(|name| name.to_str())
|
||||||
|
.unwrap_or("payload");
|
||||||
|
let staging = parent.join(format!(".{name}.sync-stage"));
|
||||||
|
let backup = parent.join(format!(".{name}.sync-backup"));
|
||||||
|
// An existing backup belongs to an interrupted transaction and must survive for recovery.
|
||||||
|
std::fs::create_dir(&backup).map_err(|error| {
|
||||||
|
std::io::Error::new(
|
||||||
|
error.kind(),
|
||||||
|
format!("Cannot create backup '{}': {error}", backup.display()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let mut moved = Vec::new();
|
||||||
|
let mut installed = Vec::new();
|
||||||
|
let result = (|| {
|
||||||
|
remove_if_exists(&staging)?;
|
||||||
|
std::fs::create_dir(&staging)?;
|
||||||
|
if include_config {
|
||||||
|
std::fs::create_dir(staging.join("config"))?;
|
||||||
|
if entry_exists(&src.join("config"))? {
|
||||||
|
copy_dir_contents(
|
||||||
|
&src.join("config"),
|
||||||
|
&staging.join("config"),
|
||||||
|
src,
|
||||||
|
include_config,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for name in payload_names(src, false)? {
|
||||||
|
let source = src.join(&name);
|
||||||
|
let target = staging.join(&name);
|
||||||
|
if std::fs::symlink_metadata(&source)?.file_type().is_symlink() {
|
||||||
|
copy_payload_symlink(&source, &target, src, include_config)?;
|
||||||
|
} else {
|
||||||
|
std::fs::copy(&source, &target)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for name in payload_names(dst, include_config)? {
|
||||||
|
std::fs::rename(dst.join(&name), backup.join(&name))?;
|
||||||
|
moved.push(name);
|
||||||
|
}
|
||||||
|
for name in payload_names(&staging, include_config)? {
|
||||||
|
std::fs::rename(staging.join(&name), dst.join(&name))?;
|
||||||
|
installed.push(name);
|
||||||
|
}
|
||||||
|
commit()
|
||||||
|
})();
|
||||||
|
let result = match result {
|
||||||
|
Ok(value) => {
|
||||||
|
cleanup_sync_path(&backup);
|
||||||
|
Ok(value)
|
||||||
|
}
|
||||||
|
Err(error) => match rollback_payload(dst, &backup, &installed, &moved) {
|
||||||
|
Ok(()) => {
|
||||||
|
cleanup_sync_path(&backup);
|
||||||
|
Err(error)
|
||||||
|
}
|
||||||
|
Err(rollback) => Err(ConfigSyncError::SaveRollback {
|
||||||
|
save: error.to_string(),
|
||||||
|
rollback: format!(
|
||||||
|
"{rollback}; recovery backup retained at '{}'",
|
||||||
|
backup.display()
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
cleanup_sync_path(&staging);
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_options_file(name: &str) -> bool {
|
||||||
|
name == "options.txt" || name.starts_with("options") && name.ends_with(".txt")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove_path(path: &Path) -> Result<(), ConfigSyncError> {
|
||||||
|
let meta = std::fs::symlink_metadata(path)?;
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
use std::os::windows::fs::FileTypeExt;
|
||||||
|
if meta.file_type().is_symlink_dir() {
|
||||||
|
std::fs::remove_dir(path)?;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if meta.is_dir() {
|
||||||
|
std::fs::remove_dir_all(path)?;
|
||||||
|
} else {
|
||||||
|
std::fs::remove_file(path)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn copy_dir_contents(
|
||||||
|
src: &Path,
|
||||||
|
dst: &Path,
|
||||||
|
payload: &Path,
|
||||||
|
include_config: bool,
|
||||||
|
) -> Result<(), ConfigSyncError> {
|
||||||
|
for entry in std::fs::read_dir(src)? {
|
||||||
|
let entry = entry?;
|
||||||
|
let source = entry.path();
|
||||||
|
let target = dst.join(entry.file_name());
|
||||||
|
let file_type = entry.file_type()?;
|
||||||
|
|
||||||
|
if file_type.is_dir() {
|
||||||
|
std::fs::create_dir_all(&target)?;
|
||||||
|
copy_dir_contents(&source, &target, payload, include_config)?;
|
||||||
|
} else if file_type.is_file() {
|
||||||
|
std::fs::copy(&source, &target)?;
|
||||||
|
} else if file_type.is_symlink() {
|
||||||
|
copy_payload_symlink(&source, &target, payload, include_config)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn copy_payload_symlink(
|
||||||
|
source: &Path,
|
||||||
|
destination: &Path,
|
||||||
|
payload: &Path,
|
||||||
|
include_config: bool,
|
||||||
|
) -> Result<(), ConfigSyncError> {
|
||||||
|
let mut target = std::fs::read_link(source)?;
|
||||||
|
if target.is_relative() {
|
||||||
|
let relative = source
|
||||||
|
.strip_prefix(payload)
|
||||||
|
.map_err(std::io::Error::other)?;
|
||||||
|
let mut position = relative.parent().unwrap_or(Path::new("")).to_owned();
|
||||||
|
let mut internal = true;
|
||||||
|
for component in target.components() {
|
||||||
|
match component {
|
||||||
|
std::path::Component::Normal(name) => position.push(name),
|
||||||
|
std::path::Component::CurDir => {}
|
||||||
|
std::path::Component::ParentDir => {
|
||||||
|
if !position.pop() {
|
||||||
|
internal = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
internal = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(first) = position.components().next() {
|
||||||
|
let name = first.as_os_str();
|
||||||
|
if include_config && name == "config" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !is_options_file(&name.to_string_lossy()) {
|
||||||
|
internal = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
match std::fs::symlink_metadata(payload.join(name)) {
|
||||||
|
Ok(metadata) if metadata.is_file() || metadata.file_type().is_symlink() => {}
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||||
|
Err(error) => return Err(error.into()),
|
||||||
|
_ => {
|
||||||
|
internal = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
internal &= !position.as_os_str().is_empty();
|
||||||
|
if !internal {
|
||||||
|
// External links keep their source anchor; internal links move with the payload.
|
||||||
|
let anchored = std::path::absolute(source.parent().unwrap().join(target))?;
|
||||||
|
target = match (anchored.parent(), anchored.file_name()) {
|
||||||
|
(Some(parent), Some(name)) => match std::fs::canonicalize(parent) {
|
||||||
|
Ok(parent) => parent.join(name),
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => anchored,
|
||||||
|
Err(error) => return Err(error.into()),
|
||||||
|
},
|
||||||
|
_ => std::fs::canonicalize(anchored)?,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
crate::storage::copy_symlink_target(source, destination, &target)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "tests/config_sync.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use super::entry::ContentEntry;
|
||||||
|
|
||||||
|
pub fn scan_one_datapack(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||||
|
super::packs::scan_one_pack(path, file_stem, enabled)
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,64 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use super::icons::IconCell;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum WorldGameMode {
|
||||||
|
Survival,
|
||||||
|
Creative,
|
||||||
|
Adventure,
|
||||||
|
Spectator,
|
||||||
|
Hardcore,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WorldGameMode {
|
||||||
|
pub fn label(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Survival => "Survival",
|
||||||
|
Self::Creative => "Creative",
|
||||||
|
Self::Adventure => "Adventure",
|
||||||
|
Self::Spectator => "Spectator",
|
||||||
|
Self::Hardcore => "Hardcore",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct WorldDetails {
|
||||||
|
pub game_mode: Option<WorldGameMode>,
|
||||||
|
pub last_played: Option<chrono::DateTime<chrono::Utc>>,
|
||||||
|
pub minecraft_version: Option<String>,
|
||||||
|
pub size: Option<String>,
|
||||||
|
pub datapacks: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ContentEntry {
|
||||||
|
pub file_stem: String,
|
||||||
|
pub name: String,
|
||||||
|
pub source_slug: Option<String>,
|
||||||
|
pub installed_path: Option<PathBuf>,
|
||||||
|
pub provider_project: Option<super::manifest::ProviderProject>,
|
||||||
|
pub world_details: Option<WorldDetails>,
|
||||||
|
pub title_suffix: Option<String>,
|
||||||
|
pub footer_label: Option<String>,
|
||||||
|
pub footer_change: Option<(String, String)>,
|
||||||
|
pub description: String,
|
||||||
|
pub enabled: bool,
|
||||||
|
pub icon_bytes: Option<Vec<u8>>,
|
||||||
|
pub provider_icon: bool,
|
||||||
|
pub provider_description: bool,
|
||||||
|
pub path: PathBuf,
|
||||||
|
pub icon_lines: Option<Vec<Vec<IconCell>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn toggle_entry(entry: &ContentEntry) -> Result<(), std::io::Error> {
|
||||||
|
toggle_entry_path(entry).map(drop)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn toggle_entry_path(entry: &ContentEntry) -> Result<Option<PathBuf>, std::io::Error> {
|
||||||
|
super::local::toggle(entry)
|
||||||
|
}
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct IconCell {
|
||||||
|
pub symbol: char,
|
||||||
|
pub bg_r: u8,
|
||||||
|
pub bg_g: u8,
|
||||||
|
pub bg_b: u8,
|
||||||
|
pub fg_r: u8,
|
||||||
|
pub fg_g: u8,
|
||||||
|
pub fg_b: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn make_icon_pixels(
|
||||||
|
bytes: &[u8],
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
) -> Option<Vec<Vec<IconCell>>> {
|
||||||
|
let image = image::load_from_memory(bytes).ok()?;
|
||||||
|
Some(make_icon_pixels_from_image(&image, width, height))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn make_icon_pixels_from_image(
|
||||||
|
image: &image::DynamicImage,
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
) -> Vec<Vec<IconCell>> {
|
||||||
|
let resized = image.resize_exact(
|
||||||
|
u32::from(width),
|
||||||
|
u32::from(height) * 2,
|
||||||
|
image::imageops::FilterType::Nearest,
|
||||||
|
);
|
||||||
|
let rgb = resized.to_rgb8();
|
||||||
|
|
||||||
|
let mut rows = Vec::new();
|
||||||
|
for row in 0..height {
|
||||||
|
let mut columns = Vec::new();
|
||||||
|
for column in 0..width {
|
||||||
|
let top_y = u32::from(row) * 2;
|
||||||
|
let bottom_y = (top_y + 1).min(rgb.height().saturating_sub(1));
|
||||||
|
let [tr, tg, tb] = rgb.get_pixel(u32::from(column), top_y).0;
|
||||||
|
let [br, bg, bb] = rgb.get_pixel(u32::from(column), bottom_y).0;
|
||||||
|
columns.push(IconCell {
|
||||||
|
symbol: '\u{2580}',
|
||||||
|
bg_r: br,
|
||||||
|
bg_g: bg,
|
||||||
|
bg_b: bb,
|
||||||
|
fg_r: tr,
|
||||||
|
fg_g: tg,
|
||||||
|
fg_b: tb,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
rows.push(columns);
|
||||||
|
}
|
||||||
|
rows
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn make_icon_quadrants_from_image(
|
||||||
|
image: &image::DynamicImage,
|
||||||
|
width: u16,
|
||||||
|
height: u16,
|
||||||
|
) -> Vec<Vec<IconCell>> {
|
||||||
|
let resized = image
|
||||||
|
.resize_exact(
|
||||||
|
u32::from(width) * 2,
|
||||||
|
u32::from(height) * 2,
|
||||||
|
image::imageops::FilterType::Lanczos3,
|
||||||
|
)
|
||||||
|
.to_rgb8();
|
||||||
|
|
||||||
|
(0..height)
|
||||||
|
.map(|row| {
|
||||||
|
(0..width)
|
||||||
|
.map(|column| {
|
||||||
|
let x = u32::from(column) * 2;
|
||||||
|
let y = u32::from(row) * 2;
|
||||||
|
quadrant_cell([
|
||||||
|
resized.get_pixel(x, y).0,
|
||||||
|
resized.get_pixel(x + 1, y).0,
|
||||||
|
resized.get_pixel(x, y + 1).0,
|
||||||
|
resized.get_pixel(x + 1, y + 1).0,
|
||||||
|
])
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn quadrant_cell(pixels: [[u8; 3]; 4]) -> IconCell {
|
||||||
|
let mut pair = (0, 0);
|
||||||
|
let mut max_distance = 0;
|
||||||
|
for left in 0..pixels.len() {
|
||||||
|
for right in (left + 1)..pixels.len() {
|
||||||
|
let distance = color_distance(pixels[left], pixels[right]);
|
||||||
|
if distance > max_distance {
|
||||||
|
max_distance = distance;
|
||||||
|
pair = (left, right);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let bg = pixels[pair.0];
|
||||||
|
let fg = pixels[pair.1];
|
||||||
|
let mask = pixels
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.fold(0_u8, |mask, (index, pixel)| {
|
||||||
|
if color_distance(*pixel, fg) <= color_distance(*pixel, bg) {
|
||||||
|
mask | (1 << index)
|
||||||
|
} else {
|
||||||
|
mask
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let symbol = match mask {
|
||||||
|
0 => ' ',
|
||||||
|
1 => '\u{2598}',
|
||||||
|
2 => '\u{259d}',
|
||||||
|
3 => '\u{2580}',
|
||||||
|
4 => '\u{2596}',
|
||||||
|
5 => '\u{258c}',
|
||||||
|
6 => '\u{259e}',
|
||||||
|
7 => '\u{259b}',
|
||||||
|
8 => '\u{2597}',
|
||||||
|
9 => '\u{259a}',
|
||||||
|
10 => '\u{2590}',
|
||||||
|
11 => '\u{259c}',
|
||||||
|
12 => '\u{2584}',
|
||||||
|
13 => '\u{2599}',
|
||||||
|
14 => '\u{259f}',
|
||||||
|
_ => '\u{2588}',
|
||||||
|
};
|
||||||
|
|
||||||
|
IconCell {
|
||||||
|
symbol,
|
||||||
|
bg_r: bg[0],
|
||||||
|
bg_g: bg[1],
|
||||||
|
bg_b: bg[2],
|
||||||
|
fg_r: fg[0],
|
||||||
|
fg_g: fg[1],
|
||||||
|
fg_b: fg[2],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn color_distance(left: [u8; 3], right: [u8; 3]) -> u32 {
|
||||||
|
left.into_iter()
|
||||||
|
.zip(right)
|
||||||
|
.map(|(left, right)| {
|
||||||
|
let delta = i32::from(left) - i32::from(right);
|
||||||
|
(delta * delta) as u32
|
||||||
|
})
|
||||||
|
.sum()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6 columns by 3 terminal rows is physically square with the usual 1:2 cell ratio.
|
||||||
|
pub(crate) fn fallback_icon() -> Vec<Vec<IconCell>> {
|
||||||
|
const MASK: [[bool; 6]; 6] = [
|
||||||
|
[false, true, true, true, true, false],
|
||||||
|
[true, false, false, false, false, true],
|
||||||
|
[false, false, false, true, true, false],
|
||||||
|
[false, false, true, true, false, false],
|
||||||
|
[false, false, false, false, false, false],
|
||||||
|
[false, false, true, true, false, false],
|
||||||
|
];
|
||||||
|
MASK.as_chunks::<2>()
|
||||||
|
.0
|
||||||
|
.iter()
|
||||||
|
.map(|pair| {
|
||||||
|
pair[0]
|
||||||
|
.iter()
|
||||||
|
.zip(pair[1])
|
||||||
|
.map(|(&top, bottom)| fallback_cell(top, bottom))
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fallback_cell(top: bool, bottom: bool) -> IconCell {
|
||||||
|
let background = if top { 150 } else { 45 };
|
||||||
|
let foreground = if bottom { 150 } else { 45 };
|
||||||
|
IconCell {
|
||||||
|
symbol: '\u{2584}',
|
||||||
|
bg_r: background,
|
||||||
|
bg_g: background,
|
||||||
|
bg_b: background,
|
||||||
|
fg_r: foreground,
|
||||||
|
fg_g: foreground,
|
||||||
|
fg_b: foreground,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn fallback_icon_large() -> Vec<Vec<IconCell>> {
|
||||||
|
let background = IconCell {
|
||||||
|
symbol: '\u{2584}',
|
||||||
|
bg_r: 50,
|
||||||
|
bg_g: 50,
|
||||||
|
bg_b: 50,
|
||||||
|
fg_r: 50,
|
||||||
|
fg_g: 50,
|
||||||
|
fg_b: 50,
|
||||||
|
};
|
||||||
|
let bottom = IconCell {
|
||||||
|
symbol: '\u{2584}',
|
||||||
|
bg_r: 50,
|
||||||
|
bg_g: 50,
|
||||||
|
bg_b: 50,
|
||||||
|
fg_r: 130,
|
||||||
|
fg_g: 130,
|
||||||
|
fg_b: 130,
|
||||||
|
};
|
||||||
|
let top = IconCell {
|
||||||
|
symbol: '\u{2584}',
|
||||||
|
bg_r: 130,
|
||||||
|
bg_g: 130,
|
||||||
|
bg_b: 130,
|
||||||
|
fg_r: 50,
|
||||||
|
fg_g: 50,
|
||||||
|
fg_b: 50,
|
||||||
|
};
|
||||||
|
vec![
|
||||||
|
vec![
|
||||||
|
background, background, bottom, bottom, bottom, bottom, bottom, bottom, bottom, bottom,
|
||||||
|
background, background,
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
background, background, bottom, bottom, bottom, bottom, bottom, bottom, bottom, bottom,
|
||||||
|
background, background,
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
background, background, background, background, background, background, top, top, top,
|
||||||
|
top, background, background,
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
background, background, background, background, background, background, top, top, top,
|
||||||
|
top, background, background,
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
background, background, background, background, top, top, top, top, background,
|
||||||
|
background, background, background,
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
background, background, background, background, top, top, top, top, background,
|
||||||
|
background, background, background,
|
||||||
|
],
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/content/icons.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,442 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use std::io;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use super::entry::ContentEntry;
|
||||||
|
use super::manifest::{
|
||||||
|
ContentFileRecord, ContentLock, ContentManifest, FileFingerprint, fingerprint,
|
||||||
|
fingerprint_metadata,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(crate) struct StagingDirectory {
|
||||||
|
path: PathBuf,
|
||||||
|
retained: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StagingDirectory {
|
||||||
|
pub(crate) fn new(minecraft_dir: &Path) -> io::Result<Self> {
|
||||||
|
std::fs::create_dir_all(minecraft_dir)?;
|
||||||
|
Ok(Self {
|
||||||
|
path: tempfile::Builder::new()
|
||||||
|
.prefix(".rmcl-install-")
|
||||||
|
.tempdir_in(minecraft_dir)?
|
||||||
|
.keep(),
|
||||||
|
retained: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn path(&self) -> &Path {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for StagingDirectory {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if !self.retained
|
||||||
|
&& !std::thread::panicking()
|
||||||
|
&& let Err(error) = std::fs::remove_dir_all(&self.path)
|
||||||
|
&& error.kind() != io::ErrorKind::NotFound
|
||||||
|
{
|
||||||
|
tracing::warn!(
|
||||||
|
"Could not remove content staging '{}': {error}",
|
||||||
|
self.path.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct FileTransaction {
|
||||||
|
staging: StagingDirectory,
|
||||||
|
moves: Vec<(PathBuf, PathBuf)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FileTransaction {
|
||||||
|
pub(crate) fn new(staging: StagingDirectory) -> Self {
|
||||||
|
Self {
|
||||||
|
staging,
|
||||||
|
moves: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn staging(&self) -> &Path {
|
||||||
|
self.staging.path()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn move_path(&mut self, from: &Path, to: &Path) -> io::Result<()> {
|
||||||
|
require_absent(to)?;
|
||||||
|
std::fs::rename(from, to)?;
|
||||||
|
self.moves.push((from.to_owned(), to.to_owned()));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn finish<T, E: From<io::Error> + std::fmt::Display>(
|
||||||
|
&mut self,
|
||||||
|
result: Result<T, E>,
|
||||||
|
) -> Result<T, E> {
|
||||||
|
match result {
|
||||||
|
Ok(value) => {
|
||||||
|
self.moves.clear();
|
||||||
|
Ok(value)
|
||||||
|
}
|
||||||
|
Err(error) => match self.rollback() {
|
||||||
|
Ok(()) => Err(error),
|
||||||
|
Err(rollback) => Err(io::Error::other(format!("{error}; {rollback}")).into()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rollback(&mut self) -> io::Result<()> {
|
||||||
|
let mut errors = Vec::new();
|
||||||
|
for (from, to) in self.moves.iter().rev() {
|
||||||
|
if let Err(error) = require_absent(from).and_then(|()| std::fs::rename(to, from)) {
|
||||||
|
errors.push(format!(
|
||||||
|
"restore '{}' from '{}': {error}",
|
||||||
|
from.display(),
|
||||||
|
to.display()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.moves.clear();
|
||||||
|
if errors.is_empty() {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
self.staging.retained = true;
|
||||||
|
Err(io::Error::other(format!(
|
||||||
|
"Content rollback failed: {}; recovery staging retained at '{}'",
|
||||||
|
errors.join("; "),
|
||||||
|
self.staging.path.display()
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for FileTransaction {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if !self.moves.is_empty()
|
||||||
|
&& let Err(error) = self.rollback()
|
||||||
|
{
|
||||||
|
tracing::error!("{error}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn require_absent(path: &Path) -> io::Result<()> {
|
||||||
|
match std::fs::symlink_metadata(path) {
|
||||||
|
Ok(_) => Err(io::Error::new(
|
||||||
|
io::ErrorKind::AlreadyExists,
|
||||||
|
format!("'{}' already exists", path.display()),
|
||||||
|
)),
|
||||||
|
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
|
||||||
|
Err(error) => Err(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn relative_path(minecraft_dir: &Path, path: &Path) -> io::Result<PathBuf> {
|
||||||
|
let relative = path.strip_prefix(minecraft_dir).map_err(|_| {
|
||||||
|
io::Error::new(
|
||||||
|
io::ErrorKind::InvalidInput,
|
||||||
|
format!("'{}' is outside the Minecraft directory", path.display()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
if !crate::storage::safe_relative_path(relative) {
|
||||||
|
return Err(io::Error::new(
|
||||||
|
io::ErrorKind::InvalidInput,
|
||||||
|
format!("Invalid content path '{}'", path.display()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let root = minecraft_dir.canonicalize()?;
|
||||||
|
let mut parent = path
|
||||||
|
.parent()
|
||||||
|
.ok_or_else(|| io::Error::other("Content path has no parent"))?;
|
||||||
|
loop {
|
||||||
|
match parent.canonicalize() {
|
||||||
|
Ok(parent) if parent.starts_with(&root) => break,
|
||||||
|
Ok(_) => {
|
||||||
|
return Err(io::Error::new(
|
||||||
|
io::ErrorKind::InvalidInput,
|
||||||
|
format!(
|
||||||
|
"Content path '{}' escapes through a symlink",
|
||||||
|
path.display()
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Err(error) if error.kind() == io::ErrorKind::NotFound => {
|
||||||
|
parent = parent.parent().ok_or(error)?;
|
||||||
|
}
|
||||||
|
Err(error) => return Err(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(relative.to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn validate_record(minecraft_dir: &Path, record: &ContentFileRecord) -> io::Result<()> {
|
||||||
|
let path = minecraft_dir.join(&record.relative_path);
|
||||||
|
relative_path(minecraft_dir, &path)?;
|
||||||
|
if current_fingerprint(&path, &record.fingerprint)? != record.fingerprint {
|
||||||
|
return Err(io::Error::other(format!(
|
||||||
|
"Content '{}' changed; refresh before retrying",
|
||||||
|
path.display()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn current_fingerprint(
|
||||||
|
path: &Path,
|
||||||
|
expected: &FileFingerprint,
|
||||||
|
) -> io::Result<FileFingerprint> {
|
||||||
|
let metadata = std::fs::symlink_metadata(path)?;
|
||||||
|
if metadata.file_type().is_symlink() {
|
||||||
|
return Err(io::Error::new(
|
||||||
|
io::ErrorKind::InvalidInput,
|
||||||
|
format!("Content '{}' is a symlink", path.display()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if metadata.is_dir() {
|
||||||
|
directory_fingerprint_metadata(path)
|
||||||
|
} else if metadata.is_file() && expected.hashes.is_empty() {
|
||||||
|
fingerprint_metadata(path)
|
||||||
|
} else if metadata.is_file() {
|
||||||
|
fingerprint(path)
|
||||||
|
} else {
|
||||||
|
Err(io::Error::new(
|
||||||
|
io::ErrorKind::InvalidInput,
|
||||||
|
format!("Content '{}' is not a file or directory", path.display()),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn directory_fingerprint_metadata(path: &Path) -> io::Result<FileFingerprint> {
|
||||||
|
fn accumulate(path: &Path, size: &mut u64, modified_ns: &mut u128) -> io::Result<()> {
|
||||||
|
for entry in std::fs::read_dir(path)? {
|
||||||
|
let entry = entry?;
|
||||||
|
let metadata = std::fs::symlink_metadata(entry.path())?;
|
||||||
|
if metadata.file_type().is_symlink() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let modified = metadata
|
||||||
|
.modified()
|
||||||
|
.unwrap_or(SystemTime::UNIX_EPOCH)
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.unwrap_or_default()
|
||||||
|
.as_nanos();
|
||||||
|
*modified_ns = (*modified_ns).max(modified);
|
||||||
|
if metadata.is_dir() {
|
||||||
|
accumulate(&entry.path(), size, modified_ns)?;
|
||||||
|
} else if metadata.is_file() {
|
||||||
|
*size = size.saturating_add(metadata.len());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
let mut size = 0;
|
||||||
|
let mut modified_ns = 0;
|
||||||
|
accumulate(path, &mut size, &mut modified_ns)?;
|
||||||
|
Ok(FileFingerprint {
|
||||||
|
size,
|
||||||
|
modified_ns,
|
||||||
|
hashes: Default::default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn toggle(entry: &ContentEntry) -> io::Result<Option<PathBuf>> {
|
||||||
|
let Some(name) = entry.path.file_name().and_then(|name| name.to_str()) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let disabled = name.ends_with(".disabled");
|
||||||
|
if disabled == entry.enabled {
|
||||||
|
return Err(io::Error::other(format!(
|
||||||
|
"Enabled state of '{}' changed; refresh before retrying",
|
||||||
|
entry.path.display()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let new_name = if entry.enabled {
|
||||||
|
format!("{name}.disabled")
|
||||||
|
} else {
|
||||||
|
name.trim_end_matches(".disabled").to_owned()
|
||||||
|
};
|
||||||
|
let new_path = entry.path.with_file_name(new_name);
|
||||||
|
let instance_minecraft = entry.path.ancestors().find(|path| {
|
||||||
|
path.file_name()
|
||||||
|
.is_some_and(|name| name == crate::storage::MINECRAFT_DIR_NAME)
|
||||||
|
&& entry.path.strip_prefix(path).is_ok_and(|relative| {
|
||||||
|
relative.components().next().is_some_and(|component| {
|
||||||
|
matches!(component, std::path::Component::Normal(name)
|
||||||
|
if name == "mods" || name == "resourcepacks" || name == "shaderpacks" || name == "saves")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
});
|
||||||
|
let minecraft_dir = instance_minecraft
|
||||||
|
.or_else(|| entry.path.parent())
|
||||||
|
.ok_or_else(|| io::Error::other("Content path has no parent"))?;
|
||||||
|
let manifest_path = if let Some(minecraft) = instance_minecraft {
|
||||||
|
crate::storage::InstancePaths::new(
|
||||||
|
minecraft
|
||||||
|
.parent()
|
||||||
|
.ok_or_else(|| io::Error::other("Minecraft directory has no instance parent"))?,
|
||||||
|
)
|
||||||
|
.content_manifest()
|
||||||
|
} else {
|
||||||
|
minecraft_dir.join(".rmcl-content.json")
|
||||||
|
};
|
||||||
|
let lock = ContentLock::acquire(&manifest_path).map_err(io::Error::other)?;
|
||||||
|
let mut manifest = if instance_minecraft.is_some() {
|
||||||
|
lock.load().map_err(io::Error::other)?
|
||||||
|
} else {
|
||||||
|
ContentManifest::default()
|
||||||
|
};
|
||||||
|
let relative = relative_path(minecraft_dir, &entry.path)?;
|
||||||
|
let new_relative = relative_path(minecraft_dir, &new_path)?;
|
||||||
|
require_absent(&new_path)?;
|
||||||
|
if manifest.record(&new_relative).is_some() {
|
||||||
|
return Err(io::Error::other(format!(
|
||||||
|
"Content manifest already owns '{}'",
|
||||||
|
new_path.display()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let record = manifest.record(&relative).cloned();
|
||||||
|
let previous = manifest.clone();
|
||||||
|
if let Some(project) = &entry.provider_project
|
||||||
|
&& record
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|record| record.project_for_provider(&project.provider, &project.project_id))
|
||||||
|
!= Some(project)
|
||||||
|
{
|
||||||
|
return Err(io::Error::other(format!(
|
||||||
|
"Ownership of '{}' changed; refresh before retrying",
|
||||||
|
entry.path.display()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
if let Some(record) = &record {
|
||||||
|
if record.enabled != entry.enabled {
|
||||||
|
return Err(io::Error::other(format!(
|
||||||
|
"Enabled state of '{}' changed; refresh before retrying",
|
||||||
|
entry.path.display()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
validate_record(minecraft_dir, record)?;
|
||||||
|
} else {
|
||||||
|
current_fingerprint(
|
||||||
|
&entry.path,
|
||||||
|
&FileFingerprint {
|
||||||
|
size: 0,
|
||||||
|
modified_ns: 0,
|
||||||
|
hashes: Default::default(),
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
let mut transaction = FileTransaction::new(StagingDirectory::new(minecraft_dir)?);
|
||||||
|
let result = (|| {
|
||||||
|
transaction.move_path(&entry.path, &new_path)?;
|
||||||
|
if let Some(mut record) = record {
|
||||||
|
manifest.remove(&relative);
|
||||||
|
record.relative_path = new_relative;
|
||||||
|
record.enabled = !entry.enabled;
|
||||||
|
manifest.upsert(record);
|
||||||
|
lock.save_if_unchanged(&manifest, &previous)
|
||||||
|
.map_err(io::Error::other)?;
|
||||||
|
}
|
||||||
|
Ok(Some(new_path))
|
||||||
|
})();
|
||||||
|
transaction.finish(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn record_toggle(
|
||||||
|
manifest: &mut ContentManifest,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
old_path: &Path,
|
||||||
|
new_path: &Path,
|
||||||
|
enabled: bool,
|
||||||
|
) -> io::Result<bool> {
|
||||||
|
let old_relative = relative_path(minecraft_dir, old_path)?;
|
||||||
|
let new_relative = relative_path(minecraft_dir, new_path)?;
|
||||||
|
match std::fs::symlink_metadata(old_path) {
|
||||||
|
Ok(_) => return Ok(false),
|
||||||
|
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||||
|
Err(error) => return Err(error),
|
||||||
|
}
|
||||||
|
if let Some(record) = manifest.record(&new_relative) {
|
||||||
|
if manifest.record(&old_relative).is_some() || record.enabled != enabled {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
validate_record(minecraft_dir, record)?;
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
let Some(record) = manifest.record(&old_relative) else {
|
||||||
|
return Ok(false);
|
||||||
|
};
|
||||||
|
let fresh = match current_fingerprint(new_path, &record.fingerprint) {
|
||||||
|
Ok(fresh) => fresh,
|
||||||
|
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
|
||||||
|
Err(error) => return Err(error),
|
||||||
|
};
|
||||||
|
Ok(
|
||||||
|
fresh == record.fingerprint
|
||||||
|
&& manifest.rename_record(&old_relative, &new_relative, enabled),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn remove(
|
||||||
|
manifest_path: &Path,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
path: &Path,
|
||||||
|
expected: &[ContentFileRecord],
|
||||||
|
orphan_only: bool,
|
||||||
|
) -> io::Result<(ContentManifest, Vec<PathBuf>)> {
|
||||||
|
let lock = ContentLock::acquire(manifest_path).map_err(io::Error::other)?;
|
||||||
|
let mut manifest = lock.load().map_err(io::Error::other)?;
|
||||||
|
let previous = manifest.clone();
|
||||||
|
let relative = relative_path(minecraft_dir, path)?;
|
||||||
|
if manifest
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.filter(|record| record.relative_path.starts_with(&relative))
|
||||||
|
.ne(expected.iter())
|
||||||
|
{
|
||||||
|
return Err(io::Error::other(format!(
|
||||||
|
"Ownership of '{}' changed; refresh before retrying",
|
||||||
|
path.display()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
if orphan_only && !manifest.orphaned_dependencies().contains(&relative) {
|
||||||
|
return Err(io::Error::other(format!(
|
||||||
|
"'{}' is no longer an unused dependency",
|
||||||
|
path.display()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
for record in expected {
|
||||||
|
match validate_record(minecraft_dir, record) {
|
||||||
|
Ok(()) => {}
|
||||||
|
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||||
|
Err(error) => return Err(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut transaction = FileTransaction::new(StagingDirectory::new(minecraft_dir)?);
|
||||||
|
let result = (|| {
|
||||||
|
let backup = transaction.staging().join("removed");
|
||||||
|
match std::fs::symlink_metadata(path) {
|
||||||
|
Ok(_) => transaction.move_path(path, &backup)?,
|
||||||
|
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||||
|
Err(error) => return Err(error),
|
||||||
|
}
|
||||||
|
manifest
|
||||||
|
.files
|
||||||
|
.retain(|record| !record.relative_path.starts_with(&relative));
|
||||||
|
let orphans = manifest
|
||||||
|
.orphaned_dependencies()
|
||||||
|
.into_iter()
|
||||||
|
.map(|relative| minecraft_dir.join(relative))
|
||||||
|
.collect();
|
||||||
|
lock.save_if_unchanged(&manifest, &previous)
|
||||||
|
.map_err(io::Error::other)?;
|
||||||
|
Ok((manifest, orphans))
|
||||||
|
})();
|
||||||
|
transaction.finish(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/content/local.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,581 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::fs::{File, OpenOptions};
|
||||||
|
use std::io::{Read, Seek};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sha1::Digest as _;
|
||||||
|
|
||||||
|
const MANIFEST_VERSION: u32 = 1;
|
||||||
|
|
||||||
|
pub(crate) struct ContentLock {
|
||||||
|
file: File,
|
||||||
|
_instance_lock: Option<crate::instance::runtime::InstanceLock>,
|
||||||
|
path: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ContentLock {
|
||||||
|
pub(crate) fn acquire(path: &Path) -> Result<Self, ManifestError> {
|
||||||
|
let parent = path.parent().ok_or_else(|| {
|
||||||
|
ManifestError::InvalidPath(format!("{} has no parent", path.display()))
|
||||||
|
})?;
|
||||||
|
let instance_dir = parent
|
||||||
|
.parent()
|
||||||
|
.filter(|state| {
|
||||||
|
path.file_name().is_some_and(|name| name == "manifest.json")
|
||||||
|
&& parent.file_name().is_some_and(|name| name == "content")
|
||||||
|
&& state
|
||||||
|
.file_name()
|
||||||
|
.is_some_and(|name| name == crate::storage::INSTANCE_STATE_DIR_NAME)
|
||||||
|
})
|
||||||
|
.and_then(Path::parent);
|
||||||
|
let instance_lock = if let Some(instance_dir) = instance_dir {
|
||||||
|
let root = instance_dir.parent().ok_or_else(|| {
|
||||||
|
ManifestError::InvalidPath(format!("{} has no instance root", path.display()))
|
||||||
|
})?;
|
||||||
|
let name = instance_dir
|
||||||
|
.file_name()
|
||||||
|
.and_then(|name| name.to_str())
|
||||||
|
.ok_or_else(|| {
|
||||||
|
ManifestError::InvalidPath(format!("{} has no instance name", path.display()))
|
||||||
|
})?;
|
||||||
|
Some(crate::instance::runtime::lock_instance(root, name).map_err(
|
||||||
|
|error| match error {
|
||||||
|
crate::instance::manager::InstanceError::InstanceRunning(_) => {
|
||||||
|
ManifestError::Busy(path.to_owned())
|
||||||
|
}
|
||||||
|
error => ManifestError::Io(std::io::Error::other(error)),
|
||||||
|
},
|
||||||
|
)?)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
std::fs::create_dir_all(parent)?;
|
||||||
|
let file = OpenOptions::new()
|
||||||
|
.read(true)
|
||||||
|
.write(true)
|
||||||
|
.create(true)
|
||||||
|
.truncate(false)
|
||||||
|
.open(path.with_extension("lock"))?;
|
||||||
|
if let Err(error) = fs2::FileExt::try_lock_exclusive(&file) {
|
||||||
|
if error.raw_os_error() == fs2::lock_contended_error().raw_os_error() {
|
||||||
|
return Err(ManifestError::Busy(path.to_owned()));
|
||||||
|
}
|
||||||
|
return Err(error.into());
|
||||||
|
}
|
||||||
|
Ok(Self {
|
||||||
|
file,
|
||||||
|
_instance_lock: instance_lock,
|
||||||
|
path: path.to_owned(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn load(&self) -> Result<ContentManifest, ManifestError> {
|
||||||
|
ContentManifest::load(&self.path)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn save(&self, manifest: &ContentManifest) -> Result<(), ManifestError> {
|
||||||
|
let bytes = serde_json::to_vec_pretty(manifest)?;
|
||||||
|
crate::storage::write_atomic(&self.path, &bytes)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn save_if_unchanged(
|
||||||
|
&self,
|
||||||
|
manifest: &ContentManifest,
|
||||||
|
previous: &ContentManifest,
|
||||||
|
) -> Result<(), ManifestError> {
|
||||||
|
let current = self.load()?;
|
||||||
|
if current.version != previous.version || current.files != previous.files {
|
||||||
|
return Err(ManifestError::Changed(self.path.clone()));
|
||||||
|
}
|
||||||
|
if manifest.version != previous.version || manifest.files != previous.files {
|
||||||
|
self.save(manifest)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for ContentLock {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Err(error) = fs2::FileExt::unlock(&self.file) {
|
||||||
|
tracing::warn!(
|
||||||
|
"Could not release content lock '{}': {error}",
|
||||||
|
self.path.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum ContentKind {
|
||||||
|
Mod,
|
||||||
|
ResourcePack,
|
||||||
|
Shader,
|
||||||
|
DataPack,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ContentKind {
|
||||||
|
pub fn directory(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Mod => "mods",
|
||||||
|
Self::ResourcePack => "resourcepacks",
|
||||||
|
Self::Shader => "shaderpacks",
|
||||||
|
Self::DataPack => "datapacks",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn unavailable_message(self, loader: crate::instance::ModLoader) -> Option<&'static str> {
|
||||||
|
if loader != crate::instance::ModLoader::Vanilla {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
match self {
|
||||||
|
Self::Mod => Some("Vanilla does not support mods."),
|
||||||
|
Self::Shader => Some("Vanilla does not support shaders."),
|
||||||
|
Self::ResourcePack | Self::DataPack => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct ProviderProject {
|
||||||
|
pub provider: String,
|
||||||
|
pub project_id: String,
|
||||||
|
pub version_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "status", rename_all = "snake_case")]
|
||||||
|
pub enum Resolution {
|
||||||
|
#[default]
|
||||||
|
Pending,
|
||||||
|
Resolved {
|
||||||
|
project: ProviderProject,
|
||||||
|
},
|
||||||
|
Unmatched {
|
||||||
|
checked_at: i64,
|
||||||
|
providers: Vec<String>,
|
||||||
|
},
|
||||||
|
Ambiguous {
|
||||||
|
candidates: Vec<ProviderProject>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct FileFingerprint {
|
||||||
|
pub size: u64,
|
||||||
|
pub modified_ns: u128,
|
||||||
|
pub hashes: BTreeMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FileFingerprint {
|
||||||
|
pub fn hash(&self, algorithm: &str) -> Option<&str> {
|
||||||
|
self.hashes.get(algorithm).map(String::as_str)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct ContentFileRecord {
|
||||||
|
pub relative_path: PathBuf,
|
||||||
|
pub kind: ContentKind,
|
||||||
|
pub enabled: bool,
|
||||||
|
pub fingerprint: FileFingerprint,
|
||||||
|
#[serde(default)]
|
||||||
|
pub resolution: Resolution,
|
||||||
|
#[serde(default)]
|
||||||
|
pub provider_aliases: Vec<ProviderProject>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub provider_checks: Vec<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub required_dependencies: Vec<ProviderProject>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub automatic_dependency: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub cleanup_eligible: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct ContentManifest {
|
||||||
|
pub version: u32,
|
||||||
|
#[serde(default)]
|
||||||
|
pub files: Vec<ContentFileRecord>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ContentManifest {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
version: MANIFEST_VERSION,
|
||||||
|
files: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ContentManifest {
|
||||||
|
pub fn load(path: &Path) -> Result<Self, ManifestError> {
|
||||||
|
let bytes = match std::fs::read(path) {
|
||||||
|
Ok(bytes) => bytes,
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||||
|
return Ok(Self::default());
|
||||||
|
}
|
||||||
|
Err(error) => return Err(error.into()),
|
||||||
|
};
|
||||||
|
let mut manifest: Self = serde_json::from_slice(&bytes)?;
|
||||||
|
if manifest.version != MANIFEST_VERSION {
|
||||||
|
return Err(ManifestError::UnsupportedVersion(manifest.version));
|
||||||
|
}
|
||||||
|
// record()/upsert() rely on files being sorted by relative_path;
|
||||||
|
// normalize here so hand-edited manifests can't break the lookups.
|
||||||
|
manifest
|
||||||
|
.files
|
||||||
|
.sort_by(|left, right| left.relative_path.cmp(&right.relative_path));
|
||||||
|
for (index, record) in manifest.files.iter().enumerate() {
|
||||||
|
if !crate::storage::safe_relative_path(&record.relative_path)
|
||||||
|
|| index > 0 && manifest.files[index - 1].relative_path == record.relative_path
|
||||||
|
{
|
||||||
|
return Err(ManifestError::InvalidPath(format!(
|
||||||
|
"Unsafe or duplicate content path '{}'",
|
||||||
|
record.relative_path.display()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(manifest)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save(&self, path: &Path) -> Result<(), ManifestError> {
|
||||||
|
ContentLock::acquire(path)?.save(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update<T>(
|
||||||
|
path: &Path,
|
||||||
|
update: impl FnOnce(&mut Self) -> Result<T, ManifestError>,
|
||||||
|
) -> Result<T, ManifestError> {
|
||||||
|
let lock = ContentLock::acquire(path)?;
|
||||||
|
let mut manifest = lock.load()?;
|
||||||
|
let previous = manifest.clone();
|
||||||
|
let result = update(&mut manifest)?;
|
||||||
|
lock.save_if_unchanged(&manifest, &previous)?;
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
// binary search: files is kept sorted by relative_path (see load/upsert),
|
||||||
|
// so per-file lookups stay O(log n) even for large manifests.
|
||||||
|
pub fn record(&self, relative_path: &Path) -> Option<&ContentFileRecord> {
|
||||||
|
let index = self
|
||||||
|
.files
|
||||||
|
.partition_point(|record| record.relative_path < relative_path);
|
||||||
|
self.files
|
||||||
|
.get(index)
|
||||||
|
.filter(|record| record.relative_path == relative_path)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn upsert(&mut self, record: ContentFileRecord) {
|
||||||
|
let index = self
|
||||||
|
.files
|
||||||
|
.partition_point(|existing| existing.relative_path < record.relative_path);
|
||||||
|
if self
|
||||||
|
.files
|
||||||
|
.get(index)
|
||||||
|
.is_some_and(|existing| existing.relative_path == record.relative_path)
|
||||||
|
{
|
||||||
|
self.files[index] = record;
|
||||||
|
} else {
|
||||||
|
// insert at the sorted position instead of re-sorting the whole
|
||||||
|
// vec; bulk callers that push pre-sorted records get O(1) each.
|
||||||
|
self.files.insert(index, record);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove(&mut self, relative_path: &Path) {
|
||||||
|
self.files
|
||||||
|
.retain(|record| record.relative_path != relative_path);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn rename_record(&mut self, from: &Path, to: &Path, enabled: bool) -> bool {
|
||||||
|
if from != to && self.record(to).is_some() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let Some(index) = self
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.position(|record| record.relative_path == from)
|
||||||
|
else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let mut record = self.files.remove(index);
|
||||||
|
record.relative_path = to.to_owned();
|
||||||
|
record.enabled = enabled;
|
||||||
|
self.upsert(record);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resolved_project_path(
|
||||||
|
&self,
|
||||||
|
provider: &str,
|
||||||
|
project_id: &str,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
) -> Option<PathBuf> {
|
||||||
|
self.files.iter().find_map(|record| {
|
||||||
|
record
|
||||||
|
.matches_project(provider, project_id)
|
||||||
|
.then(|| minecraft_dir.join(&record.relative_path))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resolved_project_path_under(
|
||||||
|
&self,
|
||||||
|
provider: &str,
|
||||||
|
project_id: &str,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
directory: &Path,
|
||||||
|
) -> Option<PathBuf> {
|
||||||
|
self.files.iter().find_map(|record| {
|
||||||
|
let path = minecraft_dir.join(&record.relative_path);
|
||||||
|
(record.matches_project(provider, project_id) && path.starts_with(directory))
|
||||||
|
.then_some(path)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resolved_project_record(
|
||||||
|
&self,
|
||||||
|
provider: &str,
|
||||||
|
project_id: &str,
|
||||||
|
) -> Option<&ContentFileRecord> {
|
||||||
|
self.files
|
||||||
|
.iter()
|
||||||
|
.find(|record| record.matches_project(provider, project_id))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn dependent_paths(&self, relative_path: &Path) -> Vec<PathBuf> {
|
||||||
|
let Some(target) = self.record(relative_path) else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
self.files
|
||||||
|
.iter()
|
||||||
|
.filter(|record| record.relative_path != relative_path)
|
||||||
|
.filter(|record| dependency_applies(target, record))
|
||||||
|
.map(|record| record.relative_path.clone())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn orphaned_dependencies_after_removing(&self, relative_path: &Path) -> Vec<PathBuf> {
|
||||||
|
self.orphaned_dependencies_with_removed(std::iter::once(relative_path.to_owned()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn orphaned_dependencies(&self) -> Vec<PathBuf> {
|
||||||
|
self.orphaned_dependencies_with_removed(std::iter::empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn orphaned_dependencies_with_removed(
|
||||||
|
&self,
|
||||||
|
removed: impl IntoIterator<Item = PathBuf>,
|
||||||
|
) -> Vec<PathBuf> {
|
||||||
|
let mut removed = removed
|
||||||
|
.into_iter()
|
||||||
|
.collect::<std::collections::HashSet<_>>();
|
||||||
|
let mut orphans = Vec::new();
|
||||||
|
loop {
|
||||||
|
let mut found = false;
|
||||||
|
for candidate in &self.files {
|
||||||
|
if !candidate.automatic_dependency
|
||||||
|
|| !candidate.cleanup_eligible
|
||||||
|
|| removed.contains(&candidate.relative_path)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let still_required = self
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.filter(|record| !removed.contains(&record.relative_path))
|
||||||
|
.any(|record| dependency_applies(candidate, record));
|
||||||
|
if !still_required {
|
||||||
|
removed.insert(candidate.relative_path.clone());
|
||||||
|
orphans.push(candidate.relative_path.clone());
|
||||||
|
found = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
orphans
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dependency_applies(candidate: &ContentFileRecord, dependent: &ContentFileRecord) -> bool {
|
||||||
|
let matches = dependent
|
||||||
|
.required_dependencies
|
||||||
|
.iter()
|
||||||
|
.any(|dependency| candidate.matches_project(&dependency.provider, &dependency.project_id));
|
||||||
|
if !matches || candidate.kind != ContentKind::DataPack {
|
||||||
|
return matches;
|
||||||
|
}
|
||||||
|
datapack_world(&candidate.relative_path) == datapack_world(&dependent.relative_path)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn datapack_world(path: &Path) -> Option<&std::ffi::OsStr> {
|
||||||
|
let mut components = path.components();
|
||||||
|
(components.next()?.as_os_str() == "saves")
|
||||||
|
.then(|| components.next().map(std::path::Component::as_os_str))
|
||||||
|
.flatten()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ContentFileRecord {
|
||||||
|
pub fn resolved_project(&self) -> Option<&ProviderProject> {
|
||||||
|
match &self.resolution {
|
||||||
|
Resolution::Resolved { project } => Some(project),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn matches_project(&self, provider: &str, project_id: &str) -> bool {
|
||||||
|
self.resolved_project()
|
||||||
|
.into_iter()
|
||||||
|
.chain(self.provider_aliases.iter())
|
||||||
|
.any(|project| project.provider == provider && project.project_id == project_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn project_for_provider(
|
||||||
|
&self,
|
||||||
|
provider: &str,
|
||||||
|
project_id: &str,
|
||||||
|
) -> Option<&ProviderProject> {
|
||||||
|
self.resolved_project()
|
||||||
|
.into_iter()
|
||||||
|
.chain(self.provider_aliases.iter())
|
||||||
|
.find(|project| project.provider == provider && project.project_id == project_id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum ManifestError {
|
||||||
|
#[error("I/O error: {0}")]
|
||||||
|
Io(#[from] std::io::Error),
|
||||||
|
#[error("JSON error: {0}")]
|
||||||
|
Json(#[from] serde_json::Error),
|
||||||
|
#[error("Unsupported content manifest version {0}")]
|
||||||
|
UnsupportedVersion(u32),
|
||||||
|
#[error("Invalid manifest path: {0}")]
|
||||||
|
InvalidPath(String),
|
||||||
|
#[error("Content is being changed by another operation: {0}")]
|
||||||
|
Busy(PathBuf),
|
||||||
|
#[error("Content manifest changed during the operation; refresh before retrying: {0}")]
|
||||||
|
Changed(PathBuf),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fingerprint(path: &Path) -> Result<FileFingerprint, std::io::Error> {
|
||||||
|
let metadata = std::fs::metadata(path)?;
|
||||||
|
let modified_ns = metadata
|
||||||
|
.modified()
|
||||||
|
.unwrap_or(SystemTime::UNIX_EPOCH)
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.unwrap_or_default()
|
||||||
|
.as_nanos();
|
||||||
|
let mut file = std::fs::File::open(path)?;
|
||||||
|
let mut sha1 = sha1::Sha1::new();
|
||||||
|
let mut sha512 = sha2::Sha512::new();
|
||||||
|
let mut curseforge_len = 0u32;
|
||||||
|
let mut buffer = [0u8; 64 * 1024];
|
||||||
|
loop {
|
||||||
|
let read = file.read(&mut buffer)?;
|
||||||
|
if read == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
sha1.update(&buffer[..read]);
|
||||||
|
sha512.update(&buffer[..read]);
|
||||||
|
curseforge_len = curseforge_len.saturating_add(
|
||||||
|
buffer[..read]
|
||||||
|
.iter()
|
||||||
|
.filter(|byte| !matches!(byte, b'\t' | b'\n' | b'\r' | b' '))
|
||||||
|
.count() as u32,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
file.rewind()?;
|
||||||
|
let hashes = BTreeMap::from([
|
||||||
|
("sha1".to_owned(), format!("{:x}", sha1.finalize())),
|
||||||
|
("sha512".to_owned(), format!("{:x}", sha512.finalize())),
|
||||||
|
(
|
||||||
|
"curseforge".to_owned(),
|
||||||
|
curseforge_fingerprint(&mut file, curseforge_len)?.to_string(),
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
Ok(FileFingerprint {
|
||||||
|
size: metadata.len(),
|
||||||
|
modified_ns,
|
||||||
|
hashes,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn curseforge_fingerprint(reader: &mut impl Read, length: u32) -> std::io::Result<u32> {
|
||||||
|
const M: u32 = 0x5bd1e995;
|
||||||
|
let mut hash = 1 ^ length;
|
||||||
|
let mut block = [0u8; 4];
|
||||||
|
let mut block_len = 0;
|
||||||
|
let mut buffer = [0u8; 64 * 1024];
|
||||||
|
loop {
|
||||||
|
let read = reader.read(&mut buffer)?;
|
||||||
|
if read == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
for &byte in &buffer[..read] {
|
||||||
|
if matches!(byte, b'\t' | b'\n' | b'\r' | b' ') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
block[block_len] = byte;
|
||||||
|
block_len += 1;
|
||||||
|
if block_len == 4 {
|
||||||
|
let mut value = u32::from_le_bytes(block);
|
||||||
|
value = value.wrapping_mul(M);
|
||||||
|
value ^= value >> 24;
|
||||||
|
value = value.wrapping_mul(M);
|
||||||
|
hash = hash.wrapping_mul(M) ^ value;
|
||||||
|
block_len = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match block_len {
|
||||||
|
3 => {
|
||||||
|
hash ^= u32::from(block[2]) << 16;
|
||||||
|
hash ^= u32::from(block[1]) << 8;
|
||||||
|
hash ^= u32::from(block[0]);
|
||||||
|
hash = hash.wrapping_mul(M);
|
||||||
|
}
|
||||||
|
2 => {
|
||||||
|
hash ^= u32::from(block[1]) << 8;
|
||||||
|
hash ^= u32::from(block[0]);
|
||||||
|
hash = hash.wrapping_mul(M);
|
||||||
|
}
|
||||||
|
1 => {
|
||||||
|
hash ^= u32::from(block[0]);
|
||||||
|
hash = hash.wrapping_mul(M);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
hash ^= hash >> 13;
|
||||||
|
hash = hash.wrapping_mul(M);
|
||||||
|
hash ^= hash >> 15;
|
||||||
|
Ok(hash)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fingerprint_metadata(path: &Path) -> Result<FileFingerprint, std::io::Error> {
|
||||||
|
let metadata = std::fs::metadata(path)?;
|
||||||
|
let modified_ns = metadata
|
||||||
|
.modified()
|
||||||
|
.unwrap_or(SystemTime::UNIX_EPOCH)
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.unwrap_or_default()
|
||||||
|
.as_nanos();
|
||||||
|
Ok(FileFingerprint {
|
||||||
|
size: metadata.len(),
|
||||||
|
modified_ns,
|
||||||
|
hashes: BTreeMap::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/content/manifest.rs"]
|
||||||
|
mod tests;
|
||||||
+34
-12
@@ -1,20 +1,46 @@
|
|||||||
// scanning and toggling instance content (mods, resource packs, shaders, worlds).
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
// minecraft uses a ".disabled" suffix convention for disabled content, so this leans on that heavily.
|
// minecraft uses a ".disabled" suffix convention for disabled content, so this leans on that heavily.
|
||||||
|
|
||||||
|
pub mod datapacks;
|
||||||
|
pub mod dependencies;
|
||||||
|
pub mod entry;
|
||||||
|
pub mod icons;
|
||||||
|
pub(crate) mod local;
|
||||||
|
pub mod manifest;
|
||||||
pub mod mods;
|
pub mod mods;
|
||||||
|
mod packs;
|
||||||
|
pub mod provider;
|
||||||
|
pub mod reconcile;
|
||||||
pub mod resource_packs;
|
pub mod resource_packs;
|
||||||
pub mod shaders;
|
pub mod shaders;
|
||||||
|
pub mod updates;
|
||||||
pub mod worlds;
|
pub mod worlds;
|
||||||
|
|
||||||
pub use mods::{ContentEntry, scan_mods, toggle_entry};
|
pub use datapacks::scan_one_datapack;
|
||||||
pub use resource_packs::scan_resource_packs;
|
pub(crate) use icons::{
|
||||||
pub use shaders::scan_shaders;
|
IconCell, fallback_icon, fallback_icon_large, make_icon_pixels, make_icon_pixels_from_image,
|
||||||
pub use worlds::scan_worlds;
|
make_icon_quadrants_from_image,
|
||||||
|
};
|
||||||
|
pub use mods::{scan_mods, scan_one_mod};
|
||||||
|
pub use resource_packs::{scan_one_resource_pack, scan_resource_packs};
|
||||||
|
pub use shaders::{scan_one_shader, scan_shaders};
|
||||||
|
pub use worlds::{scan_one_world, scan_worlds};
|
||||||
|
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
|
|
||||||
// figures out if a file is enabled or disabled based on the ".disabled" suffix,
|
const MAX_LOCAL_METADATA_BYTES: u64 = 8 * 1024 * 1024;
|
||||||
// and strips the extension to get a clean stem name
|
|
||||||
|
fn read_local_metadata(reader: impl Read) -> Option<Vec<u8>> {
|
||||||
|
let mut bytes = Vec::new();
|
||||||
|
reader
|
||||||
|
.take(MAX_LOCAL_METADATA_BYTES + 1)
|
||||||
|
.read_to_end(&mut bytes)
|
||||||
|
.ok()?;
|
||||||
|
(bytes.len() as u64 <= MAX_LOCAL_METADATA_BYTES).then_some(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn parse_enabled_stem(file_name: &str, ext: &str) -> Option<(bool, String)> {
|
pub(crate) fn parse_enabled_stem(file_name: &str, ext: &str) -> Option<(bool, String)> {
|
||||||
let disabled_ext = format!("{ext}.disabled");
|
let disabled_ext = format!("{ext}.disabled");
|
||||||
if let Some(stem) = file_name.strip_suffix(&disabled_ext) {
|
if let Some(stem) = file_name.strip_suffix(&disabled_ext) {
|
||||||
@@ -26,7 +52,6 @@ pub(crate) fn parse_enabled_stem(file_name: &str, ext: &str) -> Option<(bool, St
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// same idea but for directories, which don't have a file extension to strip
|
|
||||||
pub(crate) fn parse_enabled_stem_dir(file_name: &str) -> (bool, String) {
|
pub(crate) fn parse_enabled_stem_dir(file_name: &str) -> (bool, String) {
|
||||||
if let Some(stem) = file_name.strip_suffix(".disabled") {
|
if let Some(stem) = file_name.strip_suffix(".disabled") {
|
||||||
(false, stem.to_string())
|
(false, stem.to_string())
|
||||||
@@ -36,10 +61,7 @@ pub(crate) fn parse_enabled_stem_dir(file_name: &str) -> (bool, String) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn read_icon_from_zip(archive: &mut zip::ZipArchive<std::fs::File>) -> Option<Vec<u8>> {
|
pub(crate) fn read_icon_from_zip(archive: &mut zip::ZipArchive<std::fs::File>) -> Option<Vec<u8>> {
|
||||||
let mut entry = archive.by_name("pack.png").ok()?;
|
read_local_metadata(archive.by_name("pack.png").ok()?)
|
||||||
let mut buf = Vec::new();
|
|
||||||
entry.read_to_end(&mut buf).ok()?;
|
|
||||||
Some(buf)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn open_zip(path: &std::path::Path) -> Option<zip::ZipArchive<std::fs::File>> {
|
pub(crate) fn open_zip(path: &std::path::Path) -> Option<zip::ZipArchive<std::fs::File>> {
|
||||||
|
|||||||
+258
-286
@@ -1,34 +1,12 @@
|
|||||||
// mod scanning, metadata extraction, and icon rendering for the content list.
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
// jar files are just zips, so it cracks them open looking for fabric.mod.json to get
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
// names, descriptions, and icons. if that fails, just the filename is used. it's fine.
|
|
||||||
|
|
||||||
use std::io::Read;
|
use std::path::Path;
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
// a single "pixel" in the terminal icon. uses the unicode half-block trick
|
use super::entry::ContentEntry;
|
||||||
// where each character cell shows two vertical pixels (fg = top, bg = bottom)
|
use super::icons::{fallback_icon, make_icon_pixels};
|
||||||
#[derive(Debug, Clone, Copy)]
|
|
||||||
pub struct IconCell {
|
|
||||||
pub bg_r: u8,
|
|
||||||
pub bg_g: u8,
|
|
||||||
pub bg_b: u8,
|
|
||||||
pub fg_r: u8,
|
|
||||||
pub fg_g: u8,
|
|
||||||
pub fg_b: u8,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct ContentEntry {
|
|
||||||
pub file_stem: String,
|
|
||||||
pub name: String,
|
|
||||||
pub description: String,
|
|
||||||
pub enabled: bool,
|
|
||||||
pub icon_bytes: Option<Vec<u8>>,
|
|
||||||
pub path: PathBuf,
|
|
||||||
pub icon_lines: Option<Vec<Vec<IconCell>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize, Default)]
|
#[derive(Deserialize, Default)]
|
||||||
struct FabricModJson {
|
struct FabricModJson {
|
||||||
@@ -37,29 +15,98 @@ struct FabricModJson {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
description: String,
|
description: String,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
version: String,
|
||||||
|
#[serde(default)]
|
||||||
icon: serde_json::Value,
|
icon: serde_json::Value,
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
||||||
serde_json::Value::String(s) => s.clone(),
|
}
|
||||||
serde_json::Value::Object(map) => map
|
}
|
||||||
.values()
|
|
||||||
.find_map(|v| v.as_str())
|
// fabric and quilt both support icon as a string path or a map of
|
||||||
.unwrap_or("")
|
// resolution -> path. if it's a map, just grab the first one.
|
||||||
.to_owned(),
|
fn icon_path_from_value(value: &serde_json::Value) -> String {
|
||||||
_ => String::new(),
|
match value {
|
||||||
}
|
serde_json::Value::String(s) => s.clone(),
|
||||||
|
serde_json::Value::Object(map) => map
|
||||||
|
.values()
|
||||||
|
.find_map(|v| v.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_owned(),
|
||||||
|
_ => String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
struct QuiltModJson {
|
||||||
|
#[serde(default)]
|
||||||
|
quilt_loader: QuiltLoader,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
struct QuiltLoader {
|
||||||
|
#[serde(default)]
|
||||||
|
version: String,
|
||||||
|
#[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, version, 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,
|
||||||
|
source_slug: None,
|
||||||
|
installed_path: None,
|
||||||
|
provider_project: None,
|
||||||
|
world_details: None,
|
||||||
|
title_suffix: None,
|
||||||
|
footer_label: display_version(version),
|
||||||
|
footer_change: None,
|
||||||
|
description,
|
||||||
|
enabled,
|
||||||
|
icon_bytes,
|
||||||
|
provider_icon: false,
|
||||||
|
provider_description: false,
|
||||||
|
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> {
|
||||||
let mods_dir = instances_dir
|
let mods_dir = instances_dir
|
||||||
.join(instance_name)
|
.join(instance_name)
|
||||||
.join(".minecraft")
|
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||||
.join("mods");
|
.join("mods");
|
||||||
|
|
||||||
let read_dir = match std::fs::read_dir(&mods_dir) {
|
let read_dir = match std::fs::read_dir(&mods_dir) {
|
||||||
@@ -80,68 +127,198 @@ 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),
|
fn read_mod_metadata(jar_path: &Path) -> (String, String, String, Option<Vec<u8>>) {
|
||||||
// still attempts to grab pack.png as a last resort for an icon
|
|
||||||
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,
|
||||||
Err(_) => return (String::new(), String::new(), None),
|
Err(e) => {
|
||||||
|
tracing::trace!("Failed to open mod JAR {}: {}", jar_path.display(), e);
|
||||||
|
return (String::new(), String::new(), String::new(), None);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut archive = match zip::ZipArchive::new(file) {
|
let mut archive = match zip::ZipArchive::new(file) {
|
||||||
Ok(archive) => archive,
|
Ok(archive) => archive,
|
||||||
Err(_) => return (String::new(), String::new(), None),
|
Err(e) => {
|
||||||
|
tracing::trace!(
|
||||||
|
"Failed to read mod JAR as ZIP {}: {}",
|
||||||
|
jar_path.display(),
|
||||||
|
e
|
||||||
|
);
|
||||||
|
return (String::new(), String::new(), String::new(), None);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
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.
|
||||||
None
|
type MetaReader =
|
||||||
} else {
|
fn(&mut zip::ZipArchive<std::fs::File>) -> Option<(String, String, String, String)>;
|
||||||
read_zip_bytes(&mut archive, &icon_path)
|
let readers: [MetaReader; 4] = [
|
||||||
};
|
read_fabric_meta,
|
||||||
return (name, description, icon_bytes);
|
read_quilt_meta,
|
||||||
|
read_forge_toml_meta,
|
||||||
|
read_mcmod_info,
|
||||||
|
];
|
||||||
|
|
||||||
|
for reader in &readers {
|
||||||
|
if let Some((name, description, version, icon_path)) = reader(&mut archive) {
|
||||||
|
let icon_path = icon_path.trim_start_matches('/');
|
||||||
|
let icon = if icon_path.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
read_zip_bytes(&mut archive, icon_path)
|
||||||
|
}
|
||||||
|
.or_else(|| try_fallback_icons(&mut archive));
|
||||||
|
tracing::trace!(
|
||||||
|
"Read mod metadata from {}: name='{}' icon_declared={}",
|
||||||
|
jar_path.display(),
|
||||||
|
name,
|
||||||
|
!icon_path.is_empty()
|
||||||
|
);
|
||||||
|
return (name, description, version, icon);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let icon_bytes = read_zip_bytes(&mut archive, "pack.png");
|
let icon_bytes = try_fallback_icons(&mut archive);
|
||||||
(String::new(), String::new(), icon_bytes)
|
tracing::trace!(
|
||||||
|
"No recognized mod metadata in {}; fallback_icon={}",
|
||||||
|
jar_path.display(),
|
||||||
|
icon_bytes.is_some()
|
||||||
|
);
|
||||||
|
(String::new(), String::new(), String::new(), icon_bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn display_version(version: String) -> Option<String> {
|
||||||
|
let version = version.trim();
|
||||||
|
(!version.is_empty() && !version.contains("${")).then(|| version.to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_fallback_icons(archive: &mut zip::ZipArchive<std::fs::File>) -> Option<Vec<u8>> {
|
||||||
|
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, String)> {
|
||||||
let mut entry = archive.by_name("fabric.mod.json").ok()?;
|
let raw = String::from_utf8(super::read_local_metadata(
|
||||||
let mut raw = String::new();
|
archive.by_name("fabric.mod.json").ok()?,
|
||||||
entry.read_to_string(&mut raw).ok()?;
|
)?)
|
||||||
|
.ok()?;
|
||||||
let sanitized = sanitize_json_strings(&raw);
|
let sanitized = sanitize_json_strings(&raw);
|
||||||
let data: FabricModJson = serde_json::from_str(&sanitized).ok()?;
|
let data: FabricModJson = serde_json::from_str(&sanitized).ok()?;
|
||||||
let icon = data.icon_path();
|
let icon = data.icon_path();
|
||||||
Some((data.name, data.description, icon))
|
Some((data.name, data.description, data.version, icon))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_quilt_meta(
|
||||||
|
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||||
|
) -> Option<(String, String, String, String)> {
|
||||||
|
let raw = String::from_utf8(super::read_local_metadata(
|
||||||
|
archive.by_name("quilt.mod.json").ok()?,
|
||||||
|
)?)
|
||||||
|
.ok()?;
|
||||||
|
let sanitized = sanitize_json_strings(&raw);
|
||||||
|
let data: QuiltModJson = serde_json::from_str(&sanitized).ok()?;
|
||||||
|
let version = data.quilt_loader.version;
|
||||||
|
let meta = data.quilt_loader.metadata;
|
||||||
|
let icon = meta.icon_path();
|
||||||
|
Some((meta.name, meta.description, version, 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, 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, version) = 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();
|
||||||
|
let version = first
|
||||||
|
.get("version")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_owned();
|
||||||
|
(n, d, version)
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
Some((name, description, version, logo))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_mcmod_info(
|
||||||
|
archive: &mut zip::ZipArchive<std::fs::File>,
|
||||||
|
) -> Option<(String, String, String, String)> {
|
||||||
|
let raw = String::from_utf8(super::read_local_metadata(
|
||||||
|
archive.by_name("mcmod.info").ok()?,
|
||||||
|
)?)
|
||||||
|
.ok()?;
|
||||||
|
let sanitized = sanitize_json_strings(&raw);
|
||||||
|
let parsed: serde_json::Value = serde_json::from_str(&sanitized).ok()?;
|
||||||
|
let first = match &parsed {
|
||||||
|
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 version = first
|
||||||
|
.get("version")
|
||||||
|
.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, version, logo))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_zip_string(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> Option<String> {
|
||||||
|
String::from_utf8(super::read_local_metadata(archive.by_name(path).ok()?)?).ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
// some mod authors put raw newlines/tabs inside json string values which is
|
// some mod authors put raw newlines/tabs inside json string values which is
|
||||||
@@ -182,214 +359,9 @@ fn sanitize_json_strings(input: &str) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn read_zip_bytes(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> Option<Vec<u8>> {
|
fn read_zip_bytes(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> Option<Vec<u8>> {
|
||||||
let mut entry = archive.by_name(path).ok()?;
|
super::read_local_metadata(archive.by_name(path).ok()?)
|
||||||
let mut bytes = Vec::new();
|
|
||||||
entry.read_to_end(&mut bytes).ok()?;
|
|
||||||
Some(bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
// downscales an icon to terminal resolution. resizes to height*2 because each
|
|
||||||
// terminal cell renders two vertical pixels using half-block characters (▀)
|
|
||||||
pub(crate) fn make_icon_pixels(
|
|
||||||
bytes: &[u8],
|
|
||||||
width: u16,
|
|
||||||
height: u16,
|
|
||||||
) -> Option<Vec<Vec<IconCell>>> {
|
|
||||||
let img = image::load_from_memory(bytes).ok()?;
|
|
||||||
let resized = img.resize_exact(
|
|
||||||
u32::from(width),
|
|
||||||
u32::from(height) * 2,
|
|
||||||
image::imageops::FilterType::Nearest,
|
|
||||||
);
|
|
||||||
let rgb = resized.to_rgb8();
|
|
||||||
|
|
||||||
let mut rows = Vec::new();
|
|
||||||
for row in 0..height {
|
|
||||||
let mut cols = Vec::new();
|
|
||||||
for col in 0..width {
|
|
||||||
let top_y = u32::from(row) * 2;
|
|
||||||
let bottom_y = (u32::from(row) * 2 + 1).min(rgb.height().saturating_sub(1));
|
|
||||||
let [tr, tg, tb] = rgb.get_pixel(u32::from(col), top_y).0;
|
|
||||||
let [br, bg, bb] = rgb.get_pixel(u32::from(col), bottom_y).0;
|
|
||||||
cols.push(IconCell {
|
|
||||||
bg_r: br,
|
|
||||||
bg_g: bg,
|
|
||||||
bg_b: bb,
|
|
||||||
fg_r: tr,
|
|
||||||
fg_g: tg,
|
|
||||||
fg_b: tb,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
rows.push(cols);
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(rows)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 6x3 fallback icon showing a "?" pattern for mods without icons.
|
|
||||||
fn fallback_icon() -> Vec<Vec<IconCell>> {
|
|
||||||
let b = IconCell {
|
|
||||||
bg_r: 50,
|
|
||||||
bg_g: 50,
|
|
||||||
bg_b: 50,
|
|
||||||
fg_r: 50,
|
|
||||||
fg_g: 50,
|
|
||||||
fg_b: 50,
|
|
||||||
};
|
|
||||||
let tb = IconCell {
|
|
||||||
bg_r: 50,
|
|
||||||
bg_g: 50,
|
|
||||||
bg_b: 50,
|
|
||||||
fg_r: 130,
|
|
||||||
fg_g: 130,
|
|
||||||
fg_b: 130,
|
|
||||||
};
|
|
||||||
let bt = IconCell {
|
|
||||||
bg_r: 130,
|
|
||||||
bg_g: 130,
|
|
||||||
bg_b: 130,
|
|
||||||
fg_r: 50,
|
|
||||||
fg_g: 50,
|
|
||||||
fg_b: 50,
|
|
||||||
};
|
|
||||||
vec![
|
|
||||||
vec![b, tb, tb, tb, tb, b],
|
|
||||||
vec![b, b, b, bt, bt, b],
|
|
||||||
vec![b, b, bt, bt, b, b],
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
// enable/disable by renaming the file with/without ".disabled" suffix.
|
|
||||||
// the minecraft way, apparently.
|
|
||||||
pub fn toggle_entry(entry: &ContentEntry) -> Result<(), std::io::Error> {
|
|
||||||
let file_name = match entry.path.file_name().and_then(|name| name.to_str()) {
|
|
||||||
Some(name) => name,
|
|
||||||
None => return Ok(()),
|
|
||||||
};
|
|
||||||
|
|
||||||
let new_name = if entry.enabled {
|
|
||||||
format!("{file_name}.disabled")
|
|
||||||
} else {
|
|
||||||
file_name.trim_end_matches(".disabled").to_string()
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut new_path = entry.path.clone();
|
|
||||||
new_path.set_file_name(new_name);
|
|
||||||
std::fs::rename(&entry.path, new_path)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "../tests/content/mods.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
fn setup_mods_dir(tmp: &Path, instance: &str) -> PathBuf {
|
|
||||||
let dir = tmp.join(instance).join(".minecraft").join("mods");
|
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
|
||||||
dir
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_empty_dir() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
setup_mods_dir(tmp.path(), "inst");
|
|
||||||
let mods = scan_mods(tmp.path(), "inst");
|
|
||||||
assert!(mods.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_missing_dir_returns_empty() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let mods = scan_mods(tmp.path(), "ghost");
|
|
||||||
assert!(mods.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_finds_jar_files() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("cool-mod.jar"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::write(dir.join("other-mod.jar.disabled"), b"PK\x03\x04").unwrap();
|
|
||||||
let mods = scan_mods(tmp.path(), "inst");
|
|
||||||
assert_eq!(mods.len(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_enabled_disabled_flags() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("active.jar"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::write(dir.join("inactive.jar.disabled"), b"PK\x03\x04").unwrap();
|
|
||||||
let mods = scan_mods(tmp.path(), "inst");
|
|
||||||
let active = mods.iter().find(|m| m.file_stem == "active").unwrap();
|
|
||||||
let inactive = mods.iter().find(|m| m.file_stem == "inactive").unwrap();
|
|
||||||
assert!(active.enabled);
|
|
||||||
assert!(!inactive.enabled);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_ignores_non_jar() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("readme.txt"), "not a mod").unwrap();
|
|
||||||
std::fs::write(dir.join("config.json"), "{}").unwrap();
|
|
||||||
std::fs::write(dir.join("real.jar"), b"PK\x03\x04").unwrap();
|
|
||||||
let mods = scan_mods(tmp.path(), "inst");
|
|
||||||
assert_eq!(mods.len(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_mods_sorted_case_insensitive() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("Zebra.jar"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::write(dir.join("alpha.jar"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::write(dir.join("Beta.jar"), b"PK\x03\x04").unwrap();
|
|
||||||
let mods = scan_mods(tmp.path(), "inst");
|
|
||||||
let names: Vec<&str> = mods.iter().map(|m| m.name.as_str()).collect();
|
|
||||||
assert_eq!(names, vec!["alpha", "Beta", "Zebra"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn toggle_entry_enable() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
let disabled_path = dir.join("mymod.jar.disabled");
|
|
||||||
std::fs::write(&disabled_path, b"PK\x03\x04").unwrap();
|
|
||||||
|
|
||||||
let entry = ContentEntry {
|
|
||||||
file_stem: "mymod".to_string(),
|
|
||||||
name: "mymod".to_string(),
|
|
||||||
description: String::new(),
|
|
||||||
enabled: false,
|
|
||||||
icon_bytes: None,
|
|
||||||
path: disabled_path.clone(),
|
|
||||||
icon_lines: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
toggle_entry(&entry).unwrap();
|
|
||||||
assert!(!disabled_path.exists());
|
|
||||||
assert!(dir.join("mymod.jar").exists());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn toggle_entry_disable() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_mods_dir(tmp.path(), "inst");
|
|
||||||
let enabled_path = dir.join("mymod.jar");
|
|
||||||
std::fs::write(&enabled_path, b"PK\x03\x04").unwrap();
|
|
||||||
|
|
||||||
let entry = ContentEntry {
|
|
||||||
file_stem: "mymod".to_string(),
|
|
||||||
name: "mymod".to_string(),
|
|
||||||
description: String::new(),
|
|
||||||
enabled: true,
|
|
||||||
icon_bytes: None,
|
|
||||||
path: enabled_path.clone(),
|
|
||||||
icon_lines: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
toggle_entry(&entry).unwrap();
|
|
||||||
assert!(!enabled_path.exists());
|
|
||||||
assert!(dir.join("mymod.jar.disabled").exists());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use super::entry::ContentEntry;
|
||||||
|
use super::{fallback_icon, make_icon_pixels};
|
||||||
|
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
struct PackMcMeta {
|
||||||
|
#[serde(default)]
|
||||||
|
pack: PackInfo,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
struct PackInfo {
|
||||||
|
#[serde(default)]
|
||||||
|
description: serde_json::Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn extract_description(value: &serde_json::Value) -> String {
|
||||||
|
match value {
|
||||||
|
serde_json::Value::String(text) => text.clone(),
|
||||||
|
serde_json::Value::Object(object) => object
|
||||||
|
.get("text")
|
||||||
|
.and_then(|value| value.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_owned(),
|
||||||
|
serde_json::Value::Array(values) => values
|
||||||
|
.iter()
|
||||||
|
.filter_map(|value| match value {
|
||||||
|
serde_json::Value::String(text) => Some(text.as_str()),
|
||||||
|
serde_json::Value::Object(object) => {
|
||||||
|
object.get("text").and_then(|value| value.as_str())
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(""),
|
||||||
|
_ => String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn scan_one_pack(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||||
|
let (description, icon_bytes) = if path.is_dir() {
|
||||||
|
read_metadata_from_dir(path)
|
||||||
|
} else {
|
||||||
|
read_metadata_from_zip(path)
|
||||||
|
};
|
||||||
|
let icon_lines = icon_bytes
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|bytes| make_icon_pixels(bytes, 6, 3))
|
||||||
|
.or_else(|| Some(fallback_icon()));
|
||||||
|
|
||||||
|
ContentEntry {
|
||||||
|
file_stem: file_stem.to_owned(),
|
||||||
|
name: file_stem.to_owned(),
|
||||||
|
source_slug: None,
|
||||||
|
installed_path: None,
|
||||||
|
provider_project: None,
|
||||||
|
world_details: None,
|
||||||
|
title_suffix: None,
|
||||||
|
footer_label: None,
|
||||||
|
footer_change: None,
|
||||||
|
description,
|
||||||
|
enabled,
|
||||||
|
icon_bytes,
|
||||||
|
provider_icon: false,
|
||||||
|
provider_description: false,
|
||||||
|
path: path.to_path_buf(),
|
||||||
|
icon_lines,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn scan_packs(
|
||||||
|
instances_dir: &Path,
|
||||||
|
instance_name: &str,
|
||||||
|
directory: &str,
|
||||||
|
) -> Vec<ContentEntry> {
|
||||||
|
let directory = instances_dir
|
||||||
|
.join(instance_name)
|
||||||
|
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||||
|
.join(directory);
|
||||||
|
let Ok(entries) = std::fs::read_dir(directory) else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let mut packs = entries
|
||||||
|
.flatten()
|
||||||
|
.filter_map(|entry| {
|
||||||
|
let path = entry.path();
|
||||||
|
let file_name = path.file_name()?.to_str()?;
|
||||||
|
let (enabled, file_stem) = if path.is_dir() {
|
||||||
|
super::parse_enabled_stem_dir(file_name)
|
||||||
|
} else {
|
||||||
|
super::parse_enabled_stem(file_name, ".zip")?
|
||||||
|
};
|
||||||
|
Some(scan_one_pack(&path, &file_stem, enabled))
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
packs.sort_by_cached_key(|entry| entry.name.to_lowercase());
|
||||||
|
packs
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_metadata_from_zip(path: &Path) -> (String, Option<Vec<u8>>) {
|
||||||
|
let Some(mut archive) = super::open_zip(path) else {
|
||||||
|
return (String::new(), None);
|
||||||
|
};
|
||||||
|
let description = archive
|
||||||
|
.by_name("pack.mcmeta")
|
||||||
|
.ok()
|
||||||
|
.and_then(super::read_local_metadata)
|
||||||
|
.and_then(|bytes| serde_json::from_slice::<PackMcMeta>(&bytes).ok())
|
||||||
|
.map(|meta| extract_description(&meta.pack.description))
|
||||||
|
.unwrap_or_default();
|
||||||
|
let icon_bytes = super::read_icon_from_zip(&mut archive);
|
||||||
|
(description, icon_bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_metadata_from_dir(path: &Path) -> (String, Option<Vec<u8>>) {
|
||||||
|
let description = std::fs::File::open(path.join("pack.mcmeta"))
|
||||||
|
.ok()
|
||||||
|
.and_then(super::read_local_metadata)
|
||||||
|
.and_then(|bytes| serde_json::from_slice::<PackMcMeta>(&bytes).ok())
|
||||||
|
.map(|meta| extract_description(&meta.pack.description))
|
||||||
|
.unwrap_or_default();
|
||||||
|
(
|
||||||
|
description,
|
||||||
|
std::fs::File::open(path.join("pack.png"))
|
||||||
|
.ok()
|
||||||
|
.and_then(super::read_local_metadata),
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,550 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
|
||||||
|
use crate::instance::content::manifest::{ContentKind, FileFingerprint, ProviderProject};
|
||||||
|
use crate::instance::{InstanceConfig, ModLoader};
|
||||||
|
use crate::net::modrinth::{DiscoveryResults, VersionInfo};
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum DiscoverySort {
|
||||||
|
#[default]
|
||||||
|
Relevance,
|
||||||
|
Downloads,
|
||||||
|
Popular,
|
||||||
|
Updated,
|
||||||
|
Newest,
|
||||||
|
Released,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct DiscoverySearchFilters {
|
||||||
|
pub game_versions: Vec<String>,
|
||||||
|
pub excluded_versions: Vec<String>,
|
||||||
|
pub included_categories: Vec<String>,
|
||||||
|
pub excluded_categories: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DiscoverySort {
|
||||||
|
pub const ALL: [Self; 5] = [
|
||||||
|
Self::Relevance,
|
||||||
|
Self::Popular,
|
||||||
|
Self::Newest,
|
||||||
|
Self::Downloads,
|
||||||
|
Self::Updated,
|
||||||
|
];
|
||||||
|
|
||||||
|
pub fn label(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Relevance => "Best match",
|
||||||
|
Self::Downloads => "Downloads",
|
||||||
|
Self::Popular => "Popularity",
|
||||||
|
Self::Updated => "Updates",
|
||||||
|
Self::Newest | Self::Released => "Release date",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct FingerprintQuery {
|
||||||
|
pub key: String,
|
||||||
|
pub kind: ContentKind,
|
||||||
|
pub fingerprint: FileFingerprint,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ResolvedFile {
|
||||||
|
pub key: String,
|
||||||
|
pub project: ProviderProject,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(
|
||||||
|
clippy::double_must_use,
|
||||||
|
reason = "async_trait adds #[must_use] to generated futures"
|
||||||
|
)]
|
||||||
|
#[async_trait]
|
||||||
|
pub trait ContentProvider: Send + Sync {
|
||||||
|
fn id(&self) -> &'static str;
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
async fn search(
|
||||||
|
&self,
|
||||||
|
kind: ContentKind,
|
||||||
|
query: &str,
|
||||||
|
instance: &InstanceConfig,
|
||||||
|
filters: &DiscoverySearchFilters,
|
||||||
|
sort: DiscoverySort,
|
||||||
|
reversed: bool,
|
||||||
|
offset: usize,
|
||||||
|
limit: usize,
|
||||||
|
) -> Result<DiscoveryResults, crate::net::NetError>;
|
||||||
|
|
||||||
|
async fn search_modpacks(
|
||||||
|
&self,
|
||||||
|
query: &str,
|
||||||
|
filters: &DiscoverySearchFilters,
|
||||||
|
sort: DiscoverySort,
|
||||||
|
reversed: bool,
|
||||||
|
offset: usize,
|
||||||
|
limit: usize,
|
||||||
|
) -> Result<DiscoveryResults, crate::net::NetError>;
|
||||||
|
|
||||||
|
async fn resolve_files(
|
||||||
|
&self,
|
||||||
|
files: &[FingerprintQuery],
|
||||||
|
) -> Result<Vec<ResolvedFile>, crate::net::NetError>;
|
||||||
|
|
||||||
|
async fn project(
|
||||||
|
&self,
|
||||||
|
project_id: &str,
|
||||||
|
) -> Result<crate::net::modrinth::ProjectInfo, crate::net::NetError>;
|
||||||
|
|
||||||
|
async fn compatible_versions(
|
||||||
|
&self,
|
||||||
|
project_id: &str,
|
||||||
|
kind: ContentKind,
|
||||||
|
game_version: &str,
|
||||||
|
loader: ModLoader,
|
||||||
|
) -> Result<Vec<VersionInfo>, crate::net::NetError>;
|
||||||
|
|
||||||
|
async fn version(&self, version_id: &str) -> Result<VersionInfo, crate::net::NetError>;
|
||||||
|
|
||||||
|
async fn icon(&self, url: &str) -> Result<Vec<u8>, crate::net::NetError>;
|
||||||
|
|
||||||
|
async fn download_version(
|
||||||
|
&self,
|
||||||
|
version: &VersionInfo,
|
||||||
|
destination: &std::path::Path,
|
||||||
|
installed_path: Option<&std::path::Path>,
|
||||||
|
) -> Result<crate::net::modrinth::DownloadOutcome, crate::net::NetError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ModrinthProvider {
|
||||||
|
client: crate::net::HttpClient,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ModrinthProvider {
|
||||||
|
pub fn new(client: crate::net::HttpClient) -> Self {
|
||||||
|
Self { client }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl ContentProvider for ModrinthProvider {
|
||||||
|
fn id(&self) -> &'static str {
|
||||||
|
"modrinth"
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn search(
|
||||||
|
&self,
|
||||||
|
kind: ContentKind,
|
||||||
|
query: &str,
|
||||||
|
instance: &InstanceConfig,
|
||||||
|
filters: &DiscoverySearchFilters,
|
||||||
|
sort: DiscoverySort,
|
||||||
|
reversed: bool,
|
||||||
|
offset: usize,
|
||||||
|
limit: usize,
|
||||||
|
) -> Result<DiscoveryResults, crate::net::NetError> {
|
||||||
|
crate::net::modrinth::search_discovery(
|
||||||
|
&self.client,
|
||||||
|
kind,
|
||||||
|
query,
|
||||||
|
filters,
|
||||||
|
instance.loader,
|
||||||
|
sort,
|
||||||
|
reversed,
|
||||||
|
offset,
|
||||||
|
limit,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn search_modpacks(
|
||||||
|
&self,
|
||||||
|
query: &str,
|
||||||
|
filters: &DiscoverySearchFilters,
|
||||||
|
sort: DiscoverySort,
|
||||||
|
reversed: bool,
|
||||||
|
offset: usize,
|
||||||
|
limit: usize,
|
||||||
|
) -> Result<DiscoveryResults, crate::net::NetError> {
|
||||||
|
crate::net::modrinth::search_modpacks(
|
||||||
|
&self.client,
|
||||||
|
query,
|
||||||
|
filters,
|
||||||
|
sort,
|
||||||
|
reversed,
|
||||||
|
offset,
|
||||||
|
limit,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn resolve_files(
|
||||||
|
&self,
|
||||||
|
files: &[FingerprintQuery],
|
||||||
|
) -> Result<Vec<ResolvedFile>, crate::net::NetError> {
|
||||||
|
let mut by_hash = HashMap::<String, Vec<String>>::new();
|
||||||
|
for file in files {
|
||||||
|
if let Some(hash) = file.fingerprint.hash("sha512") {
|
||||||
|
by_hash
|
||||||
|
.entry(hash.to_owned())
|
||||||
|
.or_default()
|
||||||
|
.push(file.key.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let hashes = by_hash.keys().cloned().collect::<Vec<_>>();
|
||||||
|
let versions =
|
||||||
|
crate::net::modrinth::resolve_version_files(&self.client, &hashes, "sha512").await?;
|
||||||
|
Ok(versions
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|(hash, version)| {
|
||||||
|
let keys = by_hash.get(&hash).cloned().unwrap_or_default();
|
||||||
|
if version.project_id.is_empty() {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
keys.into_iter()
|
||||||
|
.map(|key| ResolvedFile {
|
||||||
|
key,
|
||||||
|
project: ProviderProject {
|
||||||
|
provider: self.id().to_owned(),
|
||||||
|
project_id: version.project_id.clone(),
|
||||||
|
version_id: version.id.clone(),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn project(
|
||||||
|
&self,
|
||||||
|
project_id: &str,
|
||||||
|
) -> Result<crate::net::modrinth::ProjectInfo, crate::net::NetError> {
|
||||||
|
crate::net::modrinth::fetch_project(&self.client, project_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn compatible_versions(
|
||||||
|
&self,
|
||||||
|
project_id: &str,
|
||||||
|
kind: ContentKind,
|
||||||
|
game_version: &str,
|
||||||
|
loader: ModLoader,
|
||||||
|
) -> Result<Vec<VersionInfo>, crate::net::NetError> {
|
||||||
|
crate::net::modrinth::fetch_content_versions(
|
||||||
|
&self.client,
|
||||||
|
project_id,
|
||||||
|
kind,
|
||||||
|
game_version,
|
||||||
|
loader,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn version(&self, version_id: &str) -> Result<VersionInfo, crate::net::NetError> {
|
||||||
|
crate::net::modrinth::fetch_version(&self.client, version_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn icon(&self, url: &str) -> Result<Vec<u8>, crate::net::NetError> {
|
||||||
|
self.client
|
||||||
|
.get_bytes_limited(url, crate::net::MAX_PROVIDER_ASSET_BYTES)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn download_version(
|
||||||
|
&self,
|
||||||
|
version: &VersionInfo,
|
||||||
|
destination: &std::path::Path,
|
||||||
|
installed_path: Option<&std::path::Path>,
|
||||||
|
) -> Result<crate::net::modrinth::DownloadOutcome, crate::net::NetError> {
|
||||||
|
if let Some(installed_path) = installed_path {
|
||||||
|
crate::net::modrinth::download_version_file_for_update(
|
||||||
|
&self.client,
|
||||||
|
version,
|
||||||
|
destination,
|
||||||
|
installed_path,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
} else {
|
||||||
|
crate::net::modrinth::download_version_file(&self.client, version, destination).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct CurseForgeProvider {
|
||||||
|
client: crate::net::HttpClient,
|
||||||
|
api_key: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CurseForgeProvider {
|
||||||
|
pub fn new(client: crate::net::HttpClient, api_key: impl Into<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
client,
|
||||||
|
api_key: api_key.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl ContentProvider for CurseForgeProvider {
|
||||||
|
fn id(&self) -> &'static str {
|
||||||
|
"curseforge"
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn search(
|
||||||
|
&self,
|
||||||
|
kind: ContentKind,
|
||||||
|
query: &str,
|
||||||
|
instance: &InstanceConfig,
|
||||||
|
filters: &DiscoverySearchFilters,
|
||||||
|
sort: DiscoverySort,
|
||||||
|
reversed: bool,
|
||||||
|
offset: usize,
|
||||||
|
limit: usize,
|
||||||
|
) -> Result<DiscoveryResults, crate::net::NetError> {
|
||||||
|
crate::net::curseforge::search_discovery(
|
||||||
|
&self.client,
|
||||||
|
&self.api_key,
|
||||||
|
kind,
|
||||||
|
query,
|
||||||
|
&filters.game_versions,
|
||||||
|
instance.loader,
|
||||||
|
&filters.included_categories,
|
||||||
|
sort,
|
||||||
|
reversed,
|
||||||
|
offset,
|
||||||
|
limit,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn search_modpacks(
|
||||||
|
&self,
|
||||||
|
query: &str,
|
||||||
|
filters: &DiscoverySearchFilters,
|
||||||
|
sort: DiscoverySort,
|
||||||
|
reversed: bool,
|
||||||
|
offset: usize,
|
||||||
|
limit: usize,
|
||||||
|
) -> Result<DiscoveryResults, crate::net::NetError> {
|
||||||
|
crate::net::curseforge::search_modpacks(
|
||||||
|
&self.client,
|
||||||
|
&self.api_key,
|
||||||
|
query,
|
||||||
|
&filters.game_versions,
|
||||||
|
&filters.included_categories,
|
||||||
|
sort,
|
||||||
|
reversed,
|
||||||
|
offset,
|
||||||
|
limit,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn resolve_files(
|
||||||
|
&self,
|
||||||
|
files: &[FingerprintQuery],
|
||||||
|
) -> Result<Vec<ResolvedFile>, crate::net::NetError> {
|
||||||
|
let mut by_fingerprint = HashMap::<u32, Vec<String>>::new();
|
||||||
|
for file in files {
|
||||||
|
if let Some(fingerprint) = file
|
||||||
|
.fingerprint
|
||||||
|
.hash("curseforge")
|
||||||
|
.and_then(|value| value.parse().ok())
|
||||||
|
{
|
||||||
|
by_fingerprint
|
||||||
|
.entry(fingerprint)
|
||||||
|
.or_default()
|
||||||
|
.push(file.key.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let fingerprints = by_fingerprint.keys().copied().collect::<Vec<_>>();
|
||||||
|
let matches = crate::net::curseforge::resolve_fingerprints(
|
||||||
|
&self.client,
|
||||||
|
&self.api_key,
|
||||||
|
&fingerprints,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
Ok(matches
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|(fingerprint, project_id, version_id)| {
|
||||||
|
by_fingerprint
|
||||||
|
.get(&fingerprint)
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.into_iter()
|
||||||
|
.map(move |key| ResolvedFile {
|
||||||
|
key,
|
||||||
|
project: ProviderProject {
|
||||||
|
provider: self.id().to_owned(),
|
||||||
|
project_id: project_id.clone(),
|
||||||
|
version_id: version_id.clone(),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn project(
|
||||||
|
&self,
|
||||||
|
project_id: &str,
|
||||||
|
) -> Result<crate::net::modrinth::ProjectInfo, crate::net::NetError> {
|
||||||
|
crate::net::curseforge::fetch_project(&self.client, &self.api_key, project_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn compatible_versions(
|
||||||
|
&self,
|
||||||
|
project_id: &str,
|
||||||
|
kind: ContentKind,
|
||||||
|
game_version: &str,
|
||||||
|
loader: ModLoader,
|
||||||
|
) -> Result<Vec<VersionInfo>, crate::net::NetError> {
|
||||||
|
crate::net::curseforge::fetch_versions(
|
||||||
|
&self.client,
|
||||||
|
&self.api_key,
|
||||||
|
project_id,
|
||||||
|
game_version,
|
||||||
|
(kind == ContentKind::Mod).then_some(loader),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn version(&self, version_id: &str) -> Result<VersionInfo, crate::net::NetError> {
|
||||||
|
let id = version_id.parse::<u64>().map_err(|_| {
|
||||||
|
crate::net::NetError::Parse(format!("Invalid CurseForge file id '{version_id}'"))
|
||||||
|
})?;
|
||||||
|
crate::net::curseforge::fetch_file_versions(&self.client, &self.api_key, &[id])
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.next()
|
||||||
|
.ok_or_else(|| {
|
||||||
|
crate::net::NetError::Parse(format!("CurseForge file '{version_id}' was not found"))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn icon(&self, url: &str) -> Result<Vec<u8>, crate::net::NetError> {
|
||||||
|
self.client
|
||||||
|
.get_bytes_limited(url, crate::net::MAX_PROVIDER_ASSET_BYTES)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn download_version(
|
||||||
|
&self,
|
||||||
|
version: &VersionInfo,
|
||||||
|
destination: &std::path::Path,
|
||||||
|
installed_path: Option<&std::path::Path>,
|
||||||
|
) -> Result<crate::net::modrinth::DownloadOutcome, crate::net::NetError> {
|
||||||
|
let mut version = version.clone();
|
||||||
|
crate::net::curseforge::ensure_download_url(&self.client, &self.api_key, &mut version)
|
||||||
|
.await?;
|
||||||
|
if let Some(installed_path) = installed_path {
|
||||||
|
crate::net::modrinth::download_version_file_for_update(
|
||||||
|
&self.client,
|
||||||
|
&version,
|
||||||
|
destination,
|
||||||
|
installed_path,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
} else {
|
||||||
|
crate::net::modrinth::download_version_file(&self.client, &version, destination).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ProviderRegistry {
|
||||||
|
providers: Vec<Box<dyn ContentProvider>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Newest entry by publish date. Providers are not required to sort their
|
||||||
|
/// responses, so list order is only the tie-breaker.
|
||||||
|
pub(crate) fn newest_version(versions: &[VersionInfo]) -> Option<&VersionInfo> {
|
||||||
|
let first = versions.first()?;
|
||||||
|
Some(versions.iter().fold(first, |newest, version| {
|
||||||
|
if published_at(version) > published_at(newest) {
|
||||||
|
version
|
||||||
|
} else {
|
||||||
|
newest
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `target` supersedes `installed`. Falls back to identity when a
|
||||||
|
/// provider omits publish dates, which keeps the newest-first list order as the
|
||||||
|
/// only signal we have left.
|
||||||
|
pub(crate) fn is_newer(target: &VersionInfo, installed: &VersionInfo) -> bool {
|
||||||
|
match (published_at(target), published_at(installed)) {
|
||||||
|
(Some(target), Some(installed)) => target > installed,
|
||||||
|
_ => target.id != installed.id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn published_at(version: &VersionInfo) -> Option<chrono::DateTime<chrono::FixedOffset>> {
|
||||||
|
chrono::DateTime::parse_from_rfc3339(&version.date_published).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keep provider order for equal or missing dates. Mod version names are
|
||||||
|
/// arbitrary labels, not necessarily comparable version numbers.
|
||||||
|
pub(crate) fn sort_versions_newest_first(versions: &mut [VersionInfo]) {
|
||||||
|
versions.sort_by_cached_key(|version| std::cmp::Reverse(published_at(version)));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn has_newer_compatible_version(
|
||||||
|
versions: &[VersionInfo],
|
||||||
|
installed_version_id: &str,
|
||||||
|
) -> bool {
|
||||||
|
let Some(installed) = versions
|
||||||
|
.iter()
|
||||||
|
.find(|version| version.id == installed_version_id)
|
||||||
|
else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
newest_version(versions).is_some_and(|target| is_newer(target, installed))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProviderRegistry {
|
||||||
|
pub(crate) fn new(providers: Vec<Box<dyn ContentProvider>>) -> Self {
|
||||||
|
Self { providers }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn modrinth(client: crate::net::HttpClient) -> Self {
|
||||||
|
Self::new(vec![Box::new(ModrinthProvider::new(client))])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn configured(client: crate::net::HttpClient) -> Self {
|
||||||
|
let mut providers: Vec<Box<dyn ContentProvider>> =
|
||||||
|
vec![Box::new(ModrinthProvider::new(client.clone()))];
|
||||||
|
if let Some(api_key) = crate::net::curseforge::api_key() {
|
||||||
|
providers.push(Box::new(CurseForgeProvider::new(client, api_key)));
|
||||||
|
}
|
||||||
|
Self::new(providers)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn providers(&self) -> &[Box<dyn ContentProvider>] {
|
||||||
|
&self.providers
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn preferred(&self, id: &str) -> Option<&dyn ContentProvider> {
|
||||||
|
self.providers
|
||||||
|
.iter()
|
||||||
|
.find(|provider| provider.id() == id)
|
||||||
|
.map(Box::as_ref)
|
||||||
|
.or_else(|| self.providers.first().map(Box::as_ref))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self, id: &str) -> Option<&dyn ContentProvider> {
|
||||||
|
self.providers
|
||||||
|
.iter()
|
||||||
|
.find(|provider| provider.id() == id)
|
||||||
|
.map(Box::as_ref)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/content/provider.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,795 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use std::collections::{HashMap, HashSet, VecDeque};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::{Arc, LazyLock, Mutex};
|
||||||
|
|
||||||
|
use super::local::{current_fingerprint, directory_fingerprint_metadata, relative_path};
|
||||||
|
use crate::feedback::progress::{ProgressTask, ProgressTaskHandle};
|
||||||
|
use crate::instance::InstanceConfig;
|
||||||
|
use crate::instance::content::manifest::{
|
||||||
|
ContentFileRecord, ContentKind, ContentLock, ContentManifest, ManifestError, ProviderProject,
|
||||||
|
Resolution, fingerprint, fingerprint_metadata,
|
||||||
|
};
|
||||||
|
use crate::instance::content::provider::{FingerprintQuery, ProviderRegistry};
|
||||||
|
use crate::storage::InstancePaths;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ReconcileResult {
|
||||||
|
pub instance_name: String,
|
||||||
|
pub instance_created: chrono::DateTime<chrono::Utc>,
|
||||||
|
pub manifest: ContentManifest,
|
||||||
|
pub complete: bool,
|
||||||
|
pub error: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub static PENDING_RECONCILIATIONS: LazyLock<Arc<Mutex<Vec<ReconcileResult>>>> =
|
||||||
|
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct ReconcileJob {
|
||||||
|
instance: InstanceConfig,
|
||||||
|
instances_dir: PathBuf,
|
||||||
|
client: crate::net::HttpClient,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct ReconcileCoordinator {
|
||||||
|
queue: VecDeque<ReconcileJob>,
|
||||||
|
scheduled: HashSet<(String, chrono::DateTime<chrono::Utc>)>,
|
||||||
|
rerun: HashSet<(String, chrono::DateTime<chrono::Utc>)>,
|
||||||
|
worker_running: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ReconcileCoordinator {
|
||||||
|
fn enqueue(&mut self, job: ReconcileJob, rerun_if_scheduled: bool) -> bool {
|
||||||
|
let instance = (job.instance.name.clone(), job.instance.created);
|
||||||
|
if !self.scheduled.insert(instance.clone()) {
|
||||||
|
if rerun_if_scheduled {
|
||||||
|
self.rerun.insert(instance);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
self.queue.push_back(job);
|
||||||
|
if self.worker_running {
|
||||||
|
false
|
||||||
|
} else {
|
||||||
|
self.worker_running = true;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static RECONCILE_COORDINATOR: LazyLock<Mutex<ReconcileCoordinator>> =
|
||||||
|
LazyLock::new(|| Mutex::new(ReconcileCoordinator::default()));
|
||||||
|
|
||||||
|
pub fn spawn(instance: InstanceConfig, instances_dir: PathBuf, client: crate::net::HttpClient) {
|
||||||
|
schedule(instance, instances_dir, client, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn spawn_after_change(
|
||||||
|
instance: InstanceConfig,
|
||||||
|
instances_dir: PathBuf,
|
||||||
|
client: crate::net::HttpClient,
|
||||||
|
) {
|
||||||
|
schedule(instance, instances_dir, client, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn schedule(
|
||||||
|
instance: InstanceConfig,
|
||||||
|
instances_dir: PathBuf,
|
||||||
|
client: crate::net::HttpClient,
|
||||||
|
rerun_if_scheduled: bool,
|
||||||
|
) {
|
||||||
|
let start_worker = {
|
||||||
|
let Ok(mut coordinator) = RECONCILE_COORDINATOR.lock() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
coordinator.enqueue(
|
||||||
|
ReconcileJob {
|
||||||
|
instance,
|
||||||
|
instances_dir,
|
||||||
|
client,
|
||||||
|
},
|
||||||
|
rerun_if_scheduled,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
if start_worker {
|
||||||
|
tokio::spawn(reconcile_worker());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn reconcile_worker() {
|
||||||
|
let task = ProgressTask::start("Preparing content index");
|
||||||
|
loop {
|
||||||
|
let job = {
|
||||||
|
let Ok(mut coordinator) = RECONCILE_COORDINATOR.lock() else {
|
||||||
|
task.finish();
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
match coordinator.queue.pop_front() {
|
||||||
|
Some(job) => job,
|
||||||
|
None => {
|
||||||
|
coordinator.worker_running = false;
|
||||||
|
task.finish();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let instance = (job.instance.name.clone(), job.instance.created);
|
||||||
|
let rerun_job = job.clone();
|
||||||
|
let result = reconcile(
|
||||||
|
job.instance,
|
||||||
|
job.instances_dir,
|
||||||
|
job.client,
|
||||||
|
&task,
|
||||||
|
publish_reconciliation,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
publish_reconciliation(result);
|
||||||
|
if let Ok(mut coordinator) = RECONCILE_COORDINATOR.lock() {
|
||||||
|
if coordinator.rerun.remove(&instance) {
|
||||||
|
coordinator.queue.push_back(rerun_job);
|
||||||
|
} else {
|
||||||
|
coordinator.scheduled.remove(&instance);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn publish_reconciliation(result: ReconcileResult) {
|
||||||
|
if let Ok(mut results) = PENDING_RECONCILIATIONS.lock() {
|
||||||
|
results.retain(|pending| {
|
||||||
|
pending.instance_name != result.instance_name
|
||||||
|
|| pending.instance_created != result.instance_created
|
||||||
|
});
|
||||||
|
results.push(result);
|
||||||
|
crate::feedback::request_redraw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn reconcile(
|
||||||
|
instance: InstanceConfig,
|
||||||
|
instances_dir: PathBuf,
|
||||||
|
client: crate::net::HttpClient,
|
||||||
|
task: &ProgressTask,
|
||||||
|
mut publish: impl FnMut(ReconcileResult),
|
||||||
|
) -> ReconcileResult {
|
||||||
|
let instance_name = instance.name;
|
||||||
|
let instance_created = instance.created;
|
||||||
|
task.set_action("Checking content");
|
||||||
|
task.set_sub_action("Reading saved content index");
|
||||||
|
task.set_progress(0, 1);
|
||||||
|
let paths = InstancePaths::new(instances_dir.join(&instance_name));
|
||||||
|
let manifest_path = paths.content_manifest();
|
||||||
|
let minecraft_dir = paths.minecraft();
|
||||||
|
let (retry_hours, max_fingerprint_size_mib) = {
|
||||||
|
let settings = crate::config::SETTINGS.read();
|
||||||
|
(
|
||||||
|
settings.content.unmatched_retry_hours,
|
||||||
|
settings.content.max_fingerprint_size_mib,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let inventory_progress = task.handle();
|
||||||
|
let inventory_minecraft_dir = minecraft_dir.clone();
|
||||||
|
let inventory = tokio::task::spawn_blocking(move || {
|
||||||
|
reconcile_inventory(
|
||||||
|
&manifest_path,
|
||||||
|
&inventory_minecraft_dir,
|
||||||
|
retry_hours,
|
||||||
|
max_fingerprint_size_mib,
|
||||||
|
&inventory_progress,
|
||||||
|
)
|
||||||
|
.map(|result| (result, manifest_path))
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
|
||||||
|
match inventory {
|
||||||
|
Ok(Ok((mut inventory, manifest_path))) => {
|
||||||
|
let resolution_result = if inventory.queries.is_empty() {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
let registry = ProviderRegistry::configured(client);
|
||||||
|
task.set_action("Identifying content");
|
||||||
|
resolve_queries(
|
||||||
|
®istry,
|
||||||
|
&inventory.queries,
|
||||||
|
&mut inventory.manifest,
|
||||||
|
&task.handle(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
};
|
||||||
|
let changed = inventory
|
||||||
|
.manifest
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.filter(|record| inventory.previous.record(&record.relative_path) != Some(record))
|
||||||
|
.count();
|
||||||
|
if changed > 0 {
|
||||||
|
task.set_action("Validating content files");
|
||||||
|
task.set_sub_action("Rechecking changed files");
|
||||||
|
task.set_progress(0, changed as u64);
|
||||||
|
}
|
||||||
|
publish(ReconcileResult {
|
||||||
|
instance_name: instance_name.clone(),
|
||||||
|
instance_created,
|
||||||
|
manifest: inventory.manifest.clone(),
|
||||||
|
complete: false,
|
||||||
|
error: None,
|
||||||
|
});
|
||||||
|
let save_progress = task.handle();
|
||||||
|
let saved = tokio::task::spawn_blocking(move || {
|
||||||
|
save_reconciled_manifest(
|
||||||
|
&manifest_path,
|
||||||
|
&minecraft_dir,
|
||||||
|
inventory.manifest,
|
||||||
|
&inventory.previous,
|
||||||
|
&save_progress,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| {
|
||||||
|
Err(std::io::Error::other(format!("Content save task failed: {error}")).into())
|
||||||
|
});
|
||||||
|
if matches!(saved, Err(ManifestError::Busy(_))) {
|
||||||
|
// Another operation (for example a reinstall commit) holds the
|
||||||
|
// manifest lock. It triggers its own reconciliation when done,
|
||||||
|
// so stay silent instead of warning on every reinstall.
|
||||||
|
tracing::debug!(
|
||||||
|
"Content reconciliation for {instance_name} deferred: manifest busy"
|
||||||
|
);
|
||||||
|
let manifest = ContentManifest::load(&paths.content_manifest()).unwrap_or_default();
|
||||||
|
return ReconcileResult {
|
||||||
|
instance_name,
|
||||||
|
instance_created,
|
||||||
|
manifest,
|
||||||
|
complete: true,
|
||||||
|
error: None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let error = match (resolution_result, &saved) {
|
||||||
|
(Ok(()), Ok(_)) => None,
|
||||||
|
(Err(error), Ok(_)) => Some(error.to_string()),
|
||||||
|
(Ok(()), Err(error)) => Some(error.to_string()),
|
||||||
|
(Err(error), Err(save_error)) => Some(format!(
|
||||||
|
"Provider matching failed: {error}; could not save content inventory: {save_error}"
|
||||||
|
)),
|
||||||
|
};
|
||||||
|
ReconcileResult {
|
||||||
|
instance_name,
|
||||||
|
instance_created,
|
||||||
|
manifest: saved.unwrap_or_default(),
|
||||||
|
complete: true,
|
||||||
|
error,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Err(error)) => {
|
||||||
|
if error
|
||||||
|
.downcast_ref::<ManifestError>()
|
||||||
|
.is_some_and(|error| matches!(error, ManifestError::Busy(_)))
|
||||||
|
{
|
||||||
|
tracing::debug!(
|
||||||
|
"Content reconciliation for {instance_name} deferred: manifest busy"
|
||||||
|
);
|
||||||
|
let manifest = ContentManifest::load(&paths.content_manifest()).unwrap_or_default();
|
||||||
|
return ReconcileResult {
|
||||||
|
instance_name,
|
||||||
|
instance_created,
|
||||||
|
manifest,
|
||||||
|
complete: true,
|
||||||
|
error: None,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
ReconcileResult {
|
||||||
|
instance_name,
|
||||||
|
instance_created,
|
||||||
|
manifest: ContentManifest::default(),
|
||||||
|
complete: true,
|
||||||
|
error: Some(error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(error) => ReconcileResult {
|
||||||
|
instance_name,
|
||||||
|
instance_created,
|
||||||
|
manifest: ContentManifest::default(),
|
||||||
|
complete: true,
|
||||||
|
error: Some(error.to_string()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save_reconciled_manifest(
|
||||||
|
manifest_path: &Path,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
reconciled: ContentManifest,
|
||||||
|
previous: &ContentManifest,
|
||||||
|
task: &impl InventoryProgress,
|
||||||
|
) -> Result<ContentManifest, crate::instance::content::manifest::ManifestError> {
|
||||||
|
let records = reconciled
|
||||||
|
.files
|
||||||
|
.into_iter()
|
||||||
|
.filter(|record| previous.record(&record.relative_path) != Some(record))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
ContentManifest::update(manifest_path, |current| {
|
||||||
|
for record in current.files.clone() {
|
||||||
|
relative_path(minecraft_dir, &minecraft_dir.join(&record.relative_path))?;
|
||||||
|
match std::fs::symlink_metadata(minecraft_dir.join(&record.relative_path)) {
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||||
|
current.remove(&record.relative_path)
|
||||||
|
}
|
||||||
|
Err(error) => return Err(error.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let total = records.len() as u64;
|
||||||
|
task.set_progress(0, total);
|
||||||
|
for (index, mut record) in records.into_iter().enumerate() {
|
||||||
|
task.set_sub_action(record.relative_path.to_string_lossy().as_ref());
|
||||||
|
task.set_progress(index as u64, total);
|
||||||
|
let path = minecraft_dir.join(&record.relative_path);
|
||||||
|
relative_path(minecraft_dir, &path)?;
|
||||||
|
if current.record(&record.relative_path) != previous.record(&record.relative_path) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let metadata = match std::fs::symlink_metadata(&path) {
|
||||||
|
Ok(metadata) => metadata,
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
|
||||||
|
Err(error) => return Err(error.into()),
|
||||||
|
};
|
||||||
|
if metadata.file_type().is_symlink() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let fresh = current_fingerprint(&path, &record.fingerprint)?;
|
||||||
|
if fresh != record.fingerprint {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(existing) = current.record(&record.relative_path)
|
||||||
|
&& existing.fingerprint == record.fingerprint
|
||||||
|
{
|
||||||
|
record
|
||||||
|
.required_dependencies
|
||||||
|
.clone_from(&existing.required_dependencies);
|
||||||
|
record.automatic_dependency = existing.automatic_dependency;
|
||||||
|
record.cleanup_eligible = existing.cleanup_eligible;
|
||||||
|
}
|
||||||
|
let keep_resolved = current
|
||||||
|
.record(&record.relative_path)
|
||||||
|
.is_some_and(|existing| {
|
||||||
|
existing.fingerprint == record.fingerprint
|
||||||
|
&& existing.resolved_project().is_some_and(|current| {
|
||||||
|
record.resolved_project().is_none_or(|resolved| {
|
||||||
|
current.provider != resolved.provider
|
||||||
|
|| current.project_id != resolved.project_id
|
||||||
|
})
|
||||||
|
})
|
||||||
|
});
|
||||||
|
if !keep_resolved {
|
||||||
|
current.upsert(record);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
task.set_progress(total, total);
|
||||||
|
Ok(current.clone())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Inventory {
|
||||||
|
previous: ContentManifest,
|
||||||
|
manifest: ContentManifest,
|
||||||
|
queries: Vec<FingerprintQuery>,
|
||||||
|
}
|
||||||
|
|
||||||
|
trait InventoryProgress {
|
||||||
|
fn set_sub_action(&self, text: &str);
|
||||||
|
fn set_progress(&self, current: u64, total: u64);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InventoryProgress for ProgressTaskHandle {
|
||||||
|
fn set_sub_action(&self, text: &str) {
|
||||||
|
ProgressTaskHandle::set_sub_action(self, text);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_progress(&self, current: u64, total: u64) {
|
||||||
|
ProgressTaskHandle::set_progress(self, current, total);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reconcile_inventory(
|
||||||
|
manifest_path: &Path,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
unmatched_retry_hours: u64,
|
||||||
|
max_fingerprint_size_mib: u64,
|
||||||
|
task: &impl InventoryProgress,
|
||||||
|
) -> Result<Inventory, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let lock = ContentLock::acquire(manifest_path)?;
|
||||||
|
let previous = lock.load()?;
|
||||||
|
let files = content_files(minecraft_dir)?;
|
||||||
|
let file_count = files.len() as u64;
|
||||||
|
if file_count == 0 {
|
||||||
|
task.set_sub_action("No local content files");
|
||||||
|
task.set_progress(1, 1);
|
||||||
|
} else {
|
||||||
|
task.set_progress(0, file_count);
|
||||||
|
}
|
||||||
|
let now = chrono::Utc::now().timestamp();
|
||||||
|
let retry_seconds = unmatched_retry_hours.saturating_mul(60 * 60) as i64;
|
||||||
|
let mut manifest = ContentManifest::default();
|
||||||
|
let mut queries = Vec::new();
|
||||||
|
|
||||||
|
for (index, (kind, path)) in files.into_iter().enumerate() {
|
||||||
|
task.set_sub_action(
|
||||||
|
path.file_name()
|
||||||
|
.and_then(|name| name.to_str())
|
||||||
|
.unwrap_or("content"),
|
||||||
|
);
|
||||||
|
let relative_path = relative_path(minecraft_dir, &path)?;
|
||||||
|
let enabled = !path
|
||||||
|
.file_name()
|
||||||
|
.and_then(|name| name.to_str())
|
||||||
|
.is_some_and(|name| name.ends_with(".disabled"));
|
||||||
|
let metadata = std::fs::metadata(&path)?;
|
||||||
|
let is_directory = metadata.is_dir();
|
||||||
|
let metadata_fingerprint = if is_directory {
|
||||||
|
directory_fingerprint_metadata(&path)?
|
||||||
|
} else {
|
||||||
|
fingerprint_metadata(&path)?
|
||||||
|
};
|
||||||
|
let modified_ns = metadata_fingerprint.modified_ns;
|
||||||
|
let existing = previous.record(&relative_path);
|
||||||
|
let unchanged = existing.is_some_and(|record| {
|
||||||
|
record.fingerprint.size == metadata_fingerprint.size
|
||||||
|
&& record.fingerprint.modified_ns == modified_ns
|
||||||
|
});
|
||||||
|
let oversized = !is_directory
|
||||||
|
&& max_fingerprint_size_mib > 0
|
||||||
|
&& metadata.len() > max_fingerprint_size_mib.saturating_mul(1024 * 1024);
|
||||||
|
let mut record = if unchanged {
|
||||||
|
existing.cloned().unwrap()
|
||||||
|
} else if is_directory {
|
||||||
|
ContentFileRecord {
|
||||||
|
relative_path: relative_path.clone(),
|
||||||
|
kind,
|
||||||
|
enabled,
|
||||||
|
fingerprint: metadata_fingerprint,
|
||||||
|
resolution: Resolution::Unmatched {
|
||||||
|
checked_at: now,
|
||||||
|
providers: Vec::new(),
|
||||||
|
},
|
||||||
|
provider_aliases: Vec::new(),
|
||||||
|
provider_checks: Vec::new(),
|
||||||
|
required_dependencies: Vec::new(),
|
||||||
|
automatic_dependency: false,
|
||||||
|
cleanup_eligible: false,
|
||||||
|
}
|
||||||
|
} else if oversized {
|
||||||
|
tracing::debug!(
|
||||||
|
"Skipping automatic provider matching for {} ({} bytes exceeds {} MiB limit)",
|
||||||
|
path.display(),
|
||||||
|
metadata.len(),
|
||||||
|
max_fingerprint_size_mib
|
||||||
|
);
|
||||||
|
ContentFileRecord {
|
||||||
|
relative_path: relative_path.clone(),
|
||||||
|
kind,
|
||||||
|
enabled,
|
||||||
|
fingerprint: fingerprint_metadata(&path)?,
|
||||||
|
resolution: Resolution::Unmatched {
|
||||||
|
checked_at: now,
|
||||||
|
providers: Vec::new(),
|
||||||
|
},
|
||||||
|
provider_aliases: Vec::new(),
|
||||||
|
provider_checks: Vec::new(),
|
||||||
|
required_dependencies: Vec::new(),
|
||||||
|
automatic_dependency: false,
|
||||||
|
cleanup_eligible: false,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ContentFileRecord {
|
||||||
|
relative_path: relative_path.clone(),
|
||||||
|
kind,
|
||||||
|
enabled,
|
||||||
|
fingerprint: fingerprint(&path)?,
|
||||||
|
resolution: Resolution::Pending,
|
||||||
|
provider_aliases: Vec::new(),
|
||||||
|
provider_checks: Vec::new(),
|
||||||
|
required_dependencies: Vec::new(),
|
||||||
|
automatic_dependency: false,
|
||||||
|
cleanup_eligible: false,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
record.kind = kind;
|
||||||
|
record.enabled = enabled;
|
||||||
|
|
||||||
|
if oversized && matches!(record.resolution, Resolution::Pending) {
|
||||||
|
record.resolution = Resolution::Unmatched {
|
||||||
|
checked_at: now,
|
||||||
|
providers: Vec::new(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let provider_unchecked = ["modrinth", "curseforge"].into_iter().any(|provider| {
|
||||||
|
crate::config::SETTINGS
|
||||||
|
.read()
|
||||||
|
.content
|
||||||
|
.discovery_provider_enabled(provider)
|
||||||
|
&& provider_was_not_checked(&record, provider)
|
||||||
|
});
|
||||||
|
if !is_directory
|
||||||
|
&& !oversized
|
||||||
|
&& provider_unchecked
|
||||||
|
&& record.fingerprint.hash("curseforge").is_none()
|
||||||
|
{
|
||||||
|
record.fingerprint = fingerprint(&path)?;
|
||||||
|
}
|
||||||
|
let should_query = !is_directory
|
||||||
|
&& !oversized
|
||||||
|
&& (provider_unchecked
|
||||||
|
|| match &record.resolution {
|
||||||
|
Resolution::Pending => true,
|
||||||
|
Resolution::Unmatched { checked_at, .. } => {
|
||||||
|
now.saturating_sub(*checked_at) >= retry_seconds
|
||||||
|
}
|
||||||
|
Resolution::Resolved { .. } | Resolution::Ambiguous { .. } => false,
|
||||||
|
});
|
||||||
|
if should_query {
|
||||||
|
if !matches!(&record.resolution, Resolution::Resolved { .. }) {
|
||||||
|
record.resolution = Resolution::Pending;
|
||||||
|
}
|
||||||
|
queries.push(FingerprintQuery {
|
||||||
|
key: relative_path.to_string_lossy().into_owned(),
|
||||||
|
kind,
|
||||||
|
fingerprint: record.fingerprint.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// content_files() yields paths in sorted order and stripping the
|
||||||
|
// common prefix preserves that order, so appending keeps manifest
|
||||||
|
// files sorted without an O(log n) lookup per record.
|
||||||
|
manifest.files.push(record);
|
||||||
|
task.set_progress(index as u64 + 1, file_count);
|
||||||
|
}
|
||||||
|
Ok(Inventory {
|
||||||
|
previous,
|
||||||
|
manifest,
|
||||||
|
queries,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn provider_was_not_checked(record: &ContentFileRecord, provider: &str) -> bool {
|
||||||
|
let identified = record
|
||||||
|
.resolved_project()
|
||||||
|
.into_iter()
|
||||||
|
.chain(record.provider_aliases.iter())
|
||||||
|
.any(|project| project.provider == provider);
|
||||||
|
let checked_as_unmatched = matches!(
|
||||||
|
&record.resolution,
|
||||||
|
Resolution::Unmatched { providers, .. }
|
||||||
|
if providers.iter().any(|checked| checked == provider)
|
||||||
|
);
|
||||||
|
!identified
|
||||||
|
&& !checked_as_unmatched
|
||||||
|
&& !record
|
||||||
|
.provider_checks
|
||||||
|
.iter()
|
||||||
|
.any(|checked| checked == provider)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn resolve_queries(
|
||||||
|
registry: &ProviderRegistry,
|
||||||
|
queries: &[FingerprintQuery],
|
||||||
|
manifest: &mut ContentManifest,
|
||||||
|
task: &impl InventoryProgress,
|
||||||
|
) -> Result<(), crate::net::NetError> {
|
||||||
|
if queries.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let mut matches: HashMap<String, Vec<ProviderProject>> = HashMap::new();
|
||||||
|
let mut checked = Vec::new();
|
||||||
|
let mut last_error = None;
|
||||||
|
let total = (queries.len() * registry.providers().len()) as u64;
|
||||||
|
task.set_progress(0, total);
|
||||||
|
for (index, provider) in registry.providers().iter().enumerate() {
|
||||||
|
let provider_id = provider.id();
|
||||||
|
task.set_sub_action(&format!(
|
||||||
|
"{} file(s) need matching ({provider_id})",
|
||||||
|
queries.len()
|
||||||
|
));
|
||||||
|
match tokio::time::timeout(
|
||||||
|
std::time::Duration::from_secs(10),
|
||||||
|
provider.resolve_files(queries),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(Ok(resolved_files)) => {
|
||||||
|
checked.push(provider_id.to_owned());
|
||||||
|
for resolved in resolved_files {
|
||||||
|
matches
|
||||||
|
.entry(resolved.key)
|
||||||
|
.or_default()
|
||||||
|
.push(resolved.project);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Err(error)) => {
|
||||||
|
tracing::warn!(
|
||||||
|
"Skipping {provider_id} content matching after provider error: {error}"
|
||||||
|
);
|
||||||
|
last_error = Some(error.to_string());
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
tracing::warn!(
|
||||||
|
"Skipping {provider_id} content matching after the 10 second timeout"
|
||||||
|
);
|
||||||
|
last_error = Some(format!("{provider_id} content matching timed out"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
task.set_progress(((index + 1) * queries.len()) as u64, total);
|
||||||
|
}
|
||||||
|
if checked.is_empty() {
|
||||||
|
return Err(crate::net::NetError::TaskFailed(last_error.unwrap_or_else(
|
||||||
|
|| "No content providers are available".to_owned(),
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let query_keys = queries
|
||||||
|
.iter()
|
||||||
|
.map(|query| query.key.as_str())
|
||||||
|
.collect::<HashSet<_>>();
|
||||||
|
let checked_at = chrono::Utc::now().timestamp();
|
||||||
|
for record in &mut manifest.files {
|
||||||
|
let key = record.relative_path.to_string_lossy();
|
||||||
|
if !query_keys.contains(key.as_ref()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let installed = record.resolved_project().cloned();
|
||||||
|
let mut candidates = matches.remove(key.as_ref()).unwrap_or_default();
|
||||||
|
for alias in &record.provider_aliases {
|
||||||
|
if !candidates.iter().any(|candidate| {
|
||||||
|
candidate.provider == alias.provider && candidate.project_id == alias.project_id
|
||||||
|
}) {
|
||||||
|
candidates.push(alias.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let (resolution, aliases) = if let Some(installed) = installed {
|
||||||
|
let project = candidates
|
||||||
|
.iter()
|
||||||
|
.find(|candidate| {
|
||||||
|
candidate.provider == installed.provider
|
||||||
|
&& candidate.project_id == installed.project_id
|
||||||
|
})
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or(installed);
|
||||||
|
candidates.retain(|candidate| {
|
||||||
|
candidate.provider != project.provider || candidate.project_id != project.project_id
|
||||||
|
});
|
||||||
|
(Resolution::Resolved { project }, candidates)
|
||||||
|
} else {
|
||||||
|
match candidates.as_slice() {
|
||||||
|
[] => (
|
||||||
|
Resolution::Unmatched {
|
||||||
|
checked_at,
|
||||||
|
providers: checked.clone(),
|
||||||
|
},
|
||||||
|
Vec::new(),
|
||||||
|
),
|
||||||
|
[project] => (
|
||||||
|
Resolution::Resolved {
|
||||||
|
project: project.clone(),
|
||||||
|
},
|
||||||
|
Vec::new(),
|
||||||
|
),
|
||||||
|
_ if !crate::config::SETTINGS
|
||||||
|
.read()
|
||||||
|
.content
|
||||||
|
.ask_on_provider_conflict =>
|
||||||
|
{
|
||||||
|
let preferred = crate::config::SETTINGS
|
||||||
|
.read()
|
||||||
|
.content
|
||||||
|
.preferred_provider()
|
||||||
|
.to_owned();
|
||||||
|
if let Some(project) = candidates
|
||||||
|
.iter()
|
||||||
|
.find(|project| project.provider == preferred)
|
||||||
|
{
|
||||||
|
(
|
||||||
|
Resolution::Resolved {
|
||||||
|
project: project.clone(),
|
||||||
|
},
|
||||||
|
candidates
|
||||||
|
.iter()
|
||||||
|
.filter(|candidate| *candidate != project)
|
||||||
|
.cloned()
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(Resolution::Ambiguous { candidates }, Vec::new())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => (Resolution::Ambiguous { candidates }, Vec::new()),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
record.resolution = resolution;
|
||||||
|
record.provider_aliases = aliases;
|
||||||
|
for provider in &checked {
|
||||||
|
if !record.provider_checks.contains(provider) {
|
||||||
|
record.provider_checks.push(provider.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn content_files(minecraft_dir: &Path) -> std::io::Result<Vec<(ContentKind, PathBuf)>> {
|
||||||
|
let mut files = Vec::new();
|
||||||
|
for kind in [
|
||||||
|
ContentKind::Mod,
|
||||||
|
ContentKind::ResourcePack,
|
||||||
|
ContentKind::Shader,
|
||||||
|
] {
|
||||||
|
let directory = minecraft_dir.join(kind.directory());
|
||||||
|
let entries = read_content_directory(&directory)?;
|
||||||
|
for entry in entries {
|
||||||
|
let entry = entry?;
|
||||||
|
let path = entry.path();
|
||||||
|
if supported_content_path(kind, &path)? {
|
||||||
|
files.push((kind, path));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
{
|
||||||
|
for world in read_content_directory(&minecraft_dir.join("saves"))? {
|
||||||
|
let world = world?;
|
||||||
|
if !world.file_type()?.is_dir() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let entries = read_content_directory(&world.path().join("datapacks"))?;
|
||||||
|
for entry in entries {
|
||||||
|
let entry = entry?;
|
||||||
|
let path = entry.path();
|
||||||
|
if supported_content_path(ContentKind::DataPack, &path)? {
|
||||||
|
files.push((ContentKind::DataPack, path));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
files.sort_by(|left, right| left.1.cmp(&right.1));
|
||||||
|
Ok(files)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_content_directory(
|
||||||
|
path: &Path,
|
||||||
|
) -> std::io::Result<impl Iterator<Item = std::io::Result<std::fs::DirEntry>> + use<>> {
|
||||||
|
match std::fs::read_dir(path) {
|
||||||
|
Ok(entries) => Ok(Some(entries).into_iter().flatten()),
|
||||||
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||||
|
Ok(None.into_iter().flatten())
|
||||||
|
}
|
||||||
|
Err(error) => Err(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supported_content_path(kind: ContentKind, path: &Path) -> std::io::Result<bool> {
|
||||||
|
let metadata = std::fs::symlink_metadata(path)?;
|
||||||
|
if metadata.file_type().is_symlink() {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
if metadata.is_dir() {
|
||||||
|
return Ok(matches!(
|
||||||
|
kind,
|
||||||
|
ContentKind::ResourcePack | ContentKind::Shader | ContentKind::DataPack
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if !metadata.is_file() {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
|
||||||
|
return Ok(false);
|
||||||
|
};
|
||||||
|
Ok(match kind {
|
||||||
|
ContentKind::Mod => name.ends_with(".jar") || name.ends_with(".jar.disabled"),
|
||||||
|
ContentKind::ResourcePack | ContentKind::Shader | ContentKind::DataPack => {
|
||||||
|
name.ends_with(".zip") || name.ends_with(".zip.disabled")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/content/reconcile.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -1,258 +1,18 @@
|
|||||||
// resource pack scanning. packs can be either .zip files or plain directories,
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
// and metadata lives in pack.mcmeta (which mojang decided should have like 3
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
// different ways to encode a description, because why not)
|
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use serde::Deserialize;
|
use super::entry::ContentEntry;
|
||||||
|
|
||||||
use super::mods::{make_icon_pixels, ContentEntry};
|
pub fn scan_one_resource_pack(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||||
|
super::packs::scan_one_pack(path, file_stem, enabled)
|
||||||
#[derive(Deserialize, Default)]
|
|
||||||
pub(crate) struct PackMcMeta {
|
|
||||||
#[serde(default)]
|
|
||||||
pub pack: PackInfo,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize, Default)]
|
|
||||||
pub(crate) struct PackInfo {
|
|
||||||
#[serde(default)]
|
|
||||||
pub description: serde_json::Value,
|
|
||||||
}
|
|
||||||
|
|
||||||
// description can be a plain string, a chat component object with "text",
|
|
||||||
// or an array mixing both. thanks mojang, very cool.
|
|
||||||
pub(crate) fn extract_description(value: &serde_json::Value) -> String {
|
|
||||||
match value {
|
|
||||||
serde_json::Value::String(s) => s.clone(),
|
|
||||||
serde_json::Value::Object(obj) => obj
|
|
||||||
.get("text")
|
|
||||||
.and_then(|v| v.as_str())
|
|
||||||
.unwrap_or("")
|
|
||||||
.to_string(),
|
|
||||||
serde_json::Value::Array(arr) => arr
|
|
||||||
.iter()
|
|
||||||
.filter_map(|v| match v {
|
|
||||||
serde_json::Value::String(s) => Some(s.as_str()),
|
|
||||||
serde_json::Value::Object(obj) => obj.get("text").and_then(|v| v.as_str()),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join(""),
|
|
||||||
_ => String::new(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
pub fn scan_resource_packs(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||||
let packs_dir = instances_dir
|
super::packs::scan_packs(instances_dir, instance_name, "resourcepacks")
|
||||||
.join(instance_name)
|
|
||||||
.join(".minecraft")
|
|
||||||
.join("resourcepacks");
|
|
||||||
|
|
||||||
let read_dir = match std::fs::read_dir(&packs_dir) {
|
|
||||||
Ok(rd) => rd,
|
|
||||||
Err(_) => return Vec::new(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut entries = Vec::new();
|
|
||||||
|
|
||||||
for entry in read_dir.flatten() {
|
|
||||||
let path = entry.path();
|
|
||||||
let file_name = match path.file_name().and_then(|n| n.to_str()) {
|
|
||||||
Some(n) => n.to_string(),
|
|
||||||
None => continue,
|
|
||||||
};
|
|
||||||
|
|
||||||
let is_dir = path.is_dir();
|
|
||||||
let (enabled, file_stem) = if is_dir {
|
|
||||||
super::parse_enabled_stem_dir(&file_name)
|
|
||||||
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
|
|
||||||
pair
|
|
||||||
} else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
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));
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_pack_metadata_from_zip(zip_path: &Path) -> (String, String, Option<Vec<u8>>) {
|
|
||||||
let Some(mut archive) = super::open_zip(zip_path) else {
|
|
||||||
return (String::new(), String::new(), None);
|
|
||||||
};
|
|
||||||
let description = read_pack_description(&mut archive);
|
|
||||||
let icon_bytes = super::read_icon_from_zip(&mut archive);
|
|
||||||
(String::new(), description, icon_bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_pack_description(archive: &mut zip::ZipArchive<std::fs::File>) -> String {
|
|
||||||
archive
|
|
||||||
.by_name("pack.mcmeta")
|
|
||||||
.ok()
|
|
||||||
.and_then(|entry| serde_json::from_reader::<_, PackMcMeta>(entry).ok())
|
|
||||||
.map(|meta| extract_description(&meta.pack.description))
|
|
||||||
.unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_pack_metadata_from_dir(dir: &Path) -> (String, String, Option<Vec<u8>>) {
|
|
||||||
let description = std::fs::read_to_string(dir.join("pack.mcmeta"))
|
|
||||||
.ok()
|
|
||||||
.and_then(|content| serde_json::from_str::<PackMcMeta>(&content).ok())
|
|
||||||
.map(|meta| extract_description(&meta.pack.description))
|
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
let icon_bytes = std::fs::read(dir.join("pack.png")).ok();
|
|
||||||
|
|
||||||
(String::new(), description, icon_bytes)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "../tests/content/resource_packs.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_string() {
|
|
||||||
let val = serde_json::json!("Simple pack");
|
|
||||||
assert_eq!(extract_description(&val), "Simple pack");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_object_with_text() {
|
|
||||||
let val = serde_json::json!({"text": "Hello world"});
|
|
||||||
assert_eq!(extract_description(&val), "Hello world");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_object_without_text() {
|
|
||||||
let val = serde_json::json!({"color": "red"});
|
|
||||||
assert_eq!(extract_description(&val), "");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_array_of_strings() {
|
|
||||||
let val = serde_json::json!(["Hello", " ", "world"]);
|
|
||||||
assert_eq!(extract_description(&val), "Hello world");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_array_of_objects() {
|
|
||||||
let val = serde_json::json!([{"text": "A"}, {"text": "B"}]);
|
|
||||||
assert_eq!(extract_description(&val), "AB");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_mixed_array() {
|
|
||||||
let val = serde_json::json!(["Prefix ", {"text": "suffix"}]);
|
|
||||||
assert_eq!(extract_description(&val), "Prefix suffix");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_empty_array() {
|
|
||||||
let val = serde_json::json!([]);
|
|
||||||
assert_eq!(extract_description(&val), "");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_null() {
|
|
||||||
let val = serde_json::Value::Null;
|
|
||||||
assert_eq!(extract_description(&val), "");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_number() {
|
|
||||||
let val = serde_json::json!(42);
|
|
||||||
assert_eq!(extract_description(&val), "");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extract_description_from_bool() {
|
|
||||||
let val = serde_json::json!(true);
|
|
||||||
assert_eq!(extract_description(&val), "");
|
|
||||||
}
|
|
||||||
|
|
||||||
fn setup_packs_dir(tmp: &std::path::Path, instance: &str) -> std::path::PathBuf {
|
|
||||||
let dir = tmp
|
|
||||||
.join(instance)
|
|
||||||
.join(".minecraft")
|
|
||||||
.join("resourcepacks");
|
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
|
||||||
dir
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_resource_packs_empty_dir() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
setup_packs_dir(tmp.path(), "inst");
|
|
||||||
let packs = scan_resource_packs(tmp.path(), "inst");
|
|
||||||
assert!(packs.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_resource_packs_missing_dir_returns_empty() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let packs = scan_resource_packs(tmp.path(), "ghost");
|
|
||||||
assert!(packs.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_resource_packs_finds_zips_and_dirs() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_packs_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("pack-a.zip"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::create_dir(dir.join("pack-b")).unwrap();
|
|
||||||
let packs = scan_resource_packs(tmp.path(), "inst");
|
|
||||||
assert_eq!(packs.len(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_resource_packs_disabled_variants() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_packs_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("on.zip"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::write(dir.join("off.zip.disabled"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::create_dir(dir.join("diron")).unwrap();
|
|
||||||
std::fs::create_dir(dir.join("diroff.disabled")).unwrap();
|
|
||||||
let packs = scan_resource_packs(tmp.path(), "inst");
|
|
||||||
assert_eq!(packs.len(), 4);
|
|
||||||
let on_zip = packs.iter().find(|p| p.file_stem == "on").unwrap();
|
|
||||||
let off_zip = packs.iter().find(|p| p.file_stem == "off").unwrap();
|
|
||||||
let on_dir = packs.iter().find(|p| p.file_stem == "diron").unwrap();
|
|
||||||
let off_dir = packs.iter().find(|p| p.file_stem == "diroff").unwrap();
|
|
||||||
assert!(on_zip.enabled);
|
|
||||||
assert!(!off_zip.enabled);
|
|
||||||
assert!(on_dir.enabled);
|
|
||||||
assert!(!off_dir.enabled);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_resource_packs_ignores_non_pack_files() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_packs_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("notes.txt"), "not a pack").unwrap();
|
|
||||||
std::fs::write(dir.join("valid.zip"), b"PK\x03\x04").unwrap();
|
|
||||||
let packs = scan_resource_packs(tmp.path(), "inst");
|
|
||||||
assert_eq!(packs.len(), 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,149 +1,14 @@
|
|||||||
// shader pack scanning. structurally almost identical to resource packs
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
// (zip or dir, pack.mcmeta for metadata, pack.png for icon)
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use super::mods::{make_icon_pixels, ContentEntry};
|
use super::entry::ContentEntry;
|
||||||
use super::resource_packs::{extract_description, PackMcMeta};
|
|
||||||
|
pub fn scan_one_shader(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||||
|
super::packs::scan_one_pack(path, file_stem, enabled)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
pub fn scan_shaders(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||||
let shaders_dir = instances_dir
|
super::packs::scan_packs(instances_dir, instance_name, "shaderpacks")
|
||||||
.join(instance_name)
|
|
||||||
.join(".minecraft")
|
|
||||||
.join("shaderpacks");
|
|
||||||
|
|
||||||
let read_dir = match std::fs::read_dir(&shaders_dir) {
|
|
||||||
Ok(rd) => rd,
|
|
||||||
Err(_) => return Vec::new(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut entries = Vec::new();
|
|
||||||
|
|
||||||
for entry in read_dir.flatten() {
|
|
||||||
let path = entry.path();
|
|
||||||
let file_name = match path.file_name().and_then(|n| n.to_str()) {
|
|
||||||
Some(n) => n.to_string(),
|
|
||||||
None => continue,
|
|
||||||
};
|
|
||||||
|
|
||||||
let is_dir = path.is_dir();
|
|
||||||
let (enabled, file_stem) = if is_dir {
|
|
||||||
super::parse_enabled_stem_dir(&file_name)
|
|
||||||
} else if let Some(pair) = super::parse_enabled_stem(&file_name, ".zip") {
|
|
||||||
pair
|
|
||||||
} else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
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));
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_shader_metadata_from_zip(zip_path: &Path) -> (String, Option<Vec<u8>>) {
|
|
||||||
let Some(mut archive) = super::open_zip(zip_path) else {
|
|
||||||
return (String::new(), None);
|
|
||||||
};
|
|
||||||
let description = archive
|
|
||||||
.by_name("pack.mcmeta")
|
|
||||||
.ok()
|
|
||||||
.and_then(|entry| serde_json::from_reader::<_, PackMcMeta>(entry).ok())
|
|
||||||
.map(|meta| extract_description(&meta.pack.description))
|
|
||||||
.unwrap_or_default();
|
|
||||||
let icon_bytes = super::read_icon_from_zip(&mut archive);
|
|
||||||
(description, icon_bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_shader_metadata_from_dir(dir: &Path) -> (String, Option<Vec<u8>>) {
|
|
||||||
let description = std::fs::read_to_string(dir.join("pack.mcmeta"))
|
|
||||||
.ok()
|
|
||||||
.and_then(|content| serde_json::from_str::<PackMcMeta>(&content).ok())
|
|
||||||
.map(|meta| extract_description(&meta.pack.description))
|
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
let icon_bytes = std::fs::read(dir.join("pack.png")).ok();
|
|
||||||
|
|
||||||
(description, icon_bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn setup_shaders_dir(tmp: &std::path::Path, instance: &str) -> std::path::PathBuf {
|
|
||||||
let dir = tmp.join(instance).join(".minecraft").join("shaderpacks");
|
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
|
||||||
dir
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_shaders_empty_dir() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
setup_shaders_dir(tmp.path(), "inst");
|
|
||||||
let shaders = scan_shaders(tmp.path(), "inst");
|
|
||||||
assert!(shaders.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_shaders_missing_dir_returns_empty() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let shaders = scan_shaders(tmp.path(), "ghost");
|
|
||||||
assert!(shaders.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_shaders_finds_zip_and_dir() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_shaders_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("shader-a.zip"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::create_dir(dir.join("shader-b")).unwrap();
|
|
||||||
let shaders = scan_shaders(tmp.path(), "inst");
|
|
||||||
assert_eq!(shaders.len(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_shaders_disabled_variants() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_shaders_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("active.zip"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::write(dir.join("off.zip.disabled"), b"PK\x03\x04").unwrap();
|
|
||||||
std::fs::create_dir(dir.join("dirshader.disabled")).unwrap();
|
|
||||||
let shaders = scan_shaders(tmp.path(), "inst");
|
|
||||||
let active = shaders.iter().find(|s| s.file_stem == "active").unwrap();
|
|
||||||
let off = shaders.iter().find(|s| s.file_stem == "off").unwrap();
|
|
||||||
let diroff = shaders.iter().find(|s| s.file_stem == "dirshader").unwrap();
|
|
||||||
assert!(active.enabled);
|
|
||||||
assert!(!off.enabled);
|
|
||||||
assert!(!diroff.enabled);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_shaders_ignores_non_shader_files() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_shaders_dir(tmp.path(), "inst");
|
|
||||||
std::fs::write(dir.join("readme.txt"), "not a shader").unwrap();
|
|
||||||
std::fs::write(dir.join("valid.zip"), b"PK\x03\x04").unwrap();
|
|
||||||
let shaders = scan_shaders(tmp.path(), "inst");
|
|
||||||
assert_eq!(shaders.len(), 1);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,816 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::{Arc, LazyLock, Mutex};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::instance::{ContentKind, ContentManifest, InstanceConfig, ModLoader, ProviderProject};
|
||||||
|
use crate::net::modrinth::VersionInfo;
|
||||||
|
|
||||||
|
use super::dependencies::{DependencyPlan, InstallRoot};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct AvailableUpdate {
|
||||||
|
pub installed: ProviderProject,
|
||||||
|
#[serde(default)]
|
||||||
|
pub current: Option<VersionInfo>,
|
||||||
|
pub target: VersionInfo,
|
||||||
|
pub kind: ContentKind,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct UpdateSnapshot {
|
||||||
|
pub game_version: String,
|
||||||
|
pub loader: ModLoader,
|
||||||
|
#[serde(default)]
|
||||||
|
pub inventory: Vec<ProviderProject>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub checked_at: i64,
|
||||||
|
pub updates: Vec<AvailableUpdate>,
|
||||||
|
pub failures: Vec<UpdateCheckFailure>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How long a snapshot is trusted before the next reconciliation rechecks it.
|
||||||
|
/// Anything shorter re-scans every mod against the provider APIs each time the
|
||||||
|
/// instance is selected.
|
||||||
|
const RECHECK_AFTER_SECONDS: i64 = 30 * 60;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct UpdateCheckFailure {
|
||||||
|
pub installed: ProviderProject,
|
||||||
|
pub kind: ContentKind,
|
||||||
|
pub reason: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct PendingUpdateSnapshot {
|
||||||
|
pub instance_name: String,
|
||||||
|
pub instance_created: chrono::DateTime<chrono::Utc>,
|
||||||
|
pub snapshot: UpdateSnapshot,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct UpdateRequest {
|
||||||
|
pub title: String,
|
||||||
|
pub installed_path: std::path::PathBuf,
|
||||||
|
pub target_world: Option<std::path::PathBuf>,
|
||||||
|
pub update: AvailableUpdate,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct PlannedRootUpdate {
|
||||||
|
pub title: String,
|
||||||
|
pub installed_path: std::path::PathBuf,
|
||||||
|
pub current_version: String,
|
||||||
|
pub target: VersionInfo,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct UpdateConflict {
|
||||||
|
pub title: String,
|
||||||
|
pub installed_path: std::path::PathBuf,
|
||||||
|
pub reason: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct BulkUpdatePlan {
|
||||||
|
pub dependency_plan: DependencyPlan,
|
||||||
|
pub roots: Vec<PlannedRootUpdate>,
|
||||||
|
pub conflicts: Vec<UpdateConflict>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub static PENDING_UPDATE_SNAPSHOTS: LazyLock<Arc<Mutex<Vec<PendingUpdateSnapshot>>>> =
|
||||||
|
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
|
||||||
|
|
||||||
|
struct RunningCheck {
|
||||||
|
instance: InstanceConfig,
|
||||||
|
inventory: Vec<ProviderProject>,
|
||||||
|
task: tokio::task::JoinHandle<()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RunningCheck {
|
||||||
|
fn matches(&self, instance: &InstanceConfig, manifest: &ContentManifest) -> bool {
|
||||||
|
self.instance.created == instance.created
|
||||||
|
&& self.instance.game_version == instance.game_version
|
||||||
|
&& self.instance.loader == instance.loader
|
||||||
|
&& self.inventory == resolved_inventory(manifest)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static RUNNING_CHECKS: LazyLock<Mutex<HashMap<std::path::PathBuf, RunningCheck>>> =
|
||||||
|
LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||||
|
|
||||||
|
impl UpdateSnapshot {
|
||||||
|
pub fn load(path: &std::path::Path) -> Option<Self> {
|
||||||
|
std::fs::read(path)
|
||||||
|
.ok()
|
||||||
|
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn applies_to(&self, instance: &InstanceConfig) -> bool {
|
||||||
|
self.game_version == instance.game_version && self.loader == instance.loader
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn matches_manifest(&self, manifest: &ContentManifest) -> bool {
|
||||||
|
self.inventory == resolved_inventory(manifest)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the snapshot is worth re-scanning. Note that a stale snapshot is
|
||||||
|
/// still displayed: every entry is keyed by its exact installed version, so
|
||||||
|
/// content that changed since the scan simply stops matching instead of
|
||||||
|
/// invalidating the labels of everything else.
|
||||||
|
pub fn is_stale(&self, manifest: &ContentManifest) -> bool {
|
||||||
|
!self.matches_manifest(manifest)
|
||||||
|
|| chrono::Utc::now()
|
||||||
|
.timestamp()
|
||||||
|
.saturating_sub(self.checked_at)
|
||||||
|
>= RECHECK_AFTER_SECONDS
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update_for(&self, installed: &ProviderProject) -> Option<&AvailableUpdate> {
|
||||||
|
self.updates.iter().find(|update| {
|
||||||
|
update.installed.provider == installed.provider
|
||||||
|
&& update.installed.project_id == installed.project_id
|
||||||
|
&& update.installed.version_id == installed.version_id
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn spawn(
|
||||||
|
instance: InstanceConfig,
|
||||||
|
manifest: ContentManifest,
|
||||||
|
path: std::path::PathBuf,
|
||||||
|
priority: Vec<ProviderProject>,
|
||||||
|
previous: Option<UpdateSnapshot>,
|
||||||
|
) {
|
||||||
|
spawn_with_registry(
|
||||||
|
instance,
|
||||||
|
manifest,
|
||||||
|
path,
|
||||||
|
priority,
|
||||||
|
previous,
|
||||||
|
Arc::new(super::provider::ProviderRegistry::configured(
|
||||||
|
crate::net::HttpClient::new(),
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn is_running(
|
||||||
|
instance: &InstanceConfig,
|
||||||
|
manifest: &ContentManifest,
|
||||||
|
path: &std::path::Path,
|
||||||
|
) -> bool {
|
||||||
|
RUNNING_CHECKS.lock().is_ok_and(|checks| {
|
||||||
|
checks
|
||||||
|
.get(path)
|
||||||
|
.is_some_and(|check| !check.task.is_finished() && check.matches(instance, manifest))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn cancel(path: Option<&std::path::Path>) {
|
||||||
|
if let Ok(mut checks) = RUNNING_CHECKS.lock() {
|
||||||
|
checks.retain(|check_path, check| {
|
||||||
|
if path.is_none_or(|path| path == check_path) {
|
||||||
|
check.task.abort();
|
||||||
|
if let Ok(mut pending) = PENDING_UPDATE_SNAPSHOTS.lock() {
|
||||||
|
pending.retain(|pending| {
|
||||||
|
pending.instance_name != check.instance.name
|
||||||
|
|| pending.instance_created != check.instance.created
|
||||||
|
});
|
||||||
|
}
|
||||||
|
false
|
||||||
|
} else {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn spawn_with_registry(
|
||||||
|
instance: InstanceConfig,
|
||||||
|
manifest: ContentManifest,
|
||||||
|
path: std::path::PathBuf,
|
||||||
|
priority: Vec<ProviderProject>,
|
||||||
|
previous: Option<UpdateSnapshot>,
|
||||||
|
registry: Arc<super::provider::ProviderRegistry>,
|
||||||
|
) -> bool {
|
||||||
|
let Ok(mut checks) = RUNNING_CHECKS.lock() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
if let Some(check) = checks.get(&path) {
|
||||||
|
if !check.task.is_finished() && check.matches(&instance, &manifest) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
check.task.abort();
|
||||||
|
}
|
||||||
|
let check_path = path.clone();
|
||||||
|
let check_instance = instance.clone();
|
||||||
|
let inventory = resolved_inventory(&manifest);
|
||||||
|
let task = tokio::spawn(async move {
|
||||||
|
let previous = previous
|
||||||
|
.or_else(|| UpdateSnapshot::load(&path))
|
||||||
|
.filter(|previous| previous.applies_to(&instance));
|
||||||
|
let snapshot = scan_with_registry(
|
||||||
|
&instance,
|
||||||
|
&manifest,
|
||||||
|
&priority,
|
||||||
|
registry,
|
||||||
|
previous.as_ref(),
|
||||||
|
|snapshot| publish_current_snapshot(&instance, snapshot.clone(), &path, false),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
publish_current_snapshot(&instance, snapshot, &path, true);
|
||||||
|
});
|
||||||
|
checks.insert(
|
||||||
|
check_path,
|
||||||
|
RunningCheck {
|
||||||
|
instance: check_instance,
|
||||||
|
inventory,
|
||||||
|
task,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn publish_current_snapshot(
|
||||||
|
instance: &InstanceConfig,
|
||||||
|
snapshot: UpdateSnapshot,
|
||||||
|
path: &std::path::Path,
|
||||||
|
complete: bool,
|
||||||
|
) {
|
||||||
|
let Ok(checks) = RUNNING_CHECKS.lock() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if checks
|
||||||
|
.get(path)
|
||||||
|
.is_none_or(|check| check.task.id() != tokio::task::id())
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Hold the check registry through persistence and publication so a replaced
|
||||||
|
// worker cannot overwrite its successor's snapshot.
|
||||||
|
if complete
|
||||||
|
&& let Ok(bytes) = serde_json::to_vec_pretty(&snapshot)
|
||||||
|
&& let Err(error) = crate::storage::write_atomic(path, &bytes)
|
||||||
|
{
|
||||||
|
tracing::debug!("Could not cache content update snapshot: {error}");
|
||||||
|
}
|
||||||
|
publish_snapshot(instance, snapshot);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn publish_snapshot(instance: &InstanceConfig, snapshot: UpdateSnapshot) {
|
||||||
|
if let Ok(mut pending) = PENDING_UPDATE_SNAPSHOTS.lock() {
|
||||||
|
pending.retain(|pending| {
|
||||||
|
pending.instance_name != instance.name
|
||||||
|
|| pending.instance_created != instance.created
|
||||||
|
|| pending.snapshot.game_version != snapshot.game_version
|
||||||
|
|| pending.snapshot.loader != snapshot.loader
|
||||||
|
});
|
||||||
|
pending.push(PendingUpdateSnapshot {
|
||||||
|
instance_name: instance.name.clone(),
|
||||||
|
instance_created: instance.created,
|
||||||
|
snapshot,
|
||||||
|
});
|
||||||
|
crate::feedback::request_redraw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn scan(instance: &InstanceConfig, manifest: &ContentManifest) -> UpdateSnapshot {
|
||||||
|
scan_with_registry(
|
||||||
|
instance,
|
||||||
|
manifest,
|
||||||
|
&[],
|
||||||
|
Arc::new(super::provider::ProviderRegistry::configured(
|
||||||
|
crate::net::HttpClient::new(),
|
||||||
|
)),
|
||||||
|
None,
|
||||||
|
|_| {},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn scan_with_registry(
|
||||||
|
instance: &InstanceConfig,
|
||||||
|
manifest: &ContentManifest,
|
||||||
|
priority: &[ProviderProject],
|
||||||
|
registry: Arc<super::provider::ProviderRegistry>,
|
||||||
|
previous: Option<&UpdateSnapshot>,
|
||||||
|
mut publish: impl FnMut(&UpdateSnapshot),
|
||||||
|
) -> UpdateSnapshot {
|
||||||
|
let previous = previous.filter(|snapshot| snapshot.applies_to(instance));
|
||||||
|
let now = chrono::Utc::now().timestamp();
|
||||||
|
let reusable =
|
||||||
|
previous.filter(|snapshot| now.saturating_sub(snapshot.checked_at) < RECHECK_AFTER_SECONDS);
|
||||||
|
let mut projects = manifest
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.filter_map(|record| {
|
||||||
|
record
|
||||||
|
.resolved_project()
|
||||||
|
.cloned()
|
||||||
|
.map(|project| (project, record.kind))
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
projects.sort_by(|left, right| {
|
||||||
|
(&left.0.provider, &left.0.project_id, &left.0.version_id).cmp(&(
|
||||||
|
&right.0.provider,
|
||||||
|
&right.0.project_id,
|
||||||
|
&right.0.version_id,
|
||||||
|
))
|
||||||
|
});
|
||||||
|
projects.dedup_by(|left, right| {
|
||||||
|
left.0.provider == right.0.provider
|
||||||
|
&& left.0.project_id == right.0.project_id
|
||||||
|
&& left.0.version_id == right.0.version_id
|
||||||
|
});
|
||||||
|
let inventory = resolved_inventory(manifest);
|
||||||
|
let priority = priority
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.rev()
|
||||||
|
.map(|(index, project)| {
|
||||||
|
(
|
||||||
|
(&project.provider, &project.project_id, &project.version_id),
|
||||||
|
index,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect::<HashMap<_, _>>();
|
||||||
|
projects.sort_by_key(|(project, _)| {
|
||||||
|
priority
|
||||||
|
.get(&(&project.provider, &project.project_id, &project.version_id))
|
||||||
|
.copied()
|
||||||
|
.unwrap_or(usize::MAX)
|
||||||
|
});
|
||||||
|
let mut snapshot = UpdateSnapshot {
|
||||||
|
game_version: instance.game_version.clone(),
|
||||||
|
loader: instance.loader,
|
||||||
|
inventory,
|
||||||
|
checked_at: 0,
|
||||||
|
updates: previous
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|previous| previous.updates.iter())
|
||||||
|
.filter(|update| {
|
||||||
|
projects
|
||||||
|
.iter()
|
||||||
|
.any(|(installed, _)| installed == &update.installed)
|
||||||
|
})
|
||||||
|
.cloned()
|
||||||
|
.collect(),
|
||||||
|
failures: Vec::new(),
|
||||||
|
};
|
||||||
|
projects.retain(|(installed, _)| {
|
||||||
|
reusable.is_none_or(|snapshot| {
|
||||||
|
!snapshot.inventory.contains(installed)
|
||||||
|
|| snapshot
|
||||||
|
.failures
|
||||||
|
.iter()
|
||||||
|
.any(|failure| &failure.installed == installed)
|
||||||
|
})
|
||||||
|
});
|
||||||
|
// Reusing old results must not extend their freshness on each inventory change.
|
||||||
|
let checked_at = reusable.map_or(now, |snapshot| snapshot.checked_at);
|
||||||
|
if projects.is_empty() {
|
||||||
|
snapshot.checked_at = checked_at;
|
||||||
|
return snapshot;
|
||||||
|
}
|
||||||
|
let total = projects.len() as u64;
|
||||||
|
let progress = crate::feedback::progress::ProgressTask::start("Checking content updates");
|
||||||
|
progress.set_progress(0, total);
|
||||||
|
let mut completed = 0;
|
||||||
|
let mut projects = projects.into_iter();
|
||||||
|
let mut tasks = tokio::task::JoinSet::new();
|
||||||
|
loop {
|
||||||
|
while tasks.len() < 8 {
|
||||||
|
let Some((installed, kind)) = projects.next() else {
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
let registry = registry.clone();
|
||||||
|
let game_version = instance.game_version.clone();
|
||||||
|
let loader = instance.loader;
|
||||||
|
tasks.spawn(async move {
|
||||||
|
let result = async {
|
||||||
|
let provider = registry.get(&installed.provider).ok_or_else(|| {
|
||||||
|
format!("{} content provider is unavailable", installed.provider)
|
||||||
|
})?;
|
||||||
|
let versions = provider
|
||||||
|
.compatible_versions(&installed.project_id, kind, &game_version, loader)
|
||||||
|
.await
|
||||||
|
.map_err(|error| error.to_string())?;
|
||||||
|
let Some(newest) =
|
||||||
|
crate::instance::content::provider::newest_version(&versions)
|
||||||
|
else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
// Packs can pin versions omitted from the compatible list.
|
||||||
|
let current = match versions
|
||||||
|
.iter()
|
||||||
|
.find(|version| version.id == installed.version_id)
|
||||||
|
{
|
||||||
|
Some(current) => current.clone(),
|
||||||
|
None => provider
|
||||||
|
.version(&installed.version_id)
|
||||||
|
.await
|
||||||
|
.map_err(|error| error.to_string())?,
|
||||||
|
};
|
||||||
|
let target =
|
||||||
|
super::provider::is_newer(newest, ¤t).then(|| newest.clone());
|
||||||
|
Ok::<_, String>(target.map(|target| (Some(current), target)))
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
(installed, kind, result)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let Some(result) = tasks.join_next().await else {
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
if let Ok((installed, _, Ok(_))) = &result {
|
||||||
|
snapshot
|
||||||
|
.updates
|
||||||
|
.retain(|update| &update.installed != installed);
|
||||||
|
}
|
||||||
|
match result {
|
||||||
|
Ok((installed, kind, Ok(Some((current, target))))) => {
|
||||||
|
snapshot.updates.push(AvailableUpdate {
|
||||||
|
installed,
|
||||||
|
current,
|
||||||
|
target,
|
||||||
|
kind,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Ok((_, _, Ok(None))) => {}
|
||||||
|
Ok((installed, kind, Err(reason))) => snapshot.failures.push(UpdateCheckFailure {
|
||||||
|
installed,
|
||||||
|
kind,
|
||||||
|
reason,
|
||||||
|
}),
|
||||||
|
Err(error) => tracing::debug!("Content update task failed: {error}"),
|
||||||
|
}
|
||||||
|
completed += 1;
|
||||||
|
progress.set_sub_action(format!("{completed}/{total} item(s) checked"));
|
||||||
|
progress.set_progress(completed, total);
|
||||||
|
publish(&snapshot);
|
||||||
|
}
|
||||||
|
sort_updates(&mut snapshot.updates);
|
||||||
|
snapshot.checked_at = checked_at;
|
||||||
|
snapshot
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sort_updates(updates: &mut [AvailableUpdate]) {
|
||||||
|
updates.sort_by(|left, right| {
|
||||||
|
(&left.installed.provider, &left.installed.project_id)
|
||||||
|
.cmp(&(&right.installed.provider, &right.installed.project_id))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolved_inventory(manifest: &ContentManifest) -> Vec<ProviderProject> {
|
||||||
|
let mut inventory = manifest
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.filter_map(|record| record.resolved_project().cloned())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
inventory.sort_by(|left, right| {
|
||||||
|
(&left.provider, &left.project_id, &left.version_id).cmp(&(
|
||||||
|
&right.provider,
|
||||||
|
&right.project_id,
|
||||||
|
&right.version_id,
|
||||||
|
))
|
||||||
|
});
|
||||||
|
inventory.dedup();
|
||||||
|
inventory
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn plan_bulk(
|
||||||
|
instance: &InstanceConfig,
|
||||||
|
manifest: &ContentManifest,
|
||||||
|
minecraft_dir: &std::path::Path,
|
||||||
|
requests: Vec<UpdateRequest>,
|
||||||
|
conflicts: Vec<UpdateConflict>,
|
||||||
|
progress: Option<&crate::feedback::progress::ProgressTaskHandle>,
|
||||||
|
) -> BulkUpdatePlan {
|
||||||
|
let registry = crate::instance::content::provider::ProviderRegistry::configured(
|
||||||
|
crate::net::HttpClient::new(),
|
||||||
|
);
|
||||||
|
plan_bulk_with_registry(
|
||||||
|
®istry,
|
||||||
|
instance,
|
||||||
|
manifest,
|
||||||
|
minecraft_dir,
|
||||||
|
requests,
|
||||||
|
conflicts,
|
||||||
|
progress,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn plan_bulk_with_registry(
|
||||||
|
registry: &super::provider::ProviderRegistry,
|
||||||
|
instance: &InstanceConfig,
|
||||||
|
manifest: &ContentManifest,
|
||||||
|
minecraft_dir: &std::path::Path,
|
||||||
|
mut requests: Vec<UpdateRequest>,
|
||||||
|
mut conflicts: Vec<UpdateConflict>,
|
||||||
|
progress: Option<&crate::feedback::progress::ProgressTaskHandle>,
|
||||||
|
) -> BulkUpdatePlan {
|
||||||
|
loop {
|
||||||
|
let request_count = requests.len();
|
||||||
|
if let Some(progress) = progress
|
||||||
|
&& request_count > 0
|
||||||
|
{
|
||||||
|
progress.set_progress(0, request_count as u64);
|
||||||
|
}
|
||||||
|
let mut completed = 0;
|
||||||
|
let projected_manifest = project_updates(manifest, minecraft_dir, &requests);
|
||||||
|
let mut accepted = Vec::new();
|
||||||
|
let mut survivors = Vec::new();
|
||||||
|
let mut dependency_plan = DependencyPlan {
|
||||||
|
items: Vec::new(),
|
||||||
|
root_count: 0,
|
||||||
|
optional_dependencies: 0,
|
||||||
|
};
|
||||||
|
for request in requests {
|
||||||
|
if let Some(progress) = progress {
|
||||||
|
progress.set_sub_action(format!(
|
||||||
|
"Checking {} ({}/{request_count})",
|
||||||
|
request.title,
|
||||||
|
completed + 1
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let root = InstallRoot {
|
||||||
|
provider: request.update.installed.provider.clone(),
|
||||||
|
project_id: request.update.installed.project_id.clone(),
|
||||||
|
title: request.title.clone(),
|
||||||
|
version: request.update.target.clone(),
|
||||||
|
installed_path: Some(request.installed_path.clone()),
|
||||||
|
kind: request.update.kind,
|
||||||
|
target_world: request.target_world.clone(),
|
||||||
|
force_reinstall: false,
|
||||||
|
};
|
||||||
|
let mut resolution_manifest = projected_manifest.clone();
|
||||||
|
if let Ok(relative_path) = request.installed_path.strip_prefix(minecraft_dir)
|
||||||
|
&& let Some(current) = manifest.record(relative_path)
|
||||||
|
&& let Some(projected) = resolution_manifest
|
||||||
|
.files
|
||||||
|
.iter_mut()
|
||||||
|
.find(|record| record.relative_path == relative_path)
|
||||||
|
{
|
||||||
|
*projected = current.clone();
|
||||||
|
}
|
||||||
|
let mut plan = match super::dependencies::resolve(
|
||||||
|
registry,
|
||||||
|
&resolution_manifest,
|
||||||
|
minecraft_dir,
|
||||||
|
instance,
|
||||||
|
root,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(plan) => plan,
|
||||||
|
Err(error) => {
|
||||||
|
conflicts.push(UpdateConflict {
|
||||||
|
title: request.title,
|
||||||
|
installed_path: request.installed_path,
|
||||||
|
reason: error.to_string(),
|
||||||
|
});
|
||||||
|
completed += 1;
|
||||||
|
if let Some(progress) = progress {
|
||||||
|
progress.set_progress(completed, request_count as u64);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for item in &mut plan.items {
|
||||||
|
item.expected_record = item
|
||||||
|
.installed_path
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|path| path.strip_prefix(minecraft_dir).ok())
|
||||||
|
.and_then(|relative| manifest.record(relative))
|
||||||
|
.cloned();
|
||||||
|
}
|
||||||
|
let mut proposed = accepted.clone();
|
||||||
|
proposed.push(plan.clone());
|
||||||
|
match super::dependencies::merge(proposed) {
|
||||||
|
Ok(merged) => dependency_plan = merged,
|
||||||
|
Err(error) => {
|
||||||
|
conflicts.push(UpdateConflict {
|
||||||
|
title: request.title,
|
||||||
|
installed_path: request.installed_path,
|
||||||
|
reason: error.to_string(),
|
||||||
|
});
|
||||||
|
completed += 1;
|
||||||
|
if let Some(progress) = progress {
|
||||||
|
progress.set_progress(completed, request_count as u64);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
accepted.push(plan);
|
||||||
|
survivors.push(request);
|
||||||
|
completed += 1;
|
||||||
|
if let Some(progress) = progress {
|
||||||
|
progress.set_progress(completed, request_count as u64);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if survivors.len() != request_count {
|
||||||
|
requests = survivors;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let roots = survivors
|
||||||
|
.into_iter()
|
||||||
|
.map(|request| PlannedRootUpdate {
|
||||||
|
current_version: request.update.current.as_ref().map_or_else(
|
||||||
|
|| request.update.installed.version_id.clone(),
|
||||||
|
|version| version.version_number.clone(),
|
||||||
|
),
|
||||||
|
title: request.title,
|
||||||
|
installed_path: request.installed_path,
|
||||||
|
target: request.update.target,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
return BulkUpdatePlan {
|
||||||
|
dependency_plan,
|
||||||
|
roots,
|
||||||
|
conflicts,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn project_updates(
|
||||||
|
manifest: &ContentManifest,
|
||||||
|
minecraft_dir: &std::path::Path,
|
||||||
|
requests: &[UpdateRequest],
|
||||||
|
) -> ContentManifest {
|
||||||
|
let mut projected = manifest.clone();
|
||||||
|
for request in requests {
|
||||||
|
let Ok(relative_path) = request.installed_path.strip_prefix(minecraft_dir) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(record) = projected
|
||||||
|
.files
|
||||||
|
.iter_mut()
|
||||||
|
.find(|record| record.relative_path == relative_path)
|
||||||
|
else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
record.resolution = crate::instance::Resolution::Resolved {
|
||||||
|
project: ProviderProject {
|
||||||
|
provider: request.update.installed.provider.clone(),
|
||||||
|
project_id: request.update.installed.project_id.clone(),
|
||||||
|
version_id: request.update.target.id.clone(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
record.provider_aliases.clear();
|
||||||
|
}
|
||||||
|
projected
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::net::modrinth::{VersionFile, VersionType};
|
||||||
|
|
||||||
|
fn version(id: &str) -> VersionInfo {
|
||||||
|
VersionInfo {
|
||||||
|
id: id.to_owned(),
|
||||||
|
project_id: "project".to_owned(),
|
||||||
|
name: id.to_owned(),
|
||||||
|
version_number: id.to_owned(),
|
||||||
|
game_versions: vec!["1.21.1".to_owned()],
|
||||||
|
loaders: vec!["fabric".to_owned()],
|
||||||
|
version_type: VersionType::Release,
|
||||||
|
dependencies: Vec::new(),
|
||||||
|
date_published: String::new(),
|
||||||
|
files: Vec::<VersionFile>::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cached_updates_match_the_exact_installed_version() {
|
||||||
|
let installed = ProviderProject {
|
||||||
|
provider: "modrinth".to_owned(),
|
||||||
|
project_id: "project".to_owned(),
|
||||||
|
version_id: "old".to_owned(),
|
||||||
|
};
|
||||||
|
let snapshot = UpdateSnapshot {
|
||||||
|
game_version: "1.21.1".to_owned(),
|
||||||
|
loader: ModLoader::Fabric,
|
||||||
|
inventory: vec![installed.clone()],
|
||||||
|
checked_at: chrono::Utc::now().timestamp(),
|
||||||
|
updates: vec![AvailableUpdate {
|
||||||
|
installed: installed.clone(),
|
||||||
|
current: Some(version("old")),
|
||||||
|
target: version("new"),
|
||||||
|
kind: ContentKind::Mod,
|
||||||
|
}],
|
||||||
|
failures: Vec::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(snapshot.update_for(&installed).is_some());
|
||||||
|
assert!(
|
||||||
|
snapshot
|
||||||
|
.update_for(&ProviderProject {
|
||||||
|
version_id: "different".to_owned(),
|
||||||
|
..installed
|
||||||
|
})
|
||||||
|
.is_none()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_changed_content_inventory_only_schedules_a_rescan() {
|
||||||
|
let project = ProviderProject {
|
||||||
|
provider: "modrinth".to_owned(),
|
||||||
|
project_id: "project".to_owned(),
|
||||||
|
version_id: "old".to_owned(),
|
||||||
|
};
|
||||||
|
let snapshot = UpdateSnapshot {
|
||||||
|
game_version: "1.21.1".to_owned(),
|
||||||
|
loader: ModLoader::Fabric,
|
||||||
|
inventory: vec![project.clone()],
|
||||||
|
checked_at: chrono::Utc::now().timestamp(),
|
||||||
|
updates: Vec::new(),
|
||||||
|
failures: Vec::new(),
|
||||||
|
};
|
||||||
|
let mut manifest = ContentManifest::default();
|
||||||
|
manifest.files.push(crate::instance::ContentFileRecord {
|
||||||
|
relative_path: "mods/example.jar".into(),
|
||||||
|
kind: ContentKind::Mod,
|
||||||
|
enabled: true,
|
||||||
|
fingerprint: crate::instance::FileFingerprint {
|
||||||
|
size: 0,
|
||||||
|
modified_ns: 0,
|
||||||
|
hashes: Default::default(),
|
||||||
|
},
|
||||||
|
resolution: crate::instance::Resolution::Resolved { project },
|
||||||
|
provider_aliases: Vec::new(),
|
||||||
|
provider_checks: vec!["modrinth".to_owned()],
|
||||||
|
required_dependencies: Vec::new(),
|
||||||
|
automatic_dependency: false,
|
||||||
|
cleanup_eligible: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert!(!snapshot.is_stale(&manifest));
|
||||||
|
manifest.files[0].resolution = crate::instance::Resolution::Unmatched {
|
||||||
|
checked_at: 0,
|
||||||
|
providers: Vec::new(),
|
||||||
|
};
|
||||||
|
assert!(snapshot.is_stale(&manifest));
|
||||||
|
|
||||||
|
let expired = UpdateSnapshot {
|
||||||
|
checked_at: chrono::Utc::now().timestamp() - RECHECK_AFTER_SECONDS,
|
||||||
|
..snapshot
|
||||||
|
};
|
||||||
|
assert!(expired.is_stale(&manifest));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bulk_planning_projects_other_selected_updates() {
|
||||||
|
let minecraft = std::path::Path::new("/instance/minecraft");
|
||||||
|
let installed = ProviderProject {
|
||||||
|
provider: "modrinth".to_owned(),
|
||||||
|
project_id: "library".to_owned(),
|
||||||
|
version_id: "old".to_owned(),
|
||||||
|
};
|
||||||
|
let mut manifest = ContentManifest::default();
|
||||||
|
manifest.files.push(crate::instance::ContentFileRecord {
|
||||||
|
relative_path: "mods/library.jar".into(),
|
||||||
|
kind: ContentKind::Mod,
|
||||||
|
enabled: true,
|
||||||
|
fingerprint: crate::instance::FileFingerprint {
|
||||||
|
size: 1,
|
||||||
|
modified_ns: 1,
|
||||||
|
hashes: Default::default(),
|
||||||
|
},
|
||||||
|
resolution: crate::instance::Resolution::Resolved {
|
||||||
|
project: installed.clone(),
|
||||||
|
},
|
||||||
|
provider_aliases: Vec::new(),
|
||||||
|
provider_checks: vec!["modrinth".to_owned()],
|
||||||
|
required_dependencies: Vec::new(),
|
||||||
|
automatic_dependency: true,
|
||||||
|
cleanup_eligible: true,
|
||||||
|
});
|
||||||
|
let requests = vec![UpdateRequest {
|
||||||
|
title: "Library".to_owned(),
|
||||||
|
installed_path: minecraft.join("mods/library.jar"),
|
||||||
|
target_world: None,
|
||||||
|
update: AvailableUpdate {
|
||||||
|
installed,
|
||||||
|
current: Some(version("old")),
|
||||||
|
target: version("new"),
|
||||||
|
kind: ContentKind::Mod,
|
||||||
|
},
|
||||||
|
}];
|
||||||
|
|
||||||
|
let projected = project_updates(&manifest, minecraft, &requests);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
projected.files[0].resolved_project().unwrap().version_id,
|
||||||
|
"new"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
manifest.files[0].resolved_project().unwrap().version_id,
|
||||||
|
"old"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+157
-126
@@ -1,15 +1,90 @@
|
|||||||
// world save scanning. worlds are always directories (never zips) and store
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
// their icon as icon.png. also computes an approximate size from top-level
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
// files + region data so the user gets some sense of how chonky their world is.
|
|
||||||
|
|
||||||
use std::path::Path;
|
use std::{fs::File, path::Path};
|
||||||
|
|
||||||
use super::mods::{make_icon_pixels, ContentEntry};
|
use flate2::read::GzDecoder;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use super::entry::{ContentEntry, WorldDetails, WorldGameMode};
|
||||||
|
use super::{fallback_icon_large, make_icon_pixels};
|
||||||
|
|
||||||
|
pub fn scan_one_world(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
|
||||||
|
let icon_bytes = File::open(path.join("icon.png"))
|
||||||
|
.ok()
|
||||||
|
.and_then(super::read_local_metadata);
|
||||||
|
let icon_lines = icon_bytes
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|bytes| make_icon_pixels(bytes, 12, 6))
|
||||||
|
.or_else(|| Some(fallback_icon_large()));
|
||||||
|
|
||||||
|
let metadata = read_world_metadata(path);
|
||||||
|
let last_played = world_last_played(path, metadata.as_ref());
|
||||||
|
let size = dir_size_approx(path);
|
||||||
|
let world_details = WorldDetails {
|
||||||
|
game_mode: metadata.as_ref().and_then(WorldMetadata::game_mode),
|
||||||
|
last_played,
|
||||||
|
minecraft_version: metadata
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|metadata| metadata.version.as_ref())
|
||||||
|
.and_then(|version| version.name.as_deref())
|
||||||
|
.filter(|version| !version.trim().is_empty())
|
||||||
|
.map(str::to_owned),
|
||||||
|
size: (size > 0).then(|| format_size(size)),
|
||||||
|
datapacks: datapack_names(path),
|
||||||
|
};
|
||||||
|
|
||||||
|
ContentEntry {
|
||||||
|
name: metadata
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|metadata| metadata.level_name.as_deref())
|
||||||
|
.filter(|name| !name.trim().is_empty())
|
||||||
|
.unwrap_or(file_stem)
|
||||||
|
.to_owned(),
|
||||||
|
file_stem: file_stem.to_owned(),
|
||||||
|
source_slug: None,
|
||||||
|
installed_path: None,
|
||||||
|
provider_project: None,
|
||||||
|
world_details: Some(world_details),
|
||||||
|
title_suffix: None,
|
||||||
|
footer_label: None,
|
||||||
|
footer_change: None,
|
||||||
|
description: String::new(),
|
||||||
|
enabled,
|
||||||
|
icon_bytes,
|
||||||
|
provider_icon: false,
|
||||||
|
provider_description: false,
|
||||||
|
path: path.to_path_buf(),
|
||||||
|
icon_lines,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn datapack_names(world: &Path) -> Vec<String> {
|
||||||
|
let Ok(entries) = std::fs::read_dir(world.join("datapacks")) else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let mut names = entries
|
||||||
|
.flatten()
|
||||||
|
.filter_map(|entry| {
|
||||||
|
let path = entry.path();
|
||||||
|
let name = path.file_name()?.to_str()?;
|
||||||
|
if path.is_dir() {
|
||||||
|
Some(name.trim_end_matches(".disabled").to_owned())
|
||||||
|
} else {
|
||||||
|
name.strip_suffix(".zip")
|
||||||
|
.or_else(|| name.strip_suffix(".zip.disabled"))
|
||||||
|
.map(str::to_owned)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
names.sort_by_key(|name| name.to_lowercase());
|
||||||
|
names
|
||||||
|
}
|
||||||
|
|
||||||
pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntry> {
|
||||||
let saves_dir = instances_dir
|
let saves_dir = instances_dir
|
||||||
.join(instance_name)
|
.join(instance_name)
|
||||||
.join(".minecraft")
|
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||||
.join("saves");
|
.join("saves");
|
||||||
|
|
||||||
let read_dir = match std::fs::read_dir(&saves_dir) {
|
let read_dir = match std::fs::read_dir(&saves_dir) {
|
||||||
@@ -31,65 +106,88 @@ 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());
|
||||||
entries
|
entries
|
||||||
}
|
}
|
||||||
|
|
||||||
fn world_description(world_dir: &Path) -> String {
|
#[derive(Debug, Deserialize)]
|
||||||
let level_dat = world_dir.join("level.dat");
|
struct LevelDat {
|
||||||
|
#[serde(rename = "Data")]
|
||||||
|
data: WorldMetadata,
|
||||||
|
}
|
||||||
|
|
||||||
let created = world_dir
|
#[derive(Debug, Deserialize)]
|
||||||
.metadata()
|
struct WorldMetadata {
|
||||||
.ok()
|
#[serde(rename = "LevelName")]
|
||||||
.and_then(|m| m.created().ok().or_else(|| m.modified().ok()))
|
level_name: Option<String>,
|
||||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
#[serde(rename = "GameType")]
|
||||||
.map(|d| d.as_secs());
|
game_type: Option<i32>,
|
||||||
|
#[serde(rename = "hardcore")]
|
||||||
|
hardcore: Option<i8>,
|
||||||
|
#[serde(rename = "LastPlayed")]
|
||||||
|
last_played: Option<i64>,
|
||||||
|
#[serde(rename = "Version")]
|
||||||
|
version: Option<WorldVersion>,
|
||||||
|
}
|
||||||
|
|
||||||
let modified = level_dat
|
#[derive(Debug, Deserialize)]
|
||||||
.metadata()
|
struct WorldVersion {
|
||||||
.ok()
|
#[serde(rename = "Name")]
|
||||||
.and_then(|m| m.modified().ok())
|
name: Option<String>,
|
||||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
}
|
||||||
.map(|d| d.as_secs());
|
|
||||||
|
|
||||||
let dir_size = dir_size_approx(world_dir);
|
impl WorldMetadata {
|
||||||
|
fn game_mode(&self) -> Option<WorldGameMode> {
|
||||||
let mut lines = Vec::new();
|
if self.hardcore.is_some_and(|hardcore| hardcore != 0) {
|
||||||
|
return Some(WorldGameMode::Hardcore);
|
||||||
if let Some(secs) = created
|
|
||||||
&& let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0) {
|
|
||||||
lines.push(format!("Created: {}", dt.format("%Y-%m-%d %H:%M")));
|
|
||||||
}
|
}
|
||||||
|
Some(match self.game_type? {
|
||||||
if let Some(secs) = modified
|
0 => WorldGameMode::Survival,
|
||||||
&& let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0) {
|
1 => WorldGameMode::Creative,
|
||||||
lines.push(format!("Played: {}", dt.format("%Y-%m-%d %H:%M")));
|
2 => WorldGameMode::Adventure,
|
||||||
}
|
3 => WorldGameMode::Spectator,
|
||||||
|
_ => return None,
|
||||||
if dir_size > 0 {
|
})
|
||||||
lines.push(format!("Size: {}", format_size(dir_size)));
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
lines.join("\n")
|
fn read_world_metadata(world_dir: &Path) -> Option<WorldMetadata> {
|
||||||
|
let path = world_dir.join("level.dat");
|
||||||
|
let file = File::open(&path).ok()?;
|
||||||
|
let bytes = super::read_local_metadata(GzDecoder::new(file))?;
|
||||||
|
match fastnbt::from_bytes::<LevelDat>(&bytes) {
|
||||||
|
Ok(level) => Some(level.data),
|
||||||
|
Err(error) => {
|
||||||
|
tracing::debug!(
|
||||||
|
"Could not read world metadata from {}: {error}",
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn world_last_played(
|
||||||
|
world_dir: &Path,
|
||||||
|
metadata: Option<&WorldMetadata>,
|
||||||
|
) -> Option<chrono::DateTime<chrono::Utc>> {
|
||||||
|
let level_dat = world_dir.join("level.dat");
|
||||||
|
metadata
|
||||||
|
.and_then(|metadata| metadata.last_played)
|
||||||
|
.filter(|millis| *millis > 0)
|
||||||
|
.map(|millis| millis / 1000)
|
||||||
|
.or_else(|| {
|
||||||
|
level_dat
|
||||||
|
.metadata()
|
||||||
|
.ok()
|
||||||
|
.and_then(|m| m.modified().ok())
|
||||||
|
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||||
|
.map(|d| d.as_secs() as i64)
|
||||||
|
})
|
||||||
|
.and_then(|seconds| chrono::DateTime::from_timestamp(seconds, 0))
|
||||||
}
|
}
|
||||||
|
|
||||||
// only counts top-level files + region/ contents, not a full recursive walk.
|
// only counts top-level files + region/ contents, not a full recursive walk.
|
||||||
@@ -99,12 +197,12 @@ 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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Check region folder too (main chunk data)
|
|
||||||
let region = path.join("region");
|
let region = path.join("region");
|
||||||
if let Ok(rd) = std::fs::read_dir(region) {
|
if let Ok(rd) = std::fs::read_dir(region) {
|
||||||
for entry in rd.flatten() {
|
for entry in rd.flatten() {
|
||||||
@@ -129,72 +227,5 @@ fn format_size(bytes: u64) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "../tests/content/worlds.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
fn setup_saves_dir(tmp: &Path, instance: &str) -> std::path::PathBuf {
|
|
||||||
let dir = tmp.join(instance).join(".minecraft").join("saves");
|
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
|
||||||
dir
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_worlds_empty_dir() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
setup_saves_dir(tmp.path(), "inst");
|
|
||||||
let worlds = scan_worlds(tmp.path(), "inst");
|
|
||||||
assert!(worlds.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_worlds_missing_dir_returns_empty() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let worlds = scan_worlds(tmp.path(), "ghost");
|
|
||||||
assert!(worlds.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_worlds_finds_directories() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_saves_dir(tmp.path(), "inst");
|
|
||||||
std::fs::create_dir(dir.join("My World")).unwrap();
|
|
||||||
std::fs::create_dir(dir.join("Creative")).unwrap();
|
|
||||||
let worlds = scan_worlds(tmp.path(), "inst");
|
|
||||||
assert_eq!(worlds.len(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_worlds_ignores_files() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_saves_dir(tmp.path(), "inst");
|
|
||||||
std::fs::create_dir(dir.join("World1")).unwrap();
|
|
||||||
std::fs::write(dir.join("stray-file.txt"), "not a world").unwrap();
|
|
||||||
let worlds = scan_worlds(tmp.path(), "inst");
|
|
||||||
assert_eq!(worlds.len(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_worlds_disabled_world() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_saves_dir(tmp.path(), "inst");
|
|
||||||
std::fs::create_dir(dir.join("ActiveWorld")).unwrap();
|
|
||||||
std::fs::create_dir(dir.join("HiddenWorld.disabled")).unwrap();
|
|
||||||
let worlds = scan_worlds(tmp.path(), "inst");
|
|
||||||
let active = worlds.iter().find(|w| w.file_stem == "ActiveWorld").unwrap();
|
|
||||||
let hidden = worlds.iter().find(|w| w.file_stem == "HiddenWorld").unwrap();
|
|
||||||
assert!(active.enabled);
|
|
||||||
assert!(!hidden.enabled);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn scan_worlds_sorted_case_insensitive() {
|
|
||||||
let tmp = tempfile::tempdir().unwrap();
|
|
||||||
let dir = setup_saves_dir(tmp.path(), "inst");
|
|
||||||
std::fs::create_dir(dir.join("Zeta")).unwrap();
|
|
||||||
std::fs::create_dir(dir.join("alpha")).unwrap();
|
|
||||||
std::fs::create_dir(dir.join("Beta")).unwrap();
|
|
||||||
let worlds = scan_worlds(tmp.path(), "inst");
|
|
||||||
let names: Vec<&str> = worlds.iter().map(|w| w.name.as_str()).collect();
|
|
||||||
assert_eq!(names, vec!["alpha", "Beta", "Zeta"]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+285
-84
@@ -1,5 +1,5 @@
|
|||||||
// creates OS-native shortcuts for launching instances directly:
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
// .desktop files on linux, .bat on windows, .command on macos
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
@@ -8,19 +8,19 @@ use crate::instance::models::InstanceConfig;
|
|||||||
const ICON_BYTES: &[u8] = include_bytes!("../../assets/icon.svg");
|
const ICON_BYTES: &[u8] = include_bytes!("../../assets/icon.svg");
|
||||||
|
|
||||||
pub fn desktop_path(name: &str) -> Option<PathBuf> {
|
pub fn desktop_path(name: &str) -> Option<PathBuf> {
|
||||||
let sanitized = sanitize(name);
|
let sanitized = shortcut_name(name);
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
{
|
{
|
||||||
dirs_next::data_dir().map(|d| {
|
dirs::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,13 +36,12 @@ 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::data_dir().map(|d| d.join("rmcl").join("icon.svg"))
|
||||||
}
|
}
|
||||||
|
|
||||||
// lazily writes the bundled svg icon to disk the first time a shortcut needs it
|
|
||||||
fn ensure_icon() -> Option<PathBuf> {
|
fn ensure_icon() -> Option<PathBuf> {
|
||||||
let path = icon_path()?;
|
let path = icon_path()?;
|
||||||
if path.exists() {
|
if std::fs::read(&path).ok().as_deref() == Some(ICON_BYTES) {
|
||||||
return Some(path);
|
return Some(path);
|
||||||
}
|
}
|
||||||
let parent = path.parent()?;
|
let parent = path.parent()?;
|
||||||
@@ -50,28 +49,146 @@ fn ensure_icon() -> Option<PathBuf> {
|
|||||||
tracing::warn!("Failed to create icon directory: {}", e);
|
tracing::warn!("Failed to create icon directory: {}", e);
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
if let Err(e) = std::fs::write(&path, ICON_BYTES) {
|
if let Err(e) = crate::storage::write_atomic(&path, ICON_BYTES) {
|
||||||
tracing::warn!("Failed to write bundled icon: {}", e);
|
tracing::warn!("Failed to write bundled icon: {}", e);
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
Some(path)
|
Some(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn shortcut_name(name: &str) -> String {
|
||||||
|
let mut encoded = String::new();
|
||||||
|
for character in name.chars() {
|
||||||
|
if character.is_alphanumeric() || matches!(character, '-' | '_') {
|
||||||
|
encoded.push(character);
|
||||||
|
} else {
|
||||||
|
for byte in character.to_string().bytes() {
|
||||||
|
encoded.push_str(&format!("%{byte:02X}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
encoded
|
||||||
|
}
|
||||||
|
|
||||||
|
fn legacy_path(name: &str) -> Option<PathBuf> {
|
||||||
|
let legacy = desktop_path(&sanitize(name))?;
|
||||||
|
(Some(&legacy) != desktop_path(name).as_ref()).then_some(legacy)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn owns_legacy_shortcut(path: &Path, name: &str) -> bool {
|
||||||
|
let Ok(existing) = read_shortcut(path) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let marker = shortcut_marker(name);
|
||||||
|
if existing.lines().any(|line| line == marker) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
let commands = {
|
||||||
|
let quoted = quote_desktop_exec_arg(name);
|
||||||
|
[
|
||||||
|
format!("Exec=rmcl instance launch {quoted}"),
|
||||||
|
format!(
|
||||||
|
"Exec=rmcl instance launch {}",
|
||||||
|
quoted.replace("\\\\", "\\").replace("%%", "%")
|
||||||
|
),
|
||||||
|
]
|
||||||
|
};
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
let commands = {
|
||||||
|
let command =
|
||||||
|
format!("rmcl instance launch {}", quote_windows_arg(name)).replace('"', "\"\"");
|
||||||
|
[format!("shell.Run \"{command}\", 0, False")]
|
||||||
|
};
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
let commands = [format!("rmcl instance launch {}", quote_shell_arg(name))];
|
||||||
|
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
|
||||||
|
let commands: [String; 0] = [];
|
||||||
|
existing
|
||||||
|
.lines()
|
||||||
|
.any(|line| commands.iter().any(|command| line == command))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_shortcut(path: &Path) -> std::io::Result<String> {
|
||||||
|
let bytes = std::fs::read(path)?;
|
||||||
|
if let Some(bytes) = bytes.strip_prefix(&[0xff, 0xfe]) {
|
||||||
|
if bytes.len() % 2 != 0 {
|
||||||
|
return Err(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::InvalidData,
|
||||||
|
"Invalid UTF-16 shortcut",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let units = bytes
|
||||||
|
.as_chunks::<2>()
|
||||||
|
.0
|
||||||
|
.iter()
|
||||||
|
.map(|pair| u16::from_le_bytes([pair[0], pair[1]]))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
String::from_utf16(&units)
|
||||||
|
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
|
||||||
|
} else {
|
||||||
|
String::from_utf8(bytes)
|
||||||
|
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(windows, test))]
|
||||||
|
fn windows_script_bytes(content: &str) -> Vec<u8> {
|
||||||
|
// Windows Script Host reads Unicode scripts as BOM-prefixed UTF-16, not UTF-8.
|
||||||
|
[0xfeff]
|
||||||
|
.into_iter()
|
||||||
|
.chain(content.encode_utf16())
|
||||||
|
.flat_map(u16::to_le_bytes)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn shortcut_marker(name: &str) -> String {
|
||||||
|
let prefix = if cfg!(windows) { "'" } else { "#" };
|
||||||
|
format!("{prefix} rmcl-instance: {}", shortcut_name(name))
|
||||||
|
}
|
||||||
pub fn exists(name: &str) -> bool {
|
pub fn exists(name: &str) -> bool {
|
||||||
desktop_path(name).map(|p| p.exists()).unwrap_or(false)
|
desktop_path(name).is_some_and(|path| owns_legacy_shortcut(&path, name))
|
||||||
|
|| legacy_path(name).is_some_and(|path| owns_legacy_shortcut(&path, name))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create(config: &InstanceConfig) -> std::io::Result<PathBuf> {
|
pub fn create(config: &InstanceConfig) -> std::io::Result<PathBuf> {
|
||||||
|
crate::instance::manager::validate_name(&config.name).map_err(std::io::Error::other)?;
|
||||||
let path = desktop_path(&config.name)
|
let path = desktop_path(&config.name)
|
||||||
.ok_or_else(|| std::io::Error::other("cannot resolve shortcut directory"))?;
|
.ok_or_else(|| std::io::Error::other("cannot resolve shortcut directory"))?;
|
||||||
|
|
||||||
|
match std::fs::symlink_metadata(&path) {
|
||||||
|
Ok(_) if !owns_legacy_shortcut(&path, &config.name) => {
|
||||||
|
return Err(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::AlreadyExists,
|
||||||
|
format!("Another shortcut already exists at '{}'", path.display()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Err(error) if error.kind() != std::io::ErrorKind::NotFound => return Err(error),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(parent) = path.parent() {
|
if let Some(parent) = path.parent() {
|
||||||
std::fs::create_dir_all(parent)?;
|
std::fs::create_dir_all(parent)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let icon = ensure_icon();
|
let icon = ensure_icon();
|
||||||
let content = build_content(&config.name, icon.as_deref());
|
let executable = std::env::current_exe()?;
|
||||||
std::fs::write(&path, content)?;
|
let executable = executable.to_str().ok_or_else(|| {
|
||||||
|
std::io::Error::new(
|
||||||
|
std::io::ErrorKind::InvalidData,
|
||||||
|
"Launcher executable path is not UTF-8",
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let content = build_content(&config.name, icon.as_deref(), executable);
|
||||||
|
if read_shortcut(&path).ok().as_deref() != Some(content.as_str()) {
|
||||||
|
#[cfg(windows)]
|
||||||
|
let encoded = windows_script_bytes(&content);
|
||||||
|
#[cfg(windows)]
|
||||||
|
let bytes = encoded.as_slice();
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
let bytes = content.as_bytes();
|
||||||
|
crate::storage::write_atomic(&path, bytes)?;
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
{
|
{
|
||||||
@@ -80,6 +197,12 @@ pub fn create(config: &InstanceConfig) -> std::io::Result<PathBuf> {
|
|||||||
std::fs::set_permissions(&path, perms)?;
|
std::fs::set_permissions(&path, perms)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(legacy) = legacy_path(&config.name)
|
||||||
|
&& owns_legacy_shortcut(&legacy, &config.name)
|
||||||
|
{
|
||||||
|
std::fs::remove_file(legacy)?;
|
||||||
|
}
|
||||||
|
|
||||||
Ok(path)
|
Ok(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,94 +210,211 @@ pub fn remove(name: &str) -> std::io::Result<()> {
|
|||||||
let Some(path) = desktop_path(name) else {
|
let Some(path) = desktop_path(name) else {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
if path.exists() {
|
if owns_legacy_shortcut(&path, name) {
|
||||||
std::fs::remove_file(path)?;
|
std::fs::remove_file(path)?;
|
||||||
}
|
}
|
||||||
|
if let Some(legacy) = legacy_path(name)
|
||||||
|
&& owns_legacy_shortcut(&legacy, name)
|
||||||
|
{
|
||||||
|
std::fs::remove_file(legacy)?;
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn toggle(config: &InstanceConfig) -> std::io::Result<bool> {
|
pub fn set_enabled(config: &InstanceConfig, enabled: bool) -> std::io::Result<()> {
|
||||||
if exists(&config.name) {
|
if enabled {
|
||||||
remove(&config.name)?;
|
create(config).map(|_| ())
|
||||||
Ok(false)
|
|
||||||
} else {
|
} else {
|
||||||
create(config)?;
|
remove(&config.name)
|
||||||
Ok(true)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn toggle(config: &InstanceConfig) -> std::io::Result<bool> {
|
||||||
|
let enabled = !exists(&config.name);
|
||||||
|
set_enabled(config, enabled)?;
|
||||||
|
Ok(enabled)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn rename(old_name: &str, new_config: &InstanceConfig) -> std::io::Result<()> {
|
pub fn rename(old_name: &str, new_config: &InstanceConfig) -> std::io::Result<()> {
|
||||||
if !exists(old_name) {
|
if !exists(old_name) {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
remove(old_name)?;
|
let same_path = desktop_path(old_name) == desktop_path(&new_config.name);
|
||||||
|
if !same_path && let Some(new_path) = desktop_path(&new_config.name) {
|
||||||
|
for old_path in [desktop_path(old_name), legacy_path(old_name)]
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
{
|
||||||
|
if rename_shortcut_alias(&old_path, &new_path, old_name, || {
|
||||||
|
create(new_config).map(|_| ())
|
||||||
|
})? {
|
||||||
|
remove(old_name)?;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
create(new_config)?;
|
create(new_config)?;
|
||||||
|
if !same_path {
|
||||||
|
remove(old_name)?;
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_content(name: &str, icon: Option<&Path>) -> String {
|
fn rename_shortcut_alias(
|
||||||
|
old_path: &Path,
|
||||||
|
new_path: &Path,
|
||||||
|
old_name: &str,
|
||||||
|
create: impl FnOnce() -> std::io::Result<()>,
|
||||||
|
) -> std::io::Result<bool> {
|
||||||
|
if old_path == new_path
|
||||||
|
|| !owns_legacy_shortcut(old_path, old_name)
|
||||||
|
|| !crate::instance::manager::paths_alias(old_path, new_path)?
|
||||||
|
{
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
let temporary = tempfile::Builder::new()
|
||||||
|
.prefix(".rmcl-shortcut-")
|
||||||
|
.tempdir_in(
|
||||||
|
old_path
|
||||||
|
.parent()
|
||||||
|
.ok_or_else(|| std::io::Error::other("Shortcut has no parent"))?,
|
||||||
|
)?;
|
||||||
|
let original = temporary.path().join("original");
|
||||||
|
std::fs::rename(old_path, &original)?;
|
||||||
|
if let Err(error) = create() {
|
||||||
|
if let Err(rollback) = std::fs::rename(&original, old_path) {
|
||||||
|
let retained = temporary.keep();
|
||||||
|
return Err(std::io::Error::other(format!(
|
||||||
|
"Could not update shortcut: {error}; rollback failed: {rollback}; original retained at '{}'",
|
||||||
|
retained.join("original").display(),
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_content(name: &str, icon: Option<&Path>, executable: &str) -> String {
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
{
|
{
|
||||||
build_linux_desktop(name, icon)
|
build_linux_desktop(name, icon, executable)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
{
|
{
|
||||||
let _ = icon;
|
let _ = icon;
|
||||||
build_windows_shortcut(name)
|
build_windows_shortcut(name, executable)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
{
|
{
|
||||||
let _ = icon;
|
let _ = icon;
|
||||||
build_macos_command(name)
|
build_macos_command(name, executable)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
|
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
|
||||||
{
|
{
|
||||||
let _ = (name, icon);
|
let _ = (name, icon, executable);
|
||||||
String::new()
|
String::new()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(any(target_os = "linux", test))]
|
||||||
fn build_linux_desktop(name: &str, icon: Option<&Path>) -> String {
|
fn build_linux_desktop(name: &str, icon: Option<&Path>, executable: &str) -> 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=1.0\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!("# rmcl-instance: {}\n", shortcut_name(name)));
|
||||||
|
out.push_str(&format!(
|
||||||
|
"Exec={} instance launch {}\n",
|
||||||
|
quote_desktop_exec_arg(executable),
|
||||||
|
quote_desktop_exec_arg(name)
|
||||||
|
));
|
||||||
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(any(target_os = "windows", test))]
|
||||||
fn build_windows_shortcut(name: &str) -> String {
|
fn build_windows_shortcut(name: &str, executable: &str) -> String {
|
||||||
let mut out = String::new();
|
let arguments = format!("instance launch {}", quote_windows_arg(name));
|
||||||
out.push_str("@echo off\r\n");
|
let mut out = format!("' rmcl-instance: {}\r\n", shortcut_name(name));
|
||||||
out.push_str(&format!("title Minecraft - {name}\r\n"));
|
out.push_str(&windows_shell_execute(executable, &arguments));
|
||||||
out.push_str(&format!("mcl instance launch \"{name}\"\r\n"));
|
|
||||||
out.push_str("pause\r\n");
|
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(any(target_os = "windows", test))]
|
||||||
fn build_macos_command(name: &str) -> String {
|
fn windows_shell_execute(executable: &str, arguments: &str) -> String {
|
||||||
|
// ShellExecute passes parameters literally; WScript.Shell.Run expands %VAR% in them.
|
||||||
|
format!(
|
||||||
|
"Set shell = CreateObject(\"Shell.Application\")\r\nshell.ShellExecute \"{}\", \"{}\", \"\", \"open\", 0\r\n",
|
||||||
|
executable.replace('"', "\"\""),
|
||||||
|
arguments.replace('"', "\"\"")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(target_os = "macos", test))]
|
||||||
|
fn build_macos_command(name: &str, executable: &str) -> String {
|
||||||
let mut out = String::new();
|
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!("# rmcl-instance: {}\n", shortcut_name(name)));
|
||||||
out.push_str(&format!("mcl instance launch \"{name}\"\n"));
|
out.push_str(&format!(
|
||||||
|
"{} instance launch {}\n",
|
||||||
|
quote_shell_arg(executable),
|
||||||
|
quote_shell_arg(name)
|
||||||
|
));
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
// replaces anything that isn't alphanumeric, dash, or underscore with _
|
#[cfg(any(target_os = "linux", test))]
|
||||||
fn sanitize(name: &str) -> String {
|
fn quote_desktop_exec_arg(value: &str) -> String {
|
||||||
|
let mut escaped = String::with_capacity(value.len() + 2);
|
||||||
|
escaped.push('"');
|
||||||
|
for character in value.chars() {
|
||||||
|
if matches!(character, '"' | '`' | '$' | '\\') {
|
||||||
|
escaped.push('\\');
|
||||||
|
}
|
||||||
|
escaped.push(character);
|
||||||
|
}
|
||||||
|
escaped.push('"');
|
||||||
|
escaped.replace('\\', "\\\\").replace('%', "%%")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(target_os = "macos", test))]
|
||||||
|
fn quote_shell_arg(value: &str) -> String {
|
||||||
|
format!("'{}'", value.replace('\'', "'\\''"))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(target_os = "windows", test))]
|
||||||
|
fn quote_windows_arg(value: &str) -> String {
|
||||||
|
let mut quoted = String::with_capacity(value.len() + 2);
|
||||||
|
quoted.push('"');
|
||||||
|
let mut backslashes = 0;
|
||||||
|
for character in value.chars() {
|
||||||
|
if character == '\\' {
|
||||||
|
backslashes += 1;
|
||||||
|
} else if character == '"' {
|
||||||
|
quoted.extend(std::iter::repeat_n('\\', backslashes * 2 + 1));
|
||||||
|
quoted.push('"');
|
||||||
|
backslashes = 0;
|
||||||
|
} else {
|
||||||
|
quoted.extend(std::iter::repeat_n('\\', backslashes));
|
||||||
|
quoted.push(character);
|
||||||
|
backslashes = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
quoted.extend(std::iter::repeat_n('\\', backslashes * 2));
|
||||||
|
quoted.push('"');
|
||||||
|
quoted
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn sanitize(name: &str) -> String {
|
||||||
name.chars()
|
name.chars()
|
||||||
.map(|c| {
|
.map(|c| {
|
||||||
if c.is_alphanumeric() || c == '-' || c == '_' {
|
if c.is_alphanumeric() || c == '-' || c == '_' {
|
||||||
@@ -187,44 +427,5 @@ fn sanitize(name: &str) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
#[path = "tests/desktop.rs"]
|
||||||
use super::*;
|
mod tests;
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn sanitize_keeps_alphanumeric() {
|
|
||||||
assert_eq!(sanitize("my-instance_123"), "my-instance_123");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn sanitize_replaces_special_chars() {
|
|
||||||
assert_eq!(sanitize("my instance!"), "my_instance_");
|
|
||||||
assert_eq!(sanitize("path/traversal"), "path_traversal");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn desktop_path_returns_some() {
|
|
||||||
let path = desktop_path("TestPack");
|
|
||||||
if let Some(p) = path {
|
|
||||||
let name = p.file_name().unwrap().to_str().unwrap();
|
|
||||||
assert!(name.contains("TestPack"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
fn build_content_linux() {
|
|
||||||
let content = build_content("TestPack", None);
|
|
||||||
assert!(content.contains("Name=Minecraft - TestPack"));
|
|
||||||
assert!(content.contains("Exec=mcl instance launch \"TestPack\""));
|
|
||||||
assert!(content.contains("Terminal=true"));
|
|
||||||
assert!(content.contains("Categories=Game;"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
fn build_content_linux_with_icon() {
|
|
||||||
let icon = PathBuf::from("/tmp/icon.png");
|
|
||||||
let content = build_content("TestPack", Some(&icon));
|
|
||||||
assert!(content.contains("Icon=/tmp/icon.png"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
collections::BTreeSet,
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub(crate) struct GlfwInstallation {
|
||||||
|
pub path: PathBuf,
|
||||||
|
pub version: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn bundled_glfw_version(meta_dir: &Path, game_version: &str) -> Option<String> {
|
||||||
|
let path = crate::storage::MetadataPaths::new(meta_dir)
|
||||||
|
.versions()
|
||||||
|
.join(game_version)
|
||||||
|
.join("meta.json");
|
||||||
|
let profile: serde_json::Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
|
||||||
|
profile
|
||||||
|
.get("libraries")?
|
||||||
|
.as_array()?
|
||||||
|
.iter()
|
||||||
|
.filter_map(|library| library.get("name")?.as_str())
|
||||||
|
.find_map(|coordinate| {
|
||||||
|
let mut parts = coordinate.split(':');
|
||||||
|
match (parts.next(), parts.next(), parts.next()) {
|
||||||
|
(Some("org.lwjgl"), Some("lwjgl-glfw"), Some(version)) => Some(version.to_owned()),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn discover_glfw_installations() -> Vec<GlfwInstallation> {
|
||||||
|
discover_in(&discovery_directories(), std::env::consts::OS)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn discovery_directories() -> Vec<PathBuf> {
|
||||||
|
let mut directories = Vec::<PathBuf>::new();
|
||||||
|
let variables: &[&str] = match std::env::consts::OS {
|
||||||
|
"windows" => &["PATH"],
|
||||||
|
"macos" => &["DYLD_LIBRARY_PATH", "DYLD_FALLBACK_LIBRARY_PATH", "PATH"],
|
||||||
|
_ => &["LD_LIBRARY_PATH", "PATH"],
|
||||||
|
};
|
||||||
|
for variable in variables {
|
||||||
|
if let Some(value) = std::env::var_os(variable) {
|
||||||
|
directories.extend(std::env::split_paths(&value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match std::env::consts::OS {
|
||||||
|
"windows" => {
|
||||||
|
if let Some(root) = std::env::var_os("SystemRoot") {
|
||||||
|
let root = PathBuf::from(root);
|
||||||
|
directories.extend([root.join("System32"), root.clone()]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"macos" => {
|
||||||
|
directories.extend(
|
||||||
|
[
|
||||||
|
"/usr/lib",
|
||||||
|
"/usr/local/lib",
|
||||||
|
"/opt/homebrew/lib",
|
||||||
|
"/opt/local/lib",
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.map(PathBuf::from),
|
||||||
|
);
|
||||||
|
if let Some(home) = dirs::home_dir() {
|
||||||
|
directories.push(home.join("lib"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
directories.extend(
|
||||||
|
["/usr/lib", "/usr/lib64", "/usr/local/lib", "/lib", "/lib64"]
|
||||||
|
.into_iter()
|
||||||
|
.map(PathBuf::from),
|
||||||
|
);
|
||||||
|
if let Some(home) = dirs::home_dir() {
|
||||||
|
directories.push(home.join(".local/lib"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Ok(executable) = std::env::current_exe()
|
||||||
|
&& let Some(parent) = executable.parent()
|
||||||
|
{
|
||||||
|
directories.push(parent.to_owned());
|
||||||
|
}
|
||||||
|
if let Ok(directory) = std::env::current_dir() {
|
||||||
|
directories.push(directory);
|
||||||
|
}
|
||||||
|
directories.sort();
|
||||||
|
directories.dedup();
|
||||||
|
directories
|
||||||
|
}
|
||||||
|
|
||||||
|
fn discover_in(roots: &[PathBuf], os: &str) -> Vec<GlfwInstallation> {
|
||||||
|
let mut directories = roots.to_vec();
|
||||||
|
let mut nested = Vec::new();
|
||||||
|
for directory in &directories {
|
||||||
|
if let Ok(entries) = std::fs::read_dir(directory) {
|
||||||
|
nested.extend(
|
||||||
|
entries
|
||||||
|
.flatten()
|
||||||
|
.map(|entry| entry.path())
|
||||||
|
.filter(|path| path.is_dir()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
directories.extend(nested);
|
||||||
|
let mut seen = BTreeSet::new();
|
||||||
|
let mut installations = Vec::new();
|
||||||
|
for directory in directories {
|
||||||
|
let Ok(entries) = std::fs::read_dir(directory) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for path in entries.flatten().map(|entry| entry.path()) {
|
||||||
|
if !path.is_file()
|
||||||
|
|| !path
|
||||||
|
.file_name()
|
||||||
|
.and_then(|name| name.to_str())
|
||||||
|
.is_some_and(|name| is_glfw_library_name(name, os))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let canonical = std::fs::canonicalize(&path).unwrap_or(path);
|
||||||
|
if seen.insert(canonical.clone()) {
|
||||||
|
installations.push(GlfwInstallation {
|
||||||
|
version: glfw_version_from_path(&canonical),
|
||||||
|
path: canonical,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
installations.sort_by(|left, right| left.path.cmp(&right.path));
|
||||||
|
installations
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_glfw_library_name(name: &str, os: &str) -> bool {
|
||||||
|
let name = name.to_ascii_lowercase();
|
||||||
|
let versioned_so = name.strip_prefix("libglfw.so.").is_some_and(|version| {
|
||||||
|
version.split('.').all(|part| {
|
||||||
|
!part.is_empty() && part.chars().all(|character| character.is_ascii_digit())
|
||||||
|
})
|
||||||
|
});
|
||||||
|
match os {
|
||||||
|
"windows" => name.starts_with("glfw") && name.ends_with(".dll"),
|
||||||
|
"macos" => name.starts_with("libglfw.") && name.ends_with(".dylib"),
|
||||||
|
_ => name == "libglfw.so" || versioned_so,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn glfw_version_from_path(path: &Path) -> Option<String> {
|
||||||
|
let name = path.file_name()?.to_str()?.to_ascii_lowercase();
|
||||||
|
if let Some((_, suffix)) = name.rsplit_once(".so.") {
|
||||||
|
return (!suffix.is_empty()).then(|| suffix.to_owned());
|
||||||
|
}
|
||||||
|
let stem = name
|
||||||
|
.strip_prefix("libglfw.")
|
||||||
|
.and_then(|name| name.strip_suffix(".dylib"))
|
||||||
|
.or_else(|| {
|
||||||
|
name.strip_prefix("glfw")
|
||||||
|
.and_then(|name| name.strip_suffix(".dll"))
|
||||||
|
})?;
|
||||||
|
(!stem.is_empty()).then(|| stem.trim_start_matches(['-', '.']).to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn library_names_are_recognized() {
|
||||||
|
assert!(is_glfw_library_name("libglfw.so.3", "linux"));
|
||||||
|
assert!(is_glfw_library_name("libglfw.3.dylib", "macos"));
|
||||||
|
assert!(is_glfw_library_name("glfw3.dll", "windows"));
|
||||||
|
assert!(!is_glfw_library_name("libglfw.so.backup", "linux"));
|
||||||
|
assert!(!is_glfw_library_name("libGL.so", "linux"));
|
||||||
|
assert_eq!(
|
||||||
|
glfw_version_from_path(Path::new("/usr/lib/libglfw.so.3.4")).as_deref(),
|
||||||
|
Some("3.4")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn each_platform_discovers_its_native_libraries_in_environment_and_nested_directories() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let nested = temp.path().join("native");
|
||||||
|
std::fs::create_dir(&nested).unwrap();
|
||||||
|
for name in ["libglfw.so.3.4", "libglfw.3.dylib", "GLFW3.DLL"] {
|
||||||
|
std::fs::write(temp.path().join(name), b"library").unwrap();
|
||||||
|
std::fs::write(nested.join(name), b"library").unwrap();
|
||||||
|
}
|
||||||
|
for (os, expected, version) in [
|
||||||
|
("linux", "libglfw.so.3.4", "3.4"),
|
||||||
|
("macos", "libglfw.3.dylib", "3"),
|
||||||
|
("windows", "GLFW3.DLL", "3"),
|
||||||
|
] {
|
||||||
|
let found = discover_in(&[temp.path().to_owned(), temp.path().to_owned()], os);
|
||||||
|
assert_eq!(found.len(), 2, "{os}");
|
||||||
|
assert!(
|
||||||
|
found
|
||||||
|
.iter()
|
||||||
|
.all(|installation| installation.path.file_name().unwrap() == expected)
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
found
|
||||||
|
.iter()
|
||||||
|
.all(|installation| installation.version.as_deref() == Some(version))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,263 +0,0 @@
|
|||||||
// importing modrinth .mrpack modpacks: parse the manifest, create the instance,
|
|
||||||
// download all the mods, and extract config/resource overrides from the zip
|
|
||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
|
|
||||||
use crate::instance::manager::InstanceManager;
|
|
||||||
use crate::instance::models::ModLoader;
|
|
||||||
use crate::net::modrinth::MrpackIndex;
|
|
||||||
use crate::tui::progress;
|
|
||||||
|
|
||||||
#[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 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)
|
|
||||||
.ok_or_else(|| "Manifest missing minecraft dependency".to_string())?;
|
|
||||||
|
|
||||||
let (loader_opt, loader_version) =
|
|
||||||
crate::net::modrinth::loader_from_dependencies(&index.dependencies);
|
|
||||||
let loader = loader_opt.unwrap_or(ModLoader::Vanilla);
|
|
||||||
|
|
||||||
let override_count = count_overrides(&mrpack_path).unwrap_or(0);
|
|
||||||
|
|
||||||
Ok(ImportSummary {
|
|
||||||
name: index.name.clone(),
|
|
||||||
pack_version: index.version_id.clone(),
|
|
||||||
game_version,
|
|
||||||
loader,
|
|
||||||
loader_version,
|
|
||||||
mod_count: index.files.len(),
|
|
||||||
override_count,
|
|
||||||
mrpack_path,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// peek into the zip to count files under overrides/ and client-overrides/
|
|
||||||
fn count_overrides(mrpack_path: &Path) -> Result<usize, String> {
|
|
||||||
let file = std::fs::File::open(mrpack_path).map_err(|e| e.to_string())?;
|
|
||||||
let archive = zip::ZipArchive::new(file).map_err(|e| e.to_string())?;
|
|
||||||
let count = archive
|
|
||||||
.file_names()
|
|
||||||
.filter(|name| {
|
|
||||||
(name.starts_with("overrides/") || name.starts_with("client-overrides/"))
|
|
||||||
&& !name.ends_with('/')
|
|
||||||
})
|
|
||||||
.count();
|
|
||||||
Ok(count)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub 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>> {
|
|
||||||
let name = 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");
|
|
||||||
|
|
||||||
let index = crate::net::modrinth::parse_mrpack(&summary.mrpack_path)
|
|
||||||
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { e.into() })?;
|
|
||||||
|
|
||||||
download_mod_files(&index, &minecraft_dir).await?;
|
|
||||||
|
|
||||||
extract_overrides(&summary.mrpack_path, &minecraft_dir)?;
|
|
||||||
|
|
||||||
progress::clear();
|
|
||||||
Ok(config)
|
|
||||||
}
|
|
||||||
|
|
||||||
// downloads all mod files listed in the mrpack index, capped at 10 concurrent
|
|
||||||
// downloads to avoid getting rate-limited into oblivion
|
|
||||||
async fn download_mod_files(
|
|
||||||
index: &MrpackIndex,
|
|
||||||
minecraft_dir: &Path,
|
|
||||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
|
||||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
let client = crate::net::HttpClient::new();
|
|
||||||
let total = index.files.len();
|
|
||||||
let completed = Arc::new(AtomicUsize::new(0));
|
|
||||||
|
|
||||||
progress::set_action(format!("Downloading mods... 0/{total}"));
|
|
||||||
|
|
||||||
// bounded concurrency via manual JoinSet draining: seed with max_concurrent
|
|
||||||
// tasks, then spawn a new one each time one finishes
|
|
||||||
let mut tasks = tokio::task::JoinSet::new();
|
|
||||||
let max_concurrent = 10;
|
|
||||||
let mut file_iter = index.files.iter();
|
|
||||||
|
|
||||||
for _ in 0..max_concurrent {
|
|
||||||
if let Some(file) = file_iter.next() {
|
|
||||||
let client = client.clone();
|
|
||||||
let dest = minecraft_dir.join(&file.path);
|
|
||||||
let url = file.downloads.first().cloned().unwrap_or_default();
|
|
||||||
let filename = file
|
|
||||||
.path
|
|
||||||
.rsplit('/')
|
|
||||||
.next()
|
|
||||||
.unwrap_or(&file.path)
|
|
||||||
.to_string();
|
|
||||||
let completed = completed.clone();
|
|
||||||
tasks.spawn(async move {
|
|
||||||
if let Some(parent) = dest.parent() {
|
|
||||||
let _ = tokio::fs::create_dir_all(parent).await;
|
|
||||||
}
|
|
||||||
progress::set_sub_action(filename);
|
|
||||||
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
|
|
||||||
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
|
|
||||||
progress::set_action(format!("Downloading mods... {done}/{total}"));
|
|
||||||
Ok::<(), crate::net::NetError>(())
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for file in file_iter {
|
|
||||||
if let Some(result) = tasks.join_next().await {
|
|
||||||
result
|
|
||||||
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?
|
|
||||||
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?;
|
|
||||||
}
|
|
||||||
let client = client.clone();
|
|
||||||
let dest = minecraft_dir.join(&file.path);
|
|
||||||
let url = file.downloads.first().cloned().unwrap_or_default();
|
|
||||||
let filename = file
|
|
||||||
.path
|
|
||||||
.rsplit('/')
|
|
||||||
.next()
|
|
||||||
.unwrap_or(&file.path)
|
|
||||||
.to_string();
|
|
||||||
let completed = completed.clone();
|
|
||||||
tasks.spawn(async move {
|
|
||||||
if let Some(parent) = dest.parent() {
|
|
||||||
let _ = tokio::fs::create_dir_all(parent).await;
|
|
||||||
}
|
|
||||||
progress::set_sub_action(filename);
|
|
||||||
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
|
|
||||||
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
|
|
||||||
progress::set_action(format!("Downloading mods... {done}/{total}"));
|
|
||||||
Ok::<(), crate::net::NetError>(())
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
while let Some(result) = tasks.join_next().await {
|
|
||||||
result
|
|
||||||
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?
|
|
||||||
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn extract_overrides(
|
|
||||||
mrpack_path: &Path,
|
|
||||||
minecraft_dir: &Path,
|
|
||||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
|
||||||
use std::io::Read;
|
|
||||||
|
|
||||||
progress::set_action("Extracting overrides...".to_string());
|
|
||||||
progress::set_sub_action(String::new());
|
|
||||||
|
|
||||||
let file = std::fs::File::open(mrpack_path)?;
|
|
||||||
let mut archive = zip::ZipArchive::new(file)?;
|
|
||||||
|
|
||||||
for i in 0..archive.len() {
|
|
||||||
let mut entry = archive.by_index(i)?;
|
|
||||||
let entry_name = entry.name().to_string();
|
|
||||||
|
|
||||||
let relative = entry_name
|
|
||||||
.strip_prefix("overrides/")
|
|
||||||
.or_else(|| entry_name.strip_prefix("client-overrides/"));
|
|
||||||
|
|
||||||
let Some(relative) = relative else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
if relative.is_empty() || entry_name.ends_with('/') {
|
|
||||||
let dir = minecraft_dir.join(relative);
|
|
||||||
std::fs::create_dir_all(dir)?;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let dest = minecraft_dir.join(relative);
|
|
||||||
if let Some(parent) = dest.parent() {
|
|
||||||
std::fs::create_dir_all(parent)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut buf = Vec::new();
|
|
||||||
entry.read_to_end(&mut buf)?;
|
|
||||||
std::fs::write(&dest, &buf)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
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)");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use std::io::Read;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
const MAX_PACK_MANIFEST_BYTES: u64 = 8 * 1024 * 1024;
|
||||||
|
|
||||||
|
pub(super) fn read_pack_manifest(reader: impl Read) -> Result<Vec<u8>, String> {
|
||||||
|
let mut bytes = Vec::new();
|
||||||
|
reader
|
||||||
|
.take(MAX_PACK_MANIFEST_BYTES + 1)
|
||||||
|
.read_to_end(&mut bytes)
|
||||||
|
.map_err(|error| error.to_string())?;
|
||||||
|
if bytes.len() as u64 > MAX_PACK_MANIFEST_BYTES {
|
||||||
|
return Err("Pack manifest exceeds 8 MiB".to_owned());
|
||||||
|
}
|
||||||
|
Ok(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn relative_path(
|
||||||
|
entry: &zip::read::ZipFile<'_, std::fs::File>,
|
||||||
|
root: &str,
|
||||||
|
) -> Result<Option<PathBuf>, String> {
|
||||||
|
let root = root.trim_matches('/');
|
||||||
|
if root.is_empty() || !entry.name().starts_with(&format!("{root}/")) {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let enclosed = entry
|
||||||
|
.enclosed_name()
|
||||||
|
.ok_or_else(|| format!("Unsafe override path: {}", entry.name()))?;
|
||||||
|
let relative = enclosed
|
||||||
|
.strip_prefix(root)
|
||||||
|
.map_err(|_| format!("Invalid override path: {}", entry.name()))?;
|
||||||
|
if relative.as_os_str().is_empty() {
|
||||||
|
return Ok(Some(relative.to_owned()));
|
||||||
|
}
|
||||||
|
let relative = relative
|
||||||
|
.to_str()
|
||||||
|
.ok_or_else(|| "Override path is not UTF-8".to_owned())?;
|
||||||
|
Ok(Some(PathBuf::from(super::portable_pack_path(relative)?)))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn override_files(path: &Path, roots: &[&str]) -> Result<Vec<PathBuf>, String> {
|
||||||
|
let file = std::fs::File::open(path).map_err(|error| error.to_string())?;
|
||||||
|
let mut archive = zip::ZipArchive::new(file).map_err(|error| error.to_string())?;
|
||||||
|
let mut files = Vec::new();
|
||||||
|
for index in 0..archive.len() {
|
||||||
|
let entry = archive.by_index(index).map_err(|error| error.to_string())?;
|
||||||
|
if entry.is_dir() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for root in roots {
|
||||||
|
if let Some(relative) = relative_path(&entry, root)?
|
||||||
|
&& !relative.as_os_str().is_empty()
|
||||||
|
{
|
||||||
|
files.push(relative);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(files)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn extract_overrides(
|
||||||
|
path: &Path,
|
||||||
|
destination: &Path,
|
||||||
|
roots: &[&str],
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let file = std::fs::File::open(path)?;
|
||||||
|
let mut archive = zip::ZipArchive::new(file)?;
|
||||||
|
// Later roots override earlier ones, independently of ZIP entry order.
|
||||||
|
for root in roots {
|
||||||
|
for index in 0..archive.len() {
|
||||||
|
let mut entry = archive.by_index(index)?;
|
||||||
|
let Some(relative) = relative_path(&entry, root)? else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let target = destination.join(relative);
|
||||||
|
if entry.is_dir() {
|
||||||
|
std::fs::create_dir_all(&target)?;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(parent) = target.parent() {
|
||||||
|
std::fs::create_dir_all(parent)?;
|
||||||
|
}
|
||||||
|
let mut file = std::fs::File::create(&target)?;
|
||||||
|
let size = std::io::copy(&mut entry, &mut file)?;
|
||||||
|
tracing::trace!(
|
||||||
|
"Extracted {} to {} ({} bytes)",
|
||||||
|
entry.name(),
|
||||||
|
target.display(),
|
||||||
|
size
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use crate::feedback::progress;
|
||||||
|
use crate::instance::{InstanceConfig, InstanceManager, ModLoader};
|
||||||
|
|
||||||
|
use super::{ImportSummary, PackFormat};
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct Manifest {
|
||||||
|
name: String,
|
||||||
|
version: String,
|
||||||
|
minecraft: Minecraft,
|
||||||
|
#[serde(default)]
|
||||||
|
files: Vec<ManifestFile>,
|
||||||
|
#[serde(default = "default_overrides")]
|
||||||
|
overrides: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct Minecraft {
|
||||||
|
version: String,
|
||||||
|
#[serde(default)]
|
||||||
|
mod_loaders: Vec<ManifestLoader>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct ManifestLoader {
|
||||||
|
id: String,
|
||||||
|
#[serde(default)]
|
||||||
|
primary: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct ManifestFile {
|
||||||
|
#[serde(rename = "projectID")]
|
||||||
|
_project_id: u64,
|
||||||
|
#[serde(rename = "fileID")]
|
||||||
|
file_id: u64,
|
||||||
|
#[serde(default = "required_by_default")]
|
||||||
|
required: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_overrides() -> String {
|
||||||
|
"overrides".to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn required_by_default() -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse(path: &Path) -> Result<Manifest, String> {
|
||||||
|
let file = std::fs::File::open(path).map_err(|error| error.to_string())?;
|
||||||
|
let mut archive = zip::ZipArchive::new(file).map_err(|error| error.to_string())?;
|
||||||
|
let entry = archive
|
||||||
|
.by_name("manifest.json")
|
||||||
|
.map_err(|_| "Missing manifest.json in CurseForge pack".to_owned())?;
|
||||||
|
let raw = super::read_pack_manifest(entry)?;
|
||||||
|
serde_json::from_slice(&raw).map_err(|error| format!("Invalid CurseForge manifest: {error}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn loader(manifest: &Manifest) -> (ModLoader, Option<String>) {
|
||||||
|
let id = manifest
|
||||||
|
.minecraft
|
||||||
|
.mod_loaders
|
||||||
|
.iter()
|
||||||
|
.find(|loader| loader.primary)
|
||||||
|
.or_else(|| manifest.minecraft.mod_loaders.first())
|
||||||
|
.map(|loader| loader.id.as_str());
|
||||||
|
let Some(id) = id else {
|
||||||
|
return (ModLoader::Vanilla, None);
|
||||||
|
};
|
||||||
|
let (name, version) = id.split_once('-').unwrap_or((id, ""));
|
||||||
|
let loader = match name.to_ascii_lowercase().as_str() {
|
||||||
|
"fabric" => ModLoader::Fabric,
|
||||||
|
"forge" => ModLoader::Forge,
|
||||||
|
"neoforge" => ModLoader::NeoForge,
|
||||||
|
"quilt" => ModLoader::Quilt,
|
||||||
|
_ => ModLoader::Vanilla,
|
||||||
|
};
|
||||||
|
(
|
||||||
|
loader,
|
||||||
|
(!version.is_empty() && loader != ModLoader::Vanilla).then(|| version.to_owned()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||||
|
let manifest = parse(path)?;
|
||||||
|
let (loader, loader_version) = loader(&manifest);
|
||||||
|
let override_count = super::override_files(path, &[&manifest.overrides])?.len();
|
||||||
|
Ok(ImportSummary {
|
||||||
|
name: manifest.name,
|
||||||
|
pack_version: manifest.version,
|
||||||
|
game_version: manifest.minecraft.version,
|
||||||
|
loader,
|
||||||
|
loader_version,
|
||||||
|
mod_count: manifest.files.iter().filter(|file| file.required).count(),
|
||||||
|
override_count,
|
||||||
|
format: PackFormat::CurseForge,
|
||||||
|
archive_path: path.to_owned(),
|
||||||
|
source: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn execute_import(
|
||||||
|
summary: &ImportSummary,
|
||||||
|
manager: &InstanceManager,
|
||||||
|
config: &InstanceConfig,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
crate::instance::manager::validate_name(&config.name)?;
|
||||||
|
let minecraft_dir = manager
|
||||||
|
.instances_dir
|
||||||
|
.join(&config.name)
|
||||||
|
.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||||
|
let manifest = parse(&summary.archive_path)?;
|
||||||
|
download_files(&manifest, &minecraft_dir).await?;
|
||||||
|
extract_overrides(&summary.archive_path, &minecraft_dir, &manifest.overrides)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn download_files(
|
||||||
|
manifest: &Manifest,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let ids = manifest
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.filter(|file| file.required)
|
||||||
|
.map(|file| file.file_id)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
if ids.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let api_key =
|
||||||
|
crate::net::curseforge::api_key().ok_or("CurseForge API key is not configured")?;
|
||||||
|
let client = crate::net::HttpClient::new();
|
||||||
|
let versions = crate::net::curseforge::fetch_file_versions(&client, api_key, &ids).await?;
|
||||||
|
if versions.len() != ids.len() {
|
||||||
|
return Err(format!(
|
||||||
|
"CurseForge returned {} of {} required pack files",
|
||||||
|
versions.len(),
|
||||||
|
ids.len()
|
||||||
|
)
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
let mods_dir = minecraft_dir.join("mods");
|
||||||
|
tokio::fs::create_dir_all(&mods_dir).await?;
|
||||||
|
let total = versions.len();
|
||||||
|
progress::set_action(format!("Downloading mods... 0/{total}"));
|
||||||
|
let completed = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||||
|
let slots = std::sync::Arc::new(tokio::sync::Semaphore::new(10));
|
||||||
|
let mut tasks = tokio::task::JoinSet::new();
|
||||||
|
for mut version in versions {
|
||||||
|
let client = client.clone();
|
||||||
|
let api_key = api_key.to_owned();
|
||||||
|
let mods_dir = mods_dir.clone();
|
||||||
|
let completed = completed.clone();
|
||||||
|
let slots = slots.clone();
|
||||||
|
tasks.spawn(async move {
|
||||||
|
let _permit = slots.acquire_owned().await?;
|
||||||
|
crate::net::curseforge::ensure_download_url(&client, &api_key, &mut version).await?;
|
||||||
|
crate::net::modrinth::download_version_file(&client, &version, &mods_dir).await?;
|
||||||
|
let finished = completed.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
|
||||||
|
progress::set_action(format!("Downloading mods... {finished}/{total}"));
|
||||||
|
Ok::<(), Box<dyn std::error::Error + Send + Sync>>(())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
while let Some(result) = tasks.join_next().await {
|
||||||
|
result??;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn owned_files(path: &Path) -> Result<Vec<std::path::PathBuf>, String> {
|
||||||
|
let manifest = parse(path)?;
|
||||||
|
let overrides = super::override_files(path, &[manifest.overrides.trim_matches('/')])?;
|
||||||
|
let ids = manifest
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.filter(|file| file.required)
|
||||||
|
.map(|file| file.file_id)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
if ids.is_empty() {
|
||||||
|
return Ok(overrides);
|
||||||
|
}
|
||||||
|
let api_key = crate::net::curseforge::api_key()
|
||||||
|
.ok_or_else(|| "CurseForge API key is not configured".to_owned())?;
|
||||||
|
let versions =
|
||||||
|
crate::net::curseforge::fetch_file_versions(&crate::net::HttpClient::new(), api_key, &ids)
|
||||||
|
.await
|
||||||
|
.map_err(|error| error.to_string())?;
|
||||||
|
if versions.len() != ids.len() {
|
||||||
|
return Err(format!(
|
||||||
|
"CurseForge returned {} of {} required pack files",
|
||||||
|
versions.len(),
|
||||||
|
ids.len()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let mut files: Vec<_> = versions
|
||||||
|
.into_iter()
|
||||||
|
.map(|version| {
|
||||||
|
version
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.find(|file| file.primary)
|
||||||
|
.or_else(|| version.files.first())
|
||||||
|
.ok_or_else(|| format!("CurseForge file '{}' has no artifact", version.id))
|
||||||
|
.and_then(|file| super::portable_pack_path(&format!("mods/{}", file.filename)))
|
||||||
|
.map(std::path::PathBuf::from)
|
||||||
|
})
|
||||||
|
.collect::<Result<_, _>>()?;
|
||||||
|
files.extend(overrides);
|
||||||
|
Ok(files)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extract_overrides(
|
||||||
|
path: &Path,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
root: &str,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
progress::set_action("Extracting overrides...");
|
||||||
|
super::archive::extract_overrides(path, minecraft_dir, &[root])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/import/curseforge.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use crate::feedback::progress;
|
||||||
|
use crate::instance::manager::InstanceManager;
|
||||||
|
use crate::instance::models::ModLoader;
|
||||||
|
|
||||||
|
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)?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Parsed MultiMC pack {} with {} component(s)",
|
||||||
|
path.display(),
|
||||||
|
pack.components.len()
|
||||||
|
);
|
||||||
|
|
||||||
|
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)?;
|
||||||
|
tracing::trace!(
|
||||||
|
"MultiMC summary: name='{}' game_version={} loader={:?} loader_version={:?} mods={} overrides={}",
|
||||||
|
name,
|
||||||
|
game_version,
|
||||||
|
loader,
|
||||||
|
loader_version,
|
||||||
|
mod_count,
|
||||||
|
override_count
|
||||||
|
);
|
||||||
|
|
||||||
|
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(),
|
||||||
|
source: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn execute_import(
|
||||||
|
summary: &ImportSummary,
|
||||||
|
manager: &InstanceManager,
|
||||||
|
config: &crate::instance::InstanceConfig,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
crate::instance::manager::validate_name(&config.name)?;
|
||||||
|
tracing::info!(
|
||||||
|
"Importing MultiMC/Prism pack '{}' as instance '{}'",
|
||||||
|
summary.name,
|
||||||
|
config.name
|
||||||
|
);
|
||||||
|
|
||||||
|
let minecraft_dir = manager
|
||||||
|
.instances_dir
|
||||||
|
.join(&config.name)
|
||||||
|
.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||||
|
extract_mmc_archive(&summary.archive_path, &minecraft_dir)?;
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
"Imported MultiMC/Prism pack '{}' as '{}'",
|
||||||
|
summary.name,
|
||||||
|
config.name
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extract_mmc_archive(
|
||||||
|
archive_path: &Path,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
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/");
|
||||||
|
tracing::debug!(
|
||||||
|
"Extracting MultiMC archive {} with prefix '{}' into {}",
|
||||||
|
archive_path.display(),
|
||||||
|
prefix,
|
||||||
|
minecraft_dir.display()
|
||||||
|
);
|
||||||
|
|
||||||
|
let total = archive.len();
|
||||||
|
let mut extracted = 0usize;
|
||||||
|
let mut dirs = 0usize;
|
||||||
|
for i in 0..total {
|
||||||
|
let mut entry = archive.by_index(i)?;
|
||||||
|
let entry_name = entry.name().to_string();
|
||||||
|
|
||||||
|
if !entry_name.starts_with(&minecraft_prefix) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let enclosed = entry.enclosed_name().ok_or_else(|| {
|
||||||
|
std::io::Error::new(
|
||||||
|
std::io::ErrorKind::InvalidData,
|
||||||
|
format!("Unsafe archive path: {entry_name}"),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let relative = enclosed
|
||||||
|
.strip_prefix(minecraft_prefix.trim_end_matches('/'))
|
||||||
|
.map_err(|_| {
|
||||||
|
std::io::Error::new(
|
||||||
|
std::io::ErrorKind::InvalidData,
|
||||||
|
format!("Invalid archive path: {entry_name}"),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let relative = if relative.as_os_str().is_empty() {
|
||||||
|
std::path::PathBuf::new()
|
||||||
|
} else {
|
||||||
|
std::path::PathBuf::from(super::portable_pack_path(
|
||||||
|
relative.to_str().ok_or("Archive path is not UTF-8")?,
|
||||||
|
)?)
|
||||||
|
};
|
||||||
|
if relative.as_os_str().is_empty() || entry_name.ends_with('/') {
|
||||||
|
std::fs::create_dir_all(minecraft_dir.join(&relative))?;
|
||||||
|
dirs += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let dest = minecraft_dir.join(&relative);
|
||||||
|
if let Some(parent) = dest.parent() {
|
||||||
|
std::fs::create_dir_all(parent)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let filename = relative
|
||||||
|
.file_name()
|
||||||
|
.and_then(|name| name.to_str())
|
||||||
|
.unwrap_or_default();
|
||||||
|
progress::set_sub_action(filename.to_string());
|
||||||
|
|
||||||
|
let mut destination = std::fs::File::create(&dest)?;
|
||||||
|
let size = std::io::copy(&mut entry, &mut destination)?;
|
||||||
|
tracing::trace!(
|
||||||
|
"Extracting MultiMC entry {} to {} ({} bytes)",
|
||||||
|
entry_name,
|
||||||
|
dest.display(),
|
||||||
|
size
|
||||||
|
);
|
||||||
|
extracted += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::debug!(
|
||||||
|
"Extracted {} files and {} directories from MultiMC archive {}",
|
||||||
|
extracted,
|
||||||
|
dirs,
|
||||||
|
archive_path.display()
|
||||||
|
);
|
||||||
|
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}"))?;
|
||||||
|
|
||||||
|
let raw = super::read_pack_manifest(entry)?;
|
||||||
|
serde_json::from_slice(&raw).map_err(|e| format!("Invalid mmc-pack.json: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn instance_name_from_cfg(path: &Path) -> Option<String> {
|
||||||
|
let file = std::fs::File::open(path).ok()?;
|
||||||
|
let mut archive = zip::ZipArchive::new(file).ok()?;
|
||||||
|
|
||||||
|
let entry_name = find_entry(&archive, "instance.cfg")?;
|
||||||
|
tracing::trace!("Reading instance name from {}", entry_name);
|
||||||
|
let entry = archive.by_name(&entry_name).ok()?;
|
||||||
|
let raw = super::read_pack_manifest(entry).ok()?;
|
||||||
|
let reader = std::io::BufRead::lines(std::io::BufReader::new(raw.as_slice()));
|
||||||
|
for line in reader.map_while(Result::ok) {
|
||||||
|
if let Some(value) = line.strip_prefix("name=") {
|
||||||
|
let name = value.trim().to_string();
|
||||||
|
if !name.is_empty() {
|
||||||
|
tracing::debug!("Read MultiMC instance name '{}' from instance.cfg", name);
|
||||||
|
return Some(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_archive_prefix(archive: &zip::ZipArchive<std::fs::File>) -> String {
|
||||||
|
find_entry(archive, "mmc-pack.json")
|
||||||
|
.and_then(|name| name.strip_suffix("mmc-pack.json").map(str::to_owned))
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
// looks for a file at root or one level deep (some archives nest everything
|
||||||
|
// 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)]
|
||||||
|
#[path = "../tests/import/mmc.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
mod archive;
|
||||||
|
pub mod curseforge;
|
||||||
|
pub mod mmc;
|
||||||
|
pub mod mrpack;
|
||||||
|
pub mod refresh;
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use archive::{override_files, read_pack_manifest};
|
||||||
|
|
||||||
|
use crate::instance::manager::InstanceManager;
|
||||||
|
use crate::instance::models::ModLoader;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum PackFormat {
|
||||||
|
CurseForge,
|
||||||
|
Mrpack,
|
||||||
|
Mmc,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub enum ImportInput {
|
||||||
|
ProjectSlug(String),
|
||||||
|
VersionId { slug: String, version_id: String },
|
||||||
|
LocalFile(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse_import_input(input: &str) -> ImportInput {
|
||||||
|
let input = input.trim();
|
||||||
|
|
||||||
|
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();
|
||||||
|
let parsed = 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()),
|
||||||
|
};
|
||||||
|
tracing::debug!("Import input resolved as Modrinth URL: {:?}", parsed);
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
if input.rsplit_once('.').is_some_and(|(_, extension)| {
|
||||||
|
extension.eq_ignore_ascii_case("mrpack") || extension.eq_ignore_ascii_case("zip")
|
||||||
|
}) || input.starts_with('/')
|
||||||
|
|| input.starts_with("~/")
|
||||||
|
|| input.starts_with("./")
|
||||||
|
|| input.starts_with("../")
|
||||||
|
|| input.contains('\\')
|
||||||
|
|| input
|
||||||
|
.as_bytes()
|
||||||
|
.get(..2)
|
||||||
|
.is_some_and(|prefix| prefix[0].is_ascii_alphabetic() && prefix[1] == b':')
|
||||||
|
{
|
||||||
|
tracing::debug!("Import input resolved as local file: {}", input);
|
||||||
|
return ImportInput::LocalFile(input.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::debug!("Import input resolved as Modrinth project slug: {}", input);
|
||||||
|
ImportInput::ProjectSlug(input.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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,
|
||||||
|
pub source: Option<crate::instance::ProviderProject>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn detect_format(path: &Path) -> Result<PackFormat, String> {
|
||||||
|
tracing::debug!("Detecting modpack format for {}", path.display());
|
||||||
|
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") {
|
||||||
|
tracing::debug!("Detected Modrinth .mrpack archive: {}", path.display());
|
||||||
|
return Ok(PackFormat::Mrpack);
|
||||||
|
}
|
||||||
|
|
||||||
|
if archive.file_names().any(|name| name == "manifest.json") {
|
||||||
|
tracing::debug!("Detected CurseForge archive: {}", path.display());
|
||||||
|
return Ok(PackFormat::CurseForge);
|
||||||
|
}
|
||||||
|
|
||||||
|
// mmc-pack.json can be at root or one directory deep
|
||||||
|
if archive
|
||||||
|
.file_names()
|
||||||
|
.any(|n| n == "mmc-pack.json" || n.ends_with("/mmc-pack.json"))
|
||||||
|
{
|
||||||
|
tracing::debug!("Detected MultiMC/Prism archive: {}", path.display());
|
||||||
|
return Ok(PackFormat::Mmc);
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::warn!("Unknown modpack archive format: {}", path.display());
|
||||||
|
Err(
|
||||||
|
"Unknown pack format: no modrinth.index.json, manifest.json, or mmc-pack.json found"
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||||
|
if !path.exists() {
|
||||||
|
tracing::warn!("Cannot import missing file {}", path.display());
|
||||||
|
return Err(format!("File not found: {}", path.display()));
|
||||||
|
}
|
||||||
|
let format = detect_format(path)?;
|
||||||
|
let summary = match format {
|
||||||
|
PackFormat::CurseForge => curseforge::build_summary(path),
|
||||||
|
PackFormat::Mrpack => mrpack::build_summary(path),
|
||||||
|
PackFormat::Mmc => mmc::build_summary(path),
|
||||||
|
}?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Built import summary for {}: name='{}' format={:?} mc={} loader={} loader_version={:?} mods={} overrides={}",
|
||||||
|
path.display(),
|
||||||
|
summary.name,
|
||||||
|
summary.format,
|
||||||
|
summary.game_version,
|
||||||
|
summary.loader,
|
||||||
|
summary.loader_version,
|
||||||
|
summary.mod_count,
|
||||||
|
summary.override_count
|
||||||
|
);
|
||||||
|
Ok(summary)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn unique_instance_name(
|
||||||
|
base: &str,
|
||||||
|
instances_dir: &Path,
|
||||||
|
) -> Result<String, crate::instance::manager::InstanceError> {
|
||||||
|
crate::instance::manager::validate_name(base)?;
|
||||||
|
let candidate = base.to_string();
|
||||||
|
if !instances_dir.join(&candidate).exists() {
|
||||||
|
tracing::trace!("Import instance name '{}' is available", candidate);
|
||||||
|
return Ok(candidate);
|
||||||
|
}
|
||||||
|
let mut n = 2;
|
||||||
|
loop {
|
||||||
|
let candidate = format!("{base} ({n})");
|
||||||
|
crate::instance::manager::validate_name(&candidate)?;
|
||||||
|
if !instances_dir.join(&candidate).exists() {
|
||||||
|
tracing::debug!(
|
||||||
|
"Import instance name '{}' collided; using '{}'",
|
||||||
|
base,
|
||||||
|
candidate
|
||||||
|
);
|
||||||
|
return Ok(candidate);
|
||||||
|
}
|
||||||
|
n += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn execute_import(
|
||||||
|
summary: &ImportSummary,
|
||||||
|
manager: &InstanceManager,
|
||||||
|
) -> Result<crate::instance::InstanceConfig, Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
tracing::info!(
|
||||||
|
"Executing {:?} import '{}' from {}",
|
||||||
|
summary.format,
|
||||||
|
summary.name,
|
||||||
|
summary.archive_path.display()
|
||||||
|
);
|
||||||
|
let name = unique_instance_name(&summary.name, &manager.instances_dir)
|
||||||
|
.inspect_err(|_| crate::feedback::progress::clear())?;
|
||||||
|
crate::feedback::progress::set_action("Importing instance...");
|
||||||
|
crate::feedback::progress::set_sub_action(format!(
|
||||||
|
"{} {}",
|
||||||
|
summary.game_version, summary.loader
|
||||||
|
));
|
||||||
|
let config = manager
|
||||||
|
.create(
|
||||||
|
&name,
|
||||||
|
&summary.game_version,
|
||||||
|
summary.loader,
|
||||||
|
summary.loader_version.as_deref(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let mut config = match config {
|
||||||
|
Ok(config) => config,
|
||||||
|
Err(error) => {
|
||||||
|
crate::feedback::progress::clear();
|
||||||
|
return Err(Box::new(error));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let result = async {
|
||||||
|
match summary.format {
|
||||||
|
PackFormat::CurseForge => curseforge::execute_import(summary, manager, &config).await?,
|
||||||
|
PackFormat::Mrpack => mrpack::execute_import(summary, manager, &config).await?,
|
||||||
|
PackFormat::Mmc => mmc::execute_import(summary, manager, &config).await?,
|
||||||
|
}
|
||||||
|
if let Some(source) = &summary.source {
|
||||||
|
config.modpack_source = Some(source.clone());
|
||||||
|
manager.save(&config)?;
|
||||||
|
let state = refresh::PackState {
|
||||||
|
source: source.clone(),
|
||||||
|
files: owned_files(summary).await?,
|
||||||
|
};
|
||||||
|
state.save(&crate::storage::InstancePaths::new(
|
||||||
|
manager.instances_dir.join(&config.name),
|
||||||
|
))?;
|
||||||
|
}
|
||||||
|
Ok::<_, Box<dyn std::error::Error + Send + Sync>>(config)
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
crate::feedback::progress::clear();
|
||||||
|
if result.is_err() {
|
||||||
|
cleanup_failed_import(manager, &name);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn provider_versions(
|
||||||
|
source: &crate::instance::ProviderProject,
|
||||||
|
) -> Result<Vec<crate::net::modrinth::VersionInfo>, crate::net::NetError> {
|
||||||
|
let client = crate::net::HttpClient::new();
|
||||||
|
match source.provider.as_str() {
|
||||||
|
"curseforge" => {
|
||||||
|
let api_key = crate::net::curseforge::api_key().ok_or_else(|| {
|
||||||
|
crate::net::NetError::Parse("CurseForge API key is not configured".to_owned())
|
||||||
|
})?;
|
||||||
|
crate::net::curseforge::fetch_versions(&client, api_key, &source.project_id, "", None)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
"modrinth" => crate::net::modrinth::fetch_versions(&client, &source.project_id).await,
|
||||||
|
provider => Err(crate::net::NetError::Parse(format!(
|
||||||
|
"Unsupported modpack provider '{provider}'"
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn download_provider_summary(
|
||||||
|
source: &crate::instance::ProviderProject,
|
||||||
|
version: &crate::net::modrinth::VersionInfo,
|
||||||
|
temporary_dir: &Path,
|
||||||
|
) -> Result<ImportSummary, crate::net::NetError> {
|
||||||
|
tokio::fs::create_dir_all(temporary_dir).await?;
|
||||||
|
let registry = crate::instance::content::provider::ProviderRegistry::configured(
|
||||||
|
crate::net::HttpClient::new(),
|
||||||
|
);
|
||||||
|
let provider = registry.get(&source.provider).ok_or_else(|| {
|
||||||
|
crate::net::NetError::Parse(format!(
|
||||||
|
"{} content provider is unavailable",
|
||||||
|
source.provider
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
let archive = match provider
|
||||||
|
.download_version(version, temporary_dir, None)
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
crate::net::modrinth::DownloadOutcome::Downloaded(path)
|
||||||
|
| crate::net::modrinth::DownloadOutcome::SkippedExisting(path) => path,
|
||||||
|
};
|
||||||
|
let mut summary = build_summary(&archive).map_err(crate::net::NetError::Parse)?;
|
||||||
|
summary.source = Some(crate::instance::ProviderProject {
|
||||||
|
provider: source.provider.clone(),
|
||||||
|
project_id: source.project_id.clone(),
|
||||||
|
version_id: version.id.clone(),
|
||||||
|
});
|
||||||
|
Ok(summary)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn owned_files(summary: &ImportSummary) -> Result<Vec<PathBuf>, String> {
|
||||||
|
match summary.format {
|
||||||
|
PackFormat::Mrpack => mrpack::owned_files(&summary.archive_path),
|
||||||
|
PackFormat::CurseForge => curseforge::owned_files(&summary.archive_path).await,
|
||||||
|
PackFormat::Mmc => Err("Managed updates are unavailable for MultiMC packs".to_owned()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cleanup_failed_import(manager: &InstanceManager, name: &str) {
|
||||||
|
if let Err(error) = crate::instance::manager::validate_name(name) {
|
||||||
|
tracing::warn!("Refusing to clean up an invalid imported instance: {error}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let instance_dir = manager.instances_dir.join(name);
|
||||||
|
if let Err(error) = std::fs::remove_dir_all(&instance_dir)
|
||||||
|
&& error.kind() != std::io::ErrorKind::NotFound
|
||||||
|
{
|
||||||
|
tracing::warn!(
|
||||||
|
"Failed to clean up incomplete imported instance {}: {}",
|
||||||
|
instance_dir.display(),
|
||||||
|
error
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn portable_pack_path(path: &str) -> Result<String, String> {
|
||||||
|
let normalized = path.replace('\\', "/");
|
||||||
|
if !crate::storage::safe_relative_path(Path::new(&normalized))
|
||||||
|
|| !normalized
|
||||||
|
.split('/')
|
||||||
|
.all(crate::instance::manager::portable_component)
|
||||||
|
{
|
||||||
|
return Err(format!("Unsafe pack-owned path: {path:?}"));
|
||||||
|
}
|
||||||
|
Ok(normalized)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/import/format_detection.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,390 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use crate::feedback::progress;
|
||||||
|
use crate::instance::content::manifest::{
|
||||||
|
ContentFileRecord, ContentKind, ContentManifest, ProviderProject, Resolution, fingerprint,
|
||||||
|
};
|
||||||
|
use crate::instance::manager::InstanceManager;
|
||||||
|
use crate::instance::models::ModLoader;
|
||||||
|
use crate::storage::InstancePaths;
|
||||||
|
|
||||||
|
use super::{ImportSummary, PackFormat};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct MrpackIndex {
|
||||||
|
#[serde(rename = "formatVersion")]
|
||||||
|
pub format_version: u32,
|
||||||
|
pub game: String,
|
||||||
|
#[serde(rename = "versionId")]
|
||||||
|
pub version_id: String,
|
||||||
|
pub name: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub dependencies: HashMap<String, String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub files: Vec<MrpackFile>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
pub struct MrpackFile {
|
||||||
|
pub path: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub hashes: HashMap<String, String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub env: HashMap<String, String>,
|
||||||
|
pub downloads: Vec<String>,
|
||||||
|
#[serde(rename = "fileSize")]
|
||||||
|
pub file_size: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MrpackIndex {
|
||||||
|
fn client_files(&self) -> impl Iterator<Item = &MrpackFile> {
|
||||||
|
self.files.iter().filter(|file| {
|
||||||
|
file.env
|
||||||
|
.get("client")
|
||||||
|
.is_none_or(|support| support != "unsupported")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse_mrpack(path: &Path) -> Result<MrpackIndex, String> {
|
||||||
|
tracing::debug!("Parsing .mrpack manifest from {}", path.display());
|
||||||
|
let file = std::fs::File::open(path).map_err(|e| format!("Cannot open .mrpack: {e}"))?;
|
||||||
|
let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("Invalid ZIP: {e}"))?;
|
||||||
|
let entry = archive
|
||||||
|
.by_name("modrinth.index.json")
|
||||||
|
.map_err(|_| "Missing modrinth.index.json in .mrpack".to_string())?;
|
||||||
|
let raw = super::read_pack_manifest(entry)?;
|
||||||
|
let index: MrpackIndex =
|
||||||
|
serde_json::from_slice(&raw).map_err(|e| format!("Invalid manifest JSON: {e}"))?;
|
||||||
|
if index.format_version != 1 || index.game != "minecraft" {
|
||||||
|
return Err(format!(
|
||||||
|
"Unsupported .mrpack format {} for game '{}'",
|
||||||
|
index.format_version, index.game
|
||||||
|
));
|
||||||
|
}
|
||||||
|
tracing::debug!(
|
||||||
|
"Parsed .mrpack '{}' version_id={} files={} deps={}",
|
||||||
|
index.name,
|
||||||
|
index.version_id,
|
||||||
|
index.files.len(),
|
||||||
|
index.dependencies.len()
|
||||||
|
);
|
||||||
|
Ok(index)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn loader_from_dependencies(
|
||||||
|
deps: &HashMap<String, String>,
|
||||||
|
) -> (Option<ModLoader>, Option<String>) {
|
||||||
|
let loaders = [
|
||||||
|
("fabric-loader", ModLoader::Fabric),
|
||||||
|
("forge", ModLoader::Forge),
|
||||||
|
("neoforge", ModLoader::NeoForge),
|
||||||
|
("quilt-loader", ModLoader::Quilt),
|
||||||
|
];
|
||||||
|
for (key, loader) in &loaders {
|
||||||
|
if let Some(version) = deps.get(*key) {
|
||||||
|
tracing::trace!(
|
||||||
|
"Resolved Modrinth loader dependency {}={} as {}",
|
||||||
|
key,
|
||||||
|
version,
|
||||||
|
loader
|
||||||
|
);
|
||||||
|
return (Some(*loader), Some(version.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tracing::trace!("No Modrinth loader dependency found; treating pack as vanilla");
|
||||||
|
(None, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn game_version_from_dependencies(deps: &HashMap<String, String>) -> Option<String> {
|
||||||
|
deps.get("minecraft").cloned()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build_summary(path: &Path) -> Result<ImportSummary, String> {
|
||||||
|
let index = parse_mrpack(path)?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Parsed .mrpack '{}' version_id={} files={} deps={}",
|
||||||
|
index.name,
|
||||||
|
index.version_id,
|
||||||
|
index.files.len(),
|
||||||
|
index.dependencies.len()
|
||||||
|
);
|
||||||
|
|
||||||
|
let game_version = game_version_from_dependencies(&index.dependencies)
|
||||||
|
.ok_or_else(|| "Manifest missing minecraft dependency".to_string())?;
|
||||||
|
|
||||||
|
let (loader_opt, loader_version) = loader_from_dependencies(&index.dependencies);
|
||||||
|
let loader = loader_opt.unwrap_or(ModLoader::Vanilla);
|
||||||
|
|
||||||
|
let override_count = super::override_files(path, &["overrides", "client-overrides"])?.len();
|
||||||
|
tracing::trace!(
|
||||||
|
".mrpack summary: game_version={} loader={:?} loader_version={:?} overrides={}",
|
||||||
|
game_version,
|
||||||
|
loader,
|
||||||
|
loader_version,
|
||||||
|
override_count
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(ImportSummary {
|
||||||
|
name: index.name.clone(),
|
||||||
|
pack_version: index.version_id.clone(),
|
||||||
|
game_version,
|
||||||
|
loader,
|
||||||
|
loader_version,
|
||||||
|
mod_count: index.client_files().count(),
|
||||||
|
override_count,
|
||||||
|
format: PackFormat::Mrpack,
|
||||||
|
archive_path: path.to_path_buf(),
|
||||||
|
source: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn execute_import(
|
||||||
|
summary: &ImportSummary,
|
||||||
|
manager: &InstanceManager,
|
||||||
|
config: &crate::instance::InstanceConfig,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
crate::instance::manager::validate_name(&config.name)?;
|
||||||
|
tracing::info!(
|
||||||
|
"Importing Modrinth pack '{}' as instance '{}'",
|
||||||
|
summary.name,
|
||||||
|
config.name
|
||||||
|
);
|
||||||
|
|
||||||
|
let minecraft_dir = manager
|
||||||
|
.instances_dir
|
||||||
|
.join(&config.name)
|
||||||
|
.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||||
|
|
||||||
|
let index = parse_mrpack(&summary.archive_path)
|
||||||
|
.map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { e.into() })?;
|
||||||
|
download_mod_files(&index, &minecraft_dir).await?;
|
||||||
|
extract_overrides(&summary.archive_path, &minecraft_dir)?;
|
||||||
|
seed_content_manifest(
|
||||||
|
&index,
|
||||||
|
&InstancePaths::new(manager.instances_dir.join(&config.name)),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
"Imported Modrinth pack '{}' as '{}'",
|
||||||
|
summary.name,
|
||||||
|
config.name
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn download_mod_files(
|
||||||
|
index: &MrpackIndex,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
|
||||||
|
let client = crate::net::HttpClient::new();
|
||||||
|
let total = index.client_files().count();
|
||||||
|
let completed = Arc::new(AtomicUsize::new(0));
|
||||||
|
tracing::debug!(
|
||||||
|
"Downloading {} file(s) from .mrpack '{}' into {}",
|
||||||
|
total,
|
||||||
|
index.name,
|
||||||
|
minecraft_dir.display()
|
||||||
|
);
|
||||||
|
|
||||||
|
progress::set_action(format!("Downloading mods... 0/{total}"));
|
||||||
|
|
||||||
|
let mut tasks = tokio::task::JoinSet::new();
|
||||||
|
|
||||||
|
for file in index.client_files() {
|
||||||
|
// Keep at most ten downloads in flight to avoid provider rate limits.
|
||||||
|
if tasks.len() == 10
|
||||||
|
&& let Some(result) = tasks.join_next().await
|
||||||
|
{
|
||||||
|
result??;
|
||||||
|
}
|
||||||
|
let client = client.clone();
|
||||||
|
let relative = safe_mrpack_path(&file.path)?;
|
||||||
|
let dest = minecraft_dir.join(relative);
|
||||||
|
let url = file.downloads.first().cloned().ok_or_else(|| {
|
||||||
|
crate::net::NetError::Parse(format!(".mrpack file '{}' has no download URL", file.path))
|
||||||
|
})?;
|
||||||
|
let filename = file
|
||||||
|
.path
|
||||||
|
.rsplit('/')
|
||||||
|
.next()
|
||||||
|
.unwrap_or(&file.path)
|
||||||
|
.to_string();
|
||||||
|
let hashes = file.hashes.clone();
|
||||||
|
let file_size = file.file_size;
|
||||||
|
let completed = completed.clone();
|
||||||
|
tasks.spawn(async move {
|
||||||
|
if let Some(parent) = dest.parent()
|
||||||
|
&& let Err(error) = tokio::fs::create_dir_all(parent).await
|
||||||
|
{
|
||||||
|
return Err(crate::net::NetError::from(error));
|
||||||
|
}
|
||||||
|
progress::set_sub_action(filename);
|
||||||
|
tracing::trace!("Downloading .mrpack file to {}", dest.display());
|
||||||
|
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
|
||||||
|
if !verify_mrpack_file(&dest, file_size, &hashes)? {
|
||||||
|
let _ = tokio::fs::remove_file(&dest).await;
|
||||||
|
return Err(crate::net::NetError::Parse(format!(
|
||||||
|
"Downloaded .mrpack file '{}' failed its size or hash verification",
|
||||||
|
dest.display()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let done = completed.fetch_add(1, Ordering::Relaxed) + 1;
|
||||||
|
progress::set_action(format!("Downloading mods... {done}/{total}"));
|
||||||
|
Ok::<(), crate::net::NetError>(())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
while let Some(result) = tasks.join_next().await {
|
||||||
|
result??;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn safe_mrpack_path(path: &str) -> Result<PathBuf, crate::net::NetError> {
|
||||||
|
super::portable_pack_path(path)
|
||||||
|
.map(PathBuf::from)
|
||||||
|
.map_err(|error| {
|
||||||
|
crate::net::NetError::Parse(format!("Unsafe .mrpack file path '{path}': {error}"))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn owned_files(path: &Path) -> Result<Vec<PathBuf>, String> {
|
||||||
|
let index = parse_mrpack(path)?;
|
||||||
|
let mut files: Vec<_> = index
|
||||||
|
.client_files()
|
||||||
|
.map(|file| safe_mrpack_path(&file.path).map_err(|error| error.to_string()))
|
||||||
|
.collect::<Result<_, _>>()?;
|
||||||
|
files.extend(super::override_files(
|
||||||
|
path,
|
||||||
|
&["overrides", "client-overrides"],
|
||||||
|
)?);
|
||||||
|
Ok(files)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_mrpack_file(
|
||||||
|
path: &Path,
|
||||||
|
expected_size: u64,
|
||||||
|
expected_hashes: &HashMap<String, String>,
|
||||||
|
) -> Result<bool, crate::net::NetError> {
|
||||||
|
let fingerprint = fingerprint(path)?;
|
||||||
|
if fingerprint.size != expected_size {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
Ok(["sha512", "sha1"].into_iter().all(|algorithm| {
|
||||||
|
expected_hashes.get(algorithm).is_none_or(|expected| {
|
||||||
|
fingerprint
|
||||||
|
.hash(algorithm)
|
||||||
|
.is_some_and(|actual| actual.eq_ignore_ascii_case(expected))
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn seed_content_manifest(
|
||||||
|
index: &MrpackIndex,
|
||||||
|
paths: &InstancePaths,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
let mut manifest = ContentManifest::default();
|
||||||
|
for file in index.client_files() {
|
||||||
|
let relative_path = safe_mrpack_path(&file.path)?;
|
||||||
|
let Some(kind) = mrpack_content_kind(&relative_path) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some((project_id, version_id)) = file.downloads.iter().find_map(|url| {
|
||||||
|
let path = url.strip_prefix("https://cdn.modrinth.com/data/")?;
|
||||||
|
let (project_id, path) = path.split_once("/versions/")?;
|
||||||
|
let version_id = path.split('/').next()?;
|
||||||
|
(!project_id.is_empty() && !version_id.is_empty())
|
||||||
|
.then_some((project_id.to_owned(), version_id.to_owned()))
|
||||||
|
}) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(expected_sha512) = file.hashes.get("sha512") else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let file_fingerprint = fingerprint(&paths.minecraft().join(&relative_path))?;
|
||||||
|
if file_fingerprint
|
||||||
|
.hash("sha512")
|
||||||
|
.is_none_or(|actual| !actual.eq_ignore_ascii_case(expected_sha512))
|
||||||
|
{
|
||||||
|
tracing::warn!(
|
||||||
|
"Skipping stale Modrinth identity for '{}' because its downloaded hash changed",
|
||||||
|
file.path
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
manifest.upsert(ContentFileRecord {
|
||||||
|
relative_path,
|
||||||
|
kind,
|
||||||
|
enabled: true,
|
||||||
|
fingerprint: file_fingerprint,
|
||||||
|
resolution: Resolution::Resolved {
|
||||||
|
project: ProviderProject {
|
||||||
|
provider: "modrinth".to_owned(),
|
||||||
|
project_id,
|
||||||
|
version_id,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
provider_aliases: Vec::new(),
|
||||||
|
provider_checks: vec!["modrinth".to_owned()],
|
||||||
|
required_dependencies: Vec::new(),
|
||||||
|
automatic_dependency: false,
|
||||||
|
cleanup_eligible: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let seeded = manifest.files.len();
|
||||||
|
manifest.save(&paths.content_manifest())?;
|
||||||
|
tracing::debug!(
|
||||||
|
"Seeded {} exact Modrinth content record(s) from .mrpack '{}'",
|
||||||
|
seeded,
|
||||||
|
index.name
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mrpack_content_kind(path: &Path) -> Option<ContentKind> {
|
||||||
|
use std::path::Component;
|
||||||
|
|
||||||
|
if path
|
||||||
|
.components()
|
||||||
|
.any(|component| !matches!(component, Component::Normal(_)))
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let directory = path.components().next()?.as_os_str().to_str()?;
|
||||||
|
let name = path.file_name()?.to_str()?.to_ascii_lowercase();
|
||||||
|
match (directory, name.as_str()) {
|
||||||
|
("mods", name) if name.ends_with(".jar") => Some(ContentKind::Mod),
|
||||||
|
("resourcepacks", name) if name.ends_with(".zip") => Some(ContentKind::ResourcePack),
|
||||||
|
("shaderpacks", name) if name.ends_with(".zip") => Some(ContentKind::Shader),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extract_overrides(
|
||||||
|
mrpack_path: &Path,
|
||||||
|
minecraft_dir: &Path,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
|
progress::set_action("Extracting overrides...".to_string());
|
||||||
|
progress::set_sub_action(String::new());
|
||||||
|
|
||||||
|
super::archive::extract_overrides(
|
||||||
|
mrpack_path,
|
||||||
|
minecraft_dir,
|
||||||
|
&["overrides", "client-overrides"],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../tests/import/mrpack.rs"]
|
||||||
|
mod tests;
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,705 @@
|
|||||||
|
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
collections::{BTreeMap, HashSet},
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct JavaInstallation {
|
||||||
|
pub path: PathBuf,
|
||||||
|
pub version: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct JavaRuntime {
|
||||||
|
pub major_version: u32,
|
||||||
|
pub platform: crate::launch_profile::system::JavaPlatform,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn resolve_java_path(instance_java: Option<&str>) -> String {
|
||||||
|
let settings = crate::config::SETTINGS.read().clone();
|
||||||
|
let environment = merge_environment(&settings.defaults.environment, &BTreeMap::new());
|
||||||
|
resolve_java_path_in(
|
||||||
|
instance_java.or(settings.paths.effective_java_path()),
|
||||||
|
&std::env::current_dir().unwrap_or_default(),
|
||||||
|
&environment,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Command uses the platform's environment-key comparison, including Windows Unicode casing.
|
||||||
|
pub fn merge_environment(
|
||||||
|
global: &BTreeMap<String, String>,
|
||||||
|
instance: &BTreeMap<String, String>,
|
||||||
|
) -> BTreeMap<String, String> {
|
||||||
|
let mut command = std::process::Command::new("java");
|
||||||
|
command.envs(global).envs(instance);
|
||||||
|
command
|
||||||
|
.get_envs()
|
||||||
|
.map(|(name, value)| {
|
||||||
|
(
|
||||||
|
name.to_str()
|
||||||
|
.expect("environment names originate from strings")
|
||||||
|
.to_owned(),
|
||||||
|
value
|
||||||
|
.expect("only environment additions were configured")
|
||||||
|
.to_str()
|
||||||
|
.expect("environment values originate from strings")
|
||||||
|
.to_owned(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
// These lookups are for the ASCII variable names PATH, JAVA_HOME and JDK_HOME.
|
||||||
|
fn environment_value(
|
||||||
|
environment: &BTreeMap<String, String>,
|
||||||
|
name: &str,
|
||||||
|
) -> Option<std::ffi::OsString> {
|
||||||
|
environment
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.find(|(key, _)| {
|
||||||
|
if cfg!(windows) {
|
||||||
|
key.eq_ignore_ascii_case(name)
|
||||||
|
} else {
|
||||||
|
key.as_str() == name
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.map(|(_, value)| std::ffi::OsString::from(value))
|
||||||
|
.or_else(|| std::env::var_os(name))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resolve_java_path_in(
|
||||||
|
configured: Option<&str>,
|
||||||
|
cwd: &Path,
|
||||||
|
environment: &BTreeMap<String, String>,
|
||||||
|
) -> String {
|
||||||
|
let search_path = environment_value(environment, "PATH");
|
||||||
|
let find = |name: &str| {
|
||||||
|
if Path::new(name).components().count() > 1 {
|
||||||
|
return which::which_in(name, None::<&std::ffi::OsStr>, cwd).ok();
|
||||||
|
}
|
||||||
|
search_path.as_deref().and_then(|path| {
|
||||||
|
std::env::split_paths(path)
|
||||||
|
.filter(|directory| !cfg!(windows) || !directory.as_os_str().is_empty())
|
||||||
|
.find_map(|directory| {
|
||||||
|
which::which_in(
|
||||||
|
cwd.join(directory).join(name),
|
||||||
|
None::<&std::ffi::OsStr>,
|
||||||
|
cwd,
|
||||||
|
)
|
||||||
|
.ok()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
};
|
||||||
|
if let Some(configured) = configured.filter(|path| !path.is_empty()) {
|
||||||
|
return find(configured)
|
||||||
|
.map(|path| path.to_string_lossy().into_owned())
|
||||||
|
.unwrap_or_else(|| configured.to_owned());
|
||||||
|
}
|
||||||
|
if let Some(home) = environment_value(environment, "JAVA_HOME") {
|
||||||
|
let bin = cwd
|
||||||
|
.join(home)
|
||||||
|
.join("bin")
|
||||||
|
.join(if cfg!(windows) { "java.exe" } else { "java" });
|
||||||
|
if bin.is_file() {
|
||||||
|
return bin.to_string_lossy().into_owned();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
find("java")
|
||||||
|
.map(|path| path.to_string_lossy().into_owned())
|
||||||
|
.unwrap_or_else(|| "java".to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Probe the selected executable, rather than inferring its architecture from rmcl.
|
||||||
|
pub async fn probe_java(path: &Path) -> std::io::Result<JavaRuntime> {
|
||||||
|
let (cwd, environment) = default_probe_context()?;
|
||||||
|
probe_java_in(path, &cwd, &environment).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn probe_java_in(
|
||||||
|
path: &Path,
|
||||||
|
cwd: &Path,
|
||||||
|
environment: &BTreeMap<String, String>,
|
||||||
|
) -> std::io::Result<JavaRuntime> {
|
||||||
|
let output = java_version_output_in(path, cwd, environment).await?;
|
||||||
|
if !output.status.success() {
|
||||||
|
return Err(std::io::Error::other(format!(
|
||||||
|
"Java settings probe exited with {}",
|
||||||
|
output.status
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
parse_runtime_properties(&format!(
|
||||||
|
"{}\n{}",
|
||||||
|
String::from_utf8_lossy(&output.stdout),
|
||||||
|
String::from_utf8_lossy(&output.stderr)
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_probe_context() -> std::io::Result<(PathBuf, BTreeMap<String, String>)> {
|
||||||
|
Ok((
|
||||||
|
std::env::current_dir()?,
|
||||||
|
merge_environment(
|
||||||
|
&crate::config::SETTINGS.read().defaults.environment,
|
||||||
|
&BTreeMap::new(),
|
||||||
|
),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_runtime_properties(output: &str) -> std::io::Result<JavaRuntime> {
|
||||||
|
let property = |name: &str| -> std::io::Result<&str> {
|
||||||
|
output
|
||||||
|
.lines()
|
||||||
|
.filter_map(|line| line.trim().split_once(" = "))
|
||||||
|
.find_map(|(key, value)| (key == name).then_some(value.trim()))
|
||||||
|
.filter(|value| !value.is_empty())
|
||||||
|
.ok_or_else(|| {
|
||||||
|
std::io::Error::new(
|
||||||
|
std::io::ErrorKind::InvalidData,
|
||||||
|
format!("Java probe did not report {name}"),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let major_version = parse_java_major_version(property("java.version")?).ok_or_else(|| {
|
||||||
|
std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid Java java.version")
|
||||||
|
})?;
|
||||||
|
Ok(JavaRuntime {
|
||||||
|
major_version,
|
||||||
|
platform: crate::launch_profile::system::JavaPlatform::from_java_properties(
|
||||||
|
property("os.name")?,
|
||||||
|
property("os.arch")?,
|
||||||
|
property("sun.arch.data.model")?,
|
||||||
|
property("os.version")?,
|
||||||
|
)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn detect_java_path() -> String {
|
||||||
|
let Ok((cwd, environment)) = default_probe_context() else {
|
||||||
|
return "java".to_owned();
|
||||||
|
};
|
||||||
|
resolve_java_path_in(None, &cwd, &environment)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finds Java executables in the environment and the conventional installation
|
||||||
|
/// directories for the current platform. The search is deliberately bounded so
|
||||||
|
/// opening the selector never walks an entire drive.
|
||||||
|
#[must_use]
|
||||||
|
pub fn discover_installations() -> Vec<JavaInstallation> {
|
||||||
|
let Ok((cwd, environment)) = default_probe_context() else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
discover_installations_in(&cwd, &environment)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn discover_installations_in(
|
||||||
|
cwd: &Path,
|
||||||
|
environment: &BTreeMap<String, String>,
|
||||||
|
) -> Vec<JavaInstallation> {
|
||||||
|
let mut candidates = Vec::new();
|
||||||
|
for variable in ["JAVA_HOME", "JDK_HOME"] {
|
||||||
|
if let Some(java_home) = environment_value(environment, variable) {
|
||||||
|
add_java_home(&cwd.join(java_home), &mut candidates);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let search_path = environment_value(environment, "PATH");
|
||||||
|
if let Ok(path) = which::which_in(
|
||||||
|
resolve_java_path_in(None, cwd, environment),
|
||||||
|
None::<&std::ffi::OsStr>,
|
||||||
|
cwd,
|
||||||
|
) {
|
||||||
|
candidates.push(path);
|
||||||
|
}
|
||||||
|
if let Some(path) = search_path {
|
||||||
|
for directory in std::env::split_paths(&path) {
|
||||||
|
let executable = if cfg!(target_os = "windows") {
|
||||||
|
"java.exe"
|
||||||
|
} else {
|
||||||
|
"java"
|
||||||
|
};
|
||||||
|
candidates.push(cwd.join(directory).join(executable));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for root in java_roots() {
|
||||||
|
collect_java_executables(&root, 3, &mut candidates);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut seen = HashSet::new();
|
||||||
|
let mut installations = candidates
|
||||||
|
.into_iter()
|
||||||
|
.filter(|path| path.is_file())
|
||||||
|
.filter_map(|path| {
|
||||||
|
let identity = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
|
||||||
|
seen.insert(identity)
|
||||||
|
.then(|| inspect_installation_in(&path, cwd, environment))
|
||||||
|
.flatten()
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
installations.sort_by(|a, b| {
|
||||||
|
java_major(b.version.as_deref())
|
||||||
|
.cmp(&java_major(a.version.as_deref()))
|
||||||
|
.then_with(|| a.path.cmp(&b.path))
|
||||||
|
});
|
||||||
|
installations
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the version reported by one Java executable.
|
||||||
|
#[must_use]
|
||||||
|
pub fn inspect_installation(path: &Path) -> Option<JavaInstallation> {
|
||||||
|
let (cwd, environment) = default_probe_context().ok()?;
|
||||||
|
inspect_installation_in(path, &cwd, &environment)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn inspect_installation_in(
|
||||||
|
path: &Path,
|
||||||
|
cwd: &Path,
|
||||||
|
environment: &BTreeMap<String, String>,
|
||||||
|
) -> Option<JavaInstallation> {
|
||||||
|
let resolved = path
|
||||||
|
.to_str()
|
||||||
|
.map(|path| resolve_java_path_in(Some(path), cwd, environment));
|
||||||
|
let path = resolved.as_deref().map_or(path, Path::new);
|
||||||
|
path.is_file().then(|| JavaInstallation {
|
||||||
|
version: java_version_in(path, cwd, environment),
|
||||||
|
path: path.to_path_buf(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn load_installation_cache(path: &Path) -> Option<Vec<JavaInstallation>> {
|
||||||
|
let (cwd, environment) = default_probe_context().ok()?;
|
||||||
|
load_installation_cache_in(path, &cwd, &environment)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct InstallationCache {
|
||||||
|
context: String,
|
||||||
|
installations: Vec<JavaInstallation>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn probe_context_key(cwd: &Path, environment: &BTreeMap<String, String>) -> String {
|
||||||
|
use sha2::Digest;
|
||||||
|
let mut hash = sha2::Sha256::new();
|
||||||
|
let mut add = |bytes: &[u8]| {
|
||||||
|
hash.update((bytes.len() as u64).to_le_bytes());
|
||||||
|
hash.update(bytes);
|
||||||
|
};
|
||||||
|
add(cwd.as_os_str().as_encoded_bytes());
|
||||||
|
let mut ambient: Vec<_> = std::env::vars_os().collect();
|
||||||
|
ambient.sort();
|
||||||
|
for (key, value) in &ambient {
|
||||||
|
add(key.as_encoded_bytes());
|
||||||
|
add(value.as_encoded_bytes());
|
||||||
|
}
|
||||||
|
// Store a digest only; configured environment values may contain credentials.
|
||||||
|
for (key, value) in merge_environment(environment, &BTreeMap::new()) {
|
||||||
|
add(key.as_bytes());
|
||||||
|
add(value.as_bytes());
|
||||||
|
}
|
||||||
|
format!("{:x}", hash.finalize())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn load_installation_cache_in(
|
||||||
|
path: &Path,
|
||||||
|
cwd: &Path,
|
||||||
|
environment: &BTreeMap<String, String>,
|
||||||
|
) -> Option<Vec<JavaInstallation>> {
|
||||||
|
let mut cache: InstallationCache = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
|
||||||
|
if cache.context != probe_context_key(cwd, environment) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
cache
|
||||||
|
.installations
|
||||||
|
.retain(|installation| installation.path.is_file());
|
||||||
|
(!cache.installations.is_empty()).then_some(cache.installations)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save_installation_cache(
|
||||||
|
path: &Path,
|
||||||
|
installations: &[JavaInstallation],
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
let (cwd, environment) = default_probe_context()?;
|
||||||
|
save_installation_cache_in(path, installations, &cwd, &environment)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save_installation_cache_in(
|
||||||
|
path: &Path,
|
||||||
|
installations: &[JavaInstallation],
|
||||||
|
cwd: &Path,
|
||||||
|
environment: &BTreeMap<String, String>,
|
||||||
|
) -> std::io::Result<()> {
|
||||||
|
let cache = InstallationCache {
|
||||||
|
context: probe_context_key(cwd, environment),
|
||||||
|
installations: installations.to_vec(),
|
||||||
|
};
|
||||||
|
let bytes = serde_json::to_vec_pretty(&cache).map_err(std::io::Error::other)?;
|
||||||
|
crate::storage::write_atomic(path, &bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn java_roots() -> Vec<PathBuf> {
|
||||||
|
let mut roots = Vec::new();
|
||||||
|
if cfg!(target_os = "windows") {
|
||||||
|
for variable in ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"] {
|
||||||
|
if let Some(root) = std::env::var_os(variable) {
|
||||||
|
let root = PathBuf::from(root);
|
||||||
|
roots.extend([
|
||||||
|
root.join("Java"),
|
||||||
|
root.join("Eclipse Adoptium"),
|
||||||
|
root.join("Programs/Eclipse Adoptium"),
|
||||||
|
root.join("Programs/Java"),
|
||||||
|
root.join("Microsoft"),
|
||||||
|
root.join("BellSoft"),
|
||||||
|
root.join("Zulu"),
|
||||||
|
root.join("Amazon Corretto"),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if cfg!(target_os = "macos") {
|
||||||
|
roots.push(PathBuf::from("/Library/Java/JavaVirtualMachines"));
|
||||||
|
for prefix in ["/opt/homebrew/opt", "/usr/local/opt"] {
|
||||||
|
for formula in [
|
||||||
|
"openjdk",
|
||||||
|
"openjdk@8",
|
||||||
|
"openjdk@11",
|
||||||
|
"openjdk@17",
|
||||||
|
"openjdk@21",
|
||||||
|
] {
|
||||||
|
roots.push(PathBuf::from(prefix).join(formula));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(home) = dirs::home_dir() {
|
||||||
|
roots.push(home.join("Library/Java/JavaVirtualMachines"));
|
||||||
|
roots.push(home.join(".sdkman/candidates/java"));
|
||||||
|
roots.push(home.join(".asdf/installs/java"));
|
||||||
|
roots.push(home.join(".local/share/mise/installs/java"));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
roots.extend([
|
||||||
|
PathBuf::from("/usr/lib/jvm"),
|
||||||
|
PathBuf::from("/usr/java"),
|
||||||
|
PathBuf::from("/opt/java"),
|
||||||
|
PathBuf::from("/opt/jdk"),
|
||||||
|
]);
|
||||||
|
if let Some(home) = dirs::home_dir() {
|
||||||
|
roots.push(home.join(".sdkman/candidates/java"));
|
||||||
|
roots.push(home.join(".jdks"));
|
||||||
|
roots.push(home.join(".asdf/installs/java"));
|
||||||
|
roots.push(home.join(".local/share/mise/installs/java"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
roots
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collect_java_executables(directory: &Path, depth: usize, candidates: &mut Vec<PathBuf>) {
|
||||||
|
if depth == 0 || !directory.is_dir() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
add_java_home(directory, candidates);
|
||||||
|
if let Ok(entries) = std::fs::read_dir(directory) {
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let path = entry.path();
|
||||||
|
if path.is_dir() {
|
||||||
|
collect_java_executables(&path, depth - 1, candidates);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_java_home(home: &Path, candidates: &mut Vec<PathBuf>) {
|
||||||
|
let executable = if cfg!(target_os = "windows") {
|
||||||
|
"java.exe"
|
||||||
|
} else {
|
||||||
|
"java"
|
||||||
|
};
|
||||||
|
for path in [
|
||||||
|
home.join("bin").join(executable),
|
||||||
|
home.join("Contents/Home/bin").join(executable),
|
||||||
|
] {
|
||||||
|
if path.is_file() {
|
||||||
|
candidates.push(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn java_version_in(
|
||||||
|
path: &Path,
|
||||||
|
cwd: &Path,
|
||||||
|
environment: &BTreeMap<String, String>,
|
||||||
|
) -> Option<String> {
|
||||||
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.ok()?;
|
||||||
|
let output = runtime
|
||||||
|
.block_on(java_version_output_in(path, cwd, environment))
|
||||||
|
.ok()?;
|
||||||
|
if !output.status.success() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let text = format!(
|
||||||
|
"{}{}",
|
||||||
|
String::from_utf8_lossy(&output.stderr),
|
||||||
|
String::from_utf8_lossy(&output.stdout)
|
||||||
|
);
|
||||||
|
parse_java_version(&text)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn java_version_output_in(
|
||||||
|
path: &Path,
|
||||||
|
cwd: &Path,
|
||||||
|
environment: &BTreeMap<String, String>,
|
||||||
|
) -> std::io::Result<std::process::Output> {
|
||||||
|
let java = path
|
||||||
|
.to_str()
|
||||||
|
.map(|path| resolve_java_path_in(Some(path), cwd, environment));
|
||||||
|
let mut command = tokio::process::Command::new(java.as_deref().map_or(path, Path::new));
|
||||||
|
command
|
||||||
|
.args(["-XshowSettings:properties", "-version"])
|
||||||
|
.current_dir(cwd)
|
||||||
|
.envs(environment)
|
||||||
|
.kill_on_drop(true);
|
||||||
|
tokio::time::timeout(std::time::Duration::from_secs(10), command.output())
|
||||||
|
.await
|
||||||
|
.map_err(|_| {
|
||||||
|
std::io::Error::new(std::io::ErrorKind::TimedOut, "Java version check timed out")
|
||||||
|
})?
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_java_version(output: &str) -> Option<String> {
|
||||||
|
output.lines().find_map(|line| {
|
||||||
|
let line = line.trim();
|
||||||
|
if let Some(version) = line.strip_prefix("java.version = ") {
|
||||||
|
return Some(version.trim().to_owned());
|
||||||
|
}
|
||||||
|
if !line.starts_with("java version ") && !line.starts_with("openjdk version ") {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
line.split_once('"')
|
||||||
|
.and_then(|(_, rest)| rest.split_once('"'))
|
||||||
|
.map(|(version, _)| version.to_owned())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn java_major(version: Option<&str>) -> u32 {
|
||||||
|
let Some(version) = version else {
|
||||||
|
return 0;
|
||||||
|
};
|
||||||
|
let parts = version
|
||||||
|
.split(|character: char| !character.is_ascii_digit())
|
||||||
|
.filter(|part| !part.is_empty())
|
||||||
|
.filter_map(|part| part.parse::<u32>().ok())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
match parts.as_slice() {
|
||||||
|
[1, legacy_major, ..] => *legacy_major,
|
||||||
|
[major, ..] => *major,
|
||||||
|
[] => 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn parse_java_major_version(output: &str) -> Option<u32> {
|
||||||
|
if let Some(version) = parse_java_version(output) {
|
||||||
|
return Some(java_major(Some(&version))).filter(|major| *major > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
let start = output.find(|character: char| character.is_ascii_digit())?;
|
||||||
|
Some(java_major(Some(&output[start..]))).filter(|major| *major > 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_modern_and_legacy_java_versions() {
|
||||||
|
assert_eq!(
|
||||||
|
parse_java_version("openjdk version \"21.0.4\" 2024-07-16"),
|
||||||
|
Some("21.0.4".to_owned())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
parse_java_version("java version \"1.8.0_412\""),
|
||||||
|
Some("1.8.0_412".to_owned())
|
||||||
|
);
|
||||||
|
assert_eq!(java_major(Some("21.0.4")), 21);
|
||||||
|
assert_eq!(java_major(Some("1.8.0_412")), 8);
|
||||||
|
assert_eq!(java_major(Some("21-ea")), 21);
|
||||||
|
assert_eq!(
|
||||||
|
parse_java_major_version("openjdk version \"21-ea\" 2026-03-17"),
|
||||||
|
Some(21)
|
||||||
|
);
|
||||||
|
assert_eq!(parse_java_major_version("openjdk 17"), Some(17));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn installation_cache_round_trips_existing_paths() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let executable = temp.path().join("java");
|
||||||
|
std::fs::write(&executable, b"java").unwrap();
|
||||||
|
let cache = temp.path().join("cache/java/installations.json");
|
||||||
|
let installations = vec![JavaInstallation {
|
||||||
|
path: executable.clone(),
|
||||||
|
version: Some("25.0.1".to_owned()),
|
||||||
|
}];
|
||||||
|
|
||||||
|
save_installation_cache(&cache, &installations).unwrap();
|
||||||
|
assert_eq!(load_installation_cache(&cache), Some(installations));
|
||||||
|
|
||||||
|
std::fs::remove_file(executable).unwrap();
|
||||||
|
assert_eq!(load_installation_cache(&cache), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn runtime_properties_report_selected_java_architecture_and_os_version() {
|
||||||
|
for (os, arch, bits, name, normalized) in [
|
||||||
|
("Windows 10", "x86", "32", "windows", "x86"),
|
||||||
|
("Windows 11", "amd64", "64", "windows", "x86_64"),
|
||||||
|
("Mac OS X", "x86_64", "64", "osx", "x86_64"),
|
||||||
|
("Mac OS X", "aarch64", "64", "osx", "arm64"),
|
||||||
|
("Linux", "amd64", "64", "linux", "x86_64"),
|
||||||
|
] {
|
||||||
|
let properties = format!(
|
||||||
|
"Property settings:\r\n java.version = 1.8.0_412\r\n os.name = {os}\r\n os.arch = {arch}\r\n sun.arch.data.model = {bits}\r\n os.version = 10.0\r\n"
|
||||||
|
);
|
||||||
|
let runtime = parse_runtime_properties(&properties).unwrap();
|
||||||
|
assert_eq!(runtime.major_version, 8);
|
||||||
|
assert_eq!(runtime.platform.os_name, name);
|
||||||
|
assert_eq!(runtime.platform.arch, normalized);
|
||||||
|
assert_eq!(runtime.platform.bitness.to_string(), bits);
|
||||||
|
assert_eq!(runtime.platform.os_version, "10.0");
|
||||||
|
assert!(
|
||||||
|
parse_runtime_properties(&properties.replace("sun.arch.data.model =", "unknown ="))
|
||||||
|
.unwrap_err()
|
||||||
|
.to_string()
|
||||||
|
.contains("sun.arch.data.model")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn incomplete_runtime_properties_do_not_fall_back_to_the_launcher_architecture() {
|
||||||
|
assert!(parse_runtime_properties("openjdk version \"25.0.1\"").is_err());
|
||||||
|
assert!(
|
||||||
|
crate::launch_profile::system::JavaPlatform::from_java_properties(
|
||||||
|
"Windows 10",
|
||||||
|
"../x86",
|
||||||
|
"32",
|
||||||
|
"10.0"
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
crate::launch_profile::system::JavaPlatform::from_java_properties(
|
||||||
|
"Mac OS X", "aarch64", "unknown", "15.0"
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn relative_java_search_paths_are_bound_to_the_execution_directory() {
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let temp =
|
||||||
|
tempfile::tempdir_in(Path::new(env!("CARGO_MANIFEST_DIR")).join("target")).unwrap();
|
||||||
|
let cwd = temp.path().join("minecraft");
|
||||||
|
let java = cwd.join("bin/java");
|
||||||
|
std::fs::create_dir_all(java.parent().unwrap()).unwrap();
|
||||||
|
std::fs::write(&java, "#!/bin/sh\nexit 0\n").unwrap();
|
||||||
|
std::fs::set_permissions(&java, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||||
|
let environment = BTreeMap::from([
|
||||||
|
("PATH".to_owned(), "bin".to_owned()),
|
||||||
|
("JAVA_HOME".to_owned(), "missing-home".to_owned()),
|
||||||
|
]);
|
||||||
|
for configured in [None, Some("java"), Some("bin/java")] {
|
||||||
|
assert_eq!(
|
||||||
|
Path::new(&resolve_java_path_in(configured, &cwd, &environment)),
|
||||||
|
java
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn installed_jdk_reports_runtime_properties_on_the_native_platform() {
|
||||||
|
let cwd = std::env::current_dir().unwrap();
|
||||||
|
let environment = BTreeMap::new();
|
||||||
|
let java = resolve_java_path_in(None, &cwd, &environment);
|
||||||
|
let runtime = probe_java_in(Path::new(&java), &cwd, &environment)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(runtime.major_version >= 8);
|
||||||
|
assert_eq!(
|
||||||
|
runtime.platform.os_name,
|
||||||
|
crate::launch_profile::system::mojang_os_name()
|
||||||
|
);
|
||||||
|
assert!(matches!(runtime.platform.bitness, 32 | 64));
|
||||||
|
assert!(!runtime.platform.os_version.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn environment_overrides_follow_native_case_rules_and_are_deterministic() {
|
||||||
|
let global = BTreeMap::from([
|
||||||
|
("PATH".into(), "global".into()),
|
||||||
|
("TÊST".into(), "global".into()),
|
||||||
|
]);
|
||||||
|
let instance = BTreeMap::from([
|
||||||
|
("PATH".into(), "first".into()),
|
||||||
|
("path".into(), "last".into()),
|
||||||
|
("têst".into(), "instance".into()),
|
||||||
|
]);
|
||||||
|
let merged = merge_environment(&global, &instance);
|
||||||
|
assert_eq!(
|
||||||
|
environment_value(&instance, "PATH").unwrap(),
|
||||||
|
std::ffi::OsString::from(if cfg!(windows) { "last" } else { "first" })
|
||||||
|
);
|
||||||
|
if cfg!(windows) {
|
||||||
|
assert_eq!(merged.len(), 2);
|
||||||
|
assert_eq!(merged["PATH"], "last");
|
||||||
|
assert_eq!(merged["TÊST"], "instance");
|
||||||
|
} else {
|
||||||
|
assert_eq!(merged.len(), 4);
|
||||||
|
assert_eq!(merged["PATH"], "first");
|
||||||
|
assert_eq!(merged["path"], "last");
|
||||||
|
assert_eq!(merged["TÊST"], "global");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn installation_cache_is_bound_to_the_probe_context_without_storing_environment_values() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let executable = temp.path().join("java");
|
||||||
|
std::fs::write(&executable, b"java").unwrap();
|
||||||
|
let cache = temp.path().join("installations.json");
|
||||||
|
let installations = vec![JavaInstallation {
|
||||||
|
path: executable,
|
||||||
|
version: Some("25.0.1".into()),
|
||||||
|
}];
|
||||||
|
let environment =
|
||||||
|
BTreeMap::from([("PRIVATE_TEST_VALUE".into(), "sensitive-cache-value".into())]);
|
||||||
|
save_installation_cache_in(&cache, &installations, temp.path(), &environment).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
load_installation_cache_in(&cache, temp.path(), &environment),
|
||||||
|
Some(installations)
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!std::fs::read_to_string(&cache)
|
||||||
|
.unwrap()
|
||||||
|
.contains("sensitive-cache-value")
|
||||||
|
);
|
||||||
|
let changed = BTreeMap::from([("PRIVATE_TEST_VALUE".into(), "another-value".into())]);
|
||||||
|
assert!(load_installation_cache_in(&cache, temp.path(), &changed).is_none());
|
||||||
|
assert!(
|
||||||
|
load_installation_cache_in(&cache, &temp.path().join("other-cwd"), &environment)
|
||||||
|
.is_none()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
Loaded 100 of 288 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user