14 Commits

Author SHA1 Message Date
d42b9aae09 Adds task.
Some checks failed
Java CI with Gradle / build (push) Has been cancelled
Java CI with Gradle / dependency-submission (push) Has been cancelled
2026-09-26 23:44:09 -07:00
f8dd873189 Fixes modrinth publish script. 2026-09-26 23:44:09 -07:00
Tom
e2a4d57dd9 Upgrade actions and add project version extraction
Updated Gradle CI workflow to use newer action versions and added project version extraction step.
2026-09-26 23:07:33 -07:00
Tom
b8d6819cd3 Upgrade GitHub Actions to version 5 for Gradle setup 2026-09-26 22:54:39 -07:00
Tom
46dea4f781 Adds Github workflow. 2026-09-26 22:40:58 -07:00
50a66a254c Updates modrinth info. 2026-09-26 19:52:05 -07:00
4d142ad9d1 Adds a task to switch versioning in gradle. 2026-09-26 19:33:01 -07:00
60e4523ff8 Add persistent score archives 2026-09-26 18:38:41 -07:00
0e84cb1b0f Add high-score runs for score buckets 2026-09-26 18:26:29 -07:00
b165d67118 Notify players when score buckets change 2026-09-26 18:20:54 -07:00
e4bebd3908 Add configurable score change reporting 2026-09-26 18:20:10 -07:00
1773361716 Add configurable score buckets 2026-09-26 18:18:00 -07:00
46c93685ad Persist scores between server launches 2026-09-26 18:11:59 -07:00
6100865cb0 Adds some tasks to TODO.md. 2026-09-26 18:08:56 -07:00
23 changed files with 1735 additions and 140 deletions

View File

@@ -1,9 +1,24 @@
# Dev-server config for this project's tools/ scripts. # Configuration for tools/*.sh. Values are read as KEY=value data, not executed.
# Plain KEY=value only (no shell expansion). Environment variables take precedence. # Unquoted values may contain spaces; matching outer quotes are removed.
# Paper server
PAPER_VERSION=26.2 PAPER_VERSION=26.2
PAPER_BUILD=129 PAPER_BUILD=129
PAPER_USER_AGENT="majinnaibu-plugin-dev/1.0 (https://github.com/majinnaibu)"
JAVA_OPTS="-Xms2G -Xmx2G"
STOP_TIMEOUT=60
MINECRAFT_SERVER_JAR=paper-26.2-129.jar MINECRAFT_SERVER_JAR=paper-26.2-129.jar
# Relative paths are resolved from this directory; ~/ is expanded. # Relative paths are resolved from the project root; ~/ is expanded.
MINECRAFT_SERVER_PATH=./server MINECRAFT_SERVER_PATH=./server
MINECRAFT_BACKUP_PATH=./backups MINECRAFT_BACKUP_PATH=./backups
# Modrinth publishing
# Release version is read from Gradle and checked against the jar's plugin.yml.
MODRINTH_TOKEN=
MODRINTH_PROJECT_ID=5NYwxysp
MODRINTH_CHANGELOG="Release 0.2.2"
MODRINTH_GAME_VERSIONS=1.21,1.21.1,1.21.2,1.21.3,1.21.4,1.21.5,1.21.6,1.21.7
MODRINTH_LOADERS=paper
MODRINTH_VERSION_TYPE=
MODRINTH_DEPENDENCIES=
MODRINTH_FILE=

69
.github/workflows/gradle.yml vendored Normal file
View File

@@ -0,0 +1,69 @@
name: Java CI with Gradle
on:
push:
branches: [ "develop" ]
pull_request:
branches: [ "develop" ]
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v7
- name: Set up JDK 25
uses: actions/setup-java@v6
with:
java-version: '25'
distribution: 'temurin'
- name: Setup Gradle 9.8.0
uses: gradle/actions/setup-gradle@v5
with:
gradle-version: '9.8.0'
cache-read-only: ${{ github.ref != 'refs/heads/develop' }}
- name: Build with Gradle Wrapper
run: ./tools/build-plugin.sh
- name: Extract Project Version
id: project_info
run: |
VERSION=$(./gradlew properties --no-daemon -q | awk -F ': ' '$1 == "version" {print $2}')
echo "version=$VERSION" >> $GITHUB_OUTPUT
- name: Upload Plugin Artifact
uses: actions/upload-artifact@v7
with:
name: ScoreKeeper-${{ steps.project_info.outputs.version }}
path: build/libs/*.jar
if-no-files-found: error
retention-days: 14
dependency-submission:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v7
- name: Set up JDK 25
uses: actions/setup-java@v6
with:
java-version: '25'
distribution: 'temurin'
- name: Setup Gradle 9.8.0
uses: gradle/actions/setup-gradle@v5
with:
gradle-version: '9.8.0'
- name: Generate and submit dependency graph
uses: gradle/actions/dependency-submission@v5
with:
include-configurations: '^(compileClasspath|runtimeClasspath)$'

49
Modrinth-Description.md Normal file
View File

@@ -0,0 +1,49 @@
**ScoreKeeper Plugin**
ScoreKeeper tracks player scores in configurable buckets. Use it for event points, competitions, or other server-side scoring systems, and integrate it with other plugins through the public API.
## Commands
Players can omit an optional player name to target themselves. Console and RCON must provide a player name for score get/add/subtract/reset commands.
* `/score-get [playerName]` - Displays the target player's score in their active bucket.
* `/score-add <amount>` - Adds an amount to your score in your active bucket.
* `/score-add <playerName> <amount>` - Adds an amount to the target player's score.
* `/score-subtract <amount>` - Subtracts an amount from your score in your active bucket.
* `/score-subtract <playerName> <amount>` - Subtracts an amount from the target player's score.
* `/score-reset [playerName]` - Resets the target player's active-bucket score to that bucket's initial value.
* `/score-archive` - Archives and resets your score in your active bucket.
* `/score-archive <playerName>` - Archives and resets the target player's score in their active bucket.
* `/score-archive all` - Archives and resets scores in every bucket.
* `/score-archive bucket <bucketId>` - Archives and resets every score in one bucket.
* `/score-archive-list` - Lists saved archive IDs, newest first.
* `/score-archive-list <archiveId>` - Displays the saved scores in one archive.
* `/score-bucket` - Displays your active bucket.
* `/score-bucket <bucketId>` - Switches your active bucket.
* `/score-bucket create <id> <singular> <plural> <initialValue> [reporting]` - Creates a bucket. Reporting can be `admin`, `global`, `player`, or `none` (default).
* `/score-bucket <playerName> <bucketId>` - Switches a player's active bucket.
* `/score-bucket all <bucketId>` - Changes the server's default bucket and clears individual bucket assignments.
* `/score-run start <bucketId> <topN> <reset:true|false> target <score>` - Starts a run that ends when a score reaches the target.
* `/score-run start <bucketId> <topN> <reset:true|false> duration <time>` - Starts a timed run. Use a positive number and lowercase `s`, `m`, `h`, `d`, or `w`, such as `4h`.
* `/score-run start <bucketId> <topN> <reset:true|false> until-disabled` - Starts a run with no automatic end.
* `/score-run stop <bucketId>` - Ends an active run.
## Permissions
The `scorekeeper.admin` permission (default: operators) is required for archive commands, bucket creation/administration, and high-score run management. Score get/add/subtract/reset and archive-list commands currently have no permission checks; add, subtract, and reset can target any online player.
## Features
* Create score buckets with custom singular/plural labels, initial values, and reporting policies.
* Reporting can notify operators/admins, everyone online, only the scored player, or nobody.
* Start target-score, timed, or until-disabled high-score runs with configurable top-N standings and optional score resets.
* Archive player, bucket, or all-bucket scores; archived scores reset to their bucket's initial value.
* Persist bucket definitions, assignments, scores, active runs, and archives in the plugin's data folder.
## API
Other plugins can create buckets with `createBucket(id, singular, plural, initialValue, reporting)`, use bucket-aware score methods, and start or stop high-score runs with `startTargetScoreRun`, `startTimedScoreRun`, `startUntilDisabledScoreRun`, and `stopHighScoreRun`.
## Compatibility
Built for Paper and uses Bukkit and Adventure APIs.

13
Modrinth.json Normal file
View File

@@ -0,0 +1,13 @@
{
"name": "Score Keeper",
"url": "https://modrinth.com/plugin/scorekeeper",
"summary": "Track player scores in configurable buckets with custom reporting, high-score runs, and archives. Includes in-game commands and an API for other plugins.",
"visibility": "public",
"links": {
"issueTracker": "https://github.com/headhunter45/ScoreKeeper/issues",
"sourceCode": "https://github.com/headhunter45/ScoreKeeper",
"wikiPage": null,
"discordInvite": null,
"donationLinks": []
}
}

View File

@@ -27,9 +27,9 @@ and scoring formulas are all **future scope**. See §4 for the gap between *what
| Runtime target | Paper 1.21.7 (Bukkit + Adventure APIs) | | Runtime target | Paper 1.21.7 (Bukkit + Adventure APIs) |
| Build tool | Gradle 8.14.3 (`gradlew`) | | Build tool | Gradle 8.14.3 (`gradlew`) |
| Linting | Spotless (`googleJavaFormat()` + license header from `config/license-header.txt`) | | Linting | Spotless (`googleJavaFormat()` + license header from `config/license-header.txt`) |
| Release | `net.researchgate.release` plugin; tags `v$version`; rejects snapshot deps except paper-api | | Versioning | `org.danilopianini.git-sensitive-semantic-versioning`; minimum version `0.2.1`; reads `vX.Y.Z` tags |
| External deps | **None at runtime.** `paper-api:1.21.7-R0.1-SNAPSHOT` is `compileOnly` only. | | External deps | **None at runtime.** `paper-api:1.21.7-R0.1-SNAPSHOT` is `compileOnly` only. |
| CI/release entry point | `./gradlew spotlessCheck build` then `./gradlew release` | | CI/release entry point | Run `./gradlew spotlessCheck build`, tag the release commit (for example, `git tag -a v0.2.2 -m "Release v0.2.2"`), then rebuild to produce the stable release artifact |
### Build quickly ### Build quickly

View File

@@ -4,20 +4,41 @@
### Commands ### Commands
* `/score-get [playerName]` - Displays the player's score. For commands with an optional player name, players can omit it to target themselves. Console and RCON must provide a player name for score get/add/subtract/reset commands.
* `/score-add [playerName] <amount>` - Add amount points to the player's score.
* `/score-subtract [playerName] <amount>` - Subtracts amount points from the player's score.
* `/score-reset [playerName]` - Resets the player's score to 0.
* `/score-archive [playerName]` - Saves the player's score to a "High Scores" table and resets their current score to 0.
NOTES: * `/score-get [playerName]` - Displays the target player's score in their active bucket.
* All commands will use the executing player in place of [playerName] if it is omitted. * `/score-add <amount>` - Adds an amount to your score in your active bucket.
* Permissions support is coming AFTER I get archive to work. * `/score-add <playerName> <amount>` - Adds an amount to the target player's score.
* The commands aside from get are intended for admins and whatnot as some other plugin should be using the methods instead of letting player's execute commands. * `/score-subtract <amount>` - Subtracts an amount from your score in your active bucket.
* `/score-subtract <playerName> <amount>` - Subtracts an amount from the target player's score.
* `/score-reset [playerName]` - Resets the target player's score in their active bucket to that bucket's initial value.
* `/score-archive` - Archives and resets your score in your active bucket.
* `/score-archive <playerName>` - Archives and resets the target player's score in their active bucket.
* `/score-archive all` - Archives and resets scores in every bucket.
* `/score-archive bucket <bucketId>` - Archives and resets every score in one bucket.
* `/score-archive-list` - Lists saved archive IDs, newest first.
* `/score-archive-list <archiveId>` - Displays the saved scores in one archive.
* `/score-bucket` - Displays your active bucket.
* `/score-bucket <bucketId>` - Switches your active bucket.
* `/score-bucket create <id> <singular> <plural> <initialValue> [reporting]` - Creates a bucket. Reporting is `admin`, `global`, `player`, or `none` and defaults to `none`.
* `/score-bucket <playerName> <bucketId>` - Switches a player's active bucket.
* `/score-bucket all <bucketId>` - Changes the server's default bucket and clears individual bucket assignments.
* `/score-run start <bucketId> <topN> <reset:true|false> target <score>` - Starts a run that ends when a score reaches the target.
* `/score-run start <bucketId> <topN> <reset:true|false> duration <time>` - Starts a timed run. Use a positive number followed by lowercase `s`, `m`, `h`, `d`, or `w` (for example, `4h`).
* `/score-run start <bucketId> <topN> <reset:true|false> until-disabled` - Starts a run with no automatic end.
* `/score-run stop <bucketId>` - Ends an active run.
The `scorekeeper.admin` permission (default: operators) is required for archive commands, bucket creation/administration, and high-score run management. Score get/add/subtract/reset and archive-list commands currently have no permission checks; add, subtract, and reset can target any online player.
When a player's active bucket changes, they are told the bucket name and their current score with its singular or plural unit.
Bucket reporting defaults to `none`; `admin` notifies operators and score admins, `global` notifies all online players, and `player` notifies only the scored player. Other plugins can create buckets with `createBucket(id, singular, plural, initialValue, reporting)` and use the bucket-aware score methods. Existing score methods operate on the player's active bucket. Bucket definitions, reporting policies, assignments, and scores are saved in `plugins/ScoreKeeper/scores.yml`; archives are saved separately in `plugins/ScoreKeeper/archives.yml`.
Other plugins can start runs with `startTargetScoreRun`, `startTimedScoreRun`, or `startUntilDisabledScoreRun`, and end one with `stopHighScoreRun`. During a run, players receive their own score changes, while changes by current top-`n` players are reported globally. Finished runs publish a deterministic score-ordered table and each online player's place; reset runs restore the pre-run bucket scores.
## Development ## Development
See [CONTRIBUTING.md](CONTRIBUTING.md) for development environment setup instructions. See [CONTRIBUTING.md](CONTRIBUTING.md) for development environment setup instructions.
Tooling note: Tooling note:
* Gradle is configured with Java Toolchains and will automatically download a Java 21 JDK when needed during builds. * Gradle is configured with Java Toolchains and will automatically download an appropriate JDK when needed during builds.

32
TODO.md
View File

@@ -1,17 +1,17 @@
# Migration TODOs for Paper Modernization ## Tasks
- [x] Switch all player score storage to use UUID instead of Player as the key | ID | Status | Title |
- [x] Update logger usage to use getLogger() from JavaPlugin |:-----:|:--------:|:------|
- [x] Remove or modernize any old/deprecated event registration (use @EventHandler and registerEvents) | SK-01 | Done | Save scores between server launches. |
- [x] Review and update player lookup logic to use getPlayerExact or handle case sensitivity | SK-02 | Done | Allow tracking scores by bucket. An admin or other plugin should be able to create types of scores with named other than points. { id: "Bread", singular: "loaf", plural: "loaves", initialValue: 0 } Each player's score will be tracked in a bucket by id. Players may be all switched to a bucket or individually switched. |\
- [x] Ensure all commands are properly defined in plugin.yml | SK-03 | Done | Add optional score reporting to buckets with these four values. { id: "Bread", singular: "loaf", plural: "loaves", initialValue: 0, reporting:"admin|global|player|none" } admin means ops/admin only, global means everyone on the server, player means only tell the player, and none means don't report changes.
- [x] Initialize Gradle build system | SK-04 | Done | Tell a player when their bucket changes. Something like "You are now tracking ${id}. You have ${score} ${plural or singular depending in score}." |
- [x] Set project metadata in build.gradle | SK-05 | Done | Enable high score runs for a bucket. Admins or pugins should be able to start a run on a certain kind of score. The top n (configurable) players will have their scores reported globally for this bucket and the individual player will have their score reported to them when it changes. Scores will be optionally reset to their initialValue with the old score for this bucket saved. High score runs will have a lifetime of a target high score, a time like 4 hours or 1 week, or until-disabled. When the high score run is finished all players will be messaged a table with the top n places and their scores along with the individual user's place and score. The scores will be reset to their previous values if they were reset to their initialValue at the beginning otherwise they will be left alone. |
- [x] Add repositories and dependencies | SK-06 | Done | Score archiving. Scores either all or within a given bucket should be able to be archived and reset to their initial value. The archived scores should be able to be listed via a command. |
- [x] Configure Java version | SK-07 | Done | Replace 'net.researchgate.release' with org.danilopianini.git-sensitive-semantic-versioning' for our versioning in our build.gradle file. Turn org.gradle.configuration-cache back on after this. Our current version is 0.2.1-SNAPSHOT. Use that as our default or 0.2.1 and tag the commit to update to 0.2.2. |
- [x] Ensure resource handling for plugin.yml | SK-08 | Ready | Add JUnit 5 test infrastructure and keep the default Gradle `test` task server-free. Use an in-memory Paper test harness such as MockBukkit for plugin lifecycle and Bukkit/Paper behavior; use Mockito only for narrow API boundaries where a harness is unnecessary. |
- [x] Add Gradle plugins as needed (e.g., Shadow) | SK-09 | Ready | Add fast unit tests for score and bucket rules: bucket validation and duplicate IDs, initial values, UUID-isolated scores, default and per-player bucket selection, and add/subtract/reset behavior. Keep domain rules independent of a running Minecraft server. |
- [x] Update .gitignore for Gradle | SK-10 | Ready | Test YAML persistence and archives using temporary plugin data directories: score/bucket/assignment round trips, active-run state, archive contents and resets, legacy score loading, and malformed or unknown stored entries. |
- [x] Remove Maven files | SK-11 | Ready | Test command validation and dispatch, reporting policies and messages, bucket-switch messages, and high-score run ranking/lifecycle (top-N ordering, ties, target/duration/manual finish, and score restoration). Use a controllable clock and in-memory scheduler where needed. |
- [x] Update documentation and scripts | SK-12 | Ready | Add a separate Gradle `integrationTest` source set/task only for behavior that needs a real Paper server, such as loading the built plugin jar, verifying actual command registration/dispatch, and persistence across a server restart. Run it only when explicitly requested; keep it out of the normal `test` and `build` tasks. |
- [x] Test the Gradle build | SK-13 | Ready | Add a an option to `/score-get` to get the score for a specific bucket. |

View File

@@ -2,12 +2,17 @@ plugins {
id 'com.diffplug.spotless' version '6.22.0' id 'com.diffplug.spotless' version '6.22.0'
id 'java-library' id 'java-library'
id 'maven-publish' id 'maven-publish'
id 'net.researchgate.release' version '3.1.0' id 'org.danilopianini.git-sensitive-semantic-versioning' version '7.0.24'
} }
group = 'com.majinnaibu.minecraft.plugins' group = 'com.majinnaibu.minecraft.plugins'
description = "ScoreKeeper" description = "ScoreKeeper"
gitSemVer {
minimumVersion.set('0.2.1')
versionPrefix.set('v')
}
tasks.withType(JavaCompile).configureEach { tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8' options.encoding = 'UTF-8'
// options.compilerArgs << "-Xlint:deprecation" // options.compilerArgs << "-Xlint:deprecation"
@@ -41,10 +46,12 @@ tasks.named('updateDaemonJvm') {
languageVersion = JavaLanguageVersion.of(25) languageVersion = JavaLanguageVersion.of(25)
} }
def pluginVersion = project.version.toString()
processResources { processResources {
inputs.property "version", project.version inputs.property "version", pluginVersion
filesMatching('plugin.yml') { filesMatching('plugin.yml') {
expand(project.properties) expand(version: pluginVersion)
} }
} }
@@ -56,18 +63,6 @@ publishing {
} }
} }
release {
// buildTasks.addAll(['spotlessCheck', 'build'])
buildTasks = ['spotlessCheck', 'build']
failOnSnapshotDependencies = true
ignoredSnapshotDependencies = [
"io.papermc.paper:paper-api"
]
revertOnFail = true
tagTemplate = 'v$version'
versionPropertyFile = 'gradle.properties'
}
repositories { repositories {
mavenCentral() mavenCentral()
maven { url = 'https://repo.papermc.io/repository/maven-public/' } maven { url = 'https://repo.papermc.io/repository/maven-public/' }

View File

@@ -1,5 +1,6 @@
version=0.2.2-SNAPSHOT
org.gradle.java.installations.auto-download=true org.gradle.java.installations.auto-download=true
org.gradle.java.installations.auto-detect=false org.gradle.java.installations.auto-detect=false
org.gradle.java.installations.fromEnv=JAVA_HOME org.gradle.java.installations.fromEnv=JAVA_HOME
org.gradle.daemon=true
org.gradle.configuration-cache=true

View File

@@ -0,0 +1,71 @@
/*
This file is part of ScoreKeeper.
ScoreKeeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ScoreKeeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ScoreKeeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.minecraft.plugins.scorekeeper;
public final class ScoreBucket {
private final String _id;
private final String _singular;
private final String _plural;
private final int _initialValue;
private final ScoreReporting _reporting;
public ScoreBucket(String id, String singular, String plural, int initialValue) {
this(id, singular, plural, initialValue, ScoreReporting.NONE);
}
public ScoreBucket(
String id, String singular, String plural, int initialValue, ScoreReporting reporting) {
if (id == null || !id.matches("[A-Za-z0-9_-]+")) {
throw new IllegalArgumentException("Bucket ID must contain only letters, numbers, _ or -");
}
if (singular == null || singular.isBlank()) {
throw new IllegalArgumentException("Bucket singular label cannot be blank");
}
if (plural == null || plural.isBlank()) {
throw new IllegalArgumentException("Bucket plural label cannot be blank");
}
if (reporting == null) {
throw new IllegalArgumentException("Bucket reporting policy cannot be null");
}
_id = id;
_singular = singular;
_plural = plural;
_initialValue = initialValue;
_reporting = reporting;
}
public String getId() {
return _id;
}
public String getSingular() {
return _singular;
}
public String getPlural() {
return _plural;
}
public int getInitialValue() {
return _initialValue;
}
public ScoreReporting getReporting() {
return _reporting;
}
}

View File

@@ -17,25 +17,44 @@ along with ScoreKeeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
package com.majinnaibu.minecraft.plugins.scorekeeper; package com.majinnaibu.minecraft.plugins.scorekeeper;
import java.util.HashMap; import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level; import java.util.logging.Level;
import com.majinnaibu.minecraft.plugins.scorekeeper.commands.ScoreAddCommand; import com.majinnaibu.minecraft.plugins.scorekeeper.commands.ScoreAddCommand;
import com.majinnaibu.minecraft.plugins.scorekeeper.commands.ScoreArchiveCommand; import com.majinnaibu.minecraft.plugins.scorekeeper.commands.ScoreArchiveCommand;
import com.majinnaibu.minecraft.plugins.scorekeeper.commands.ScoreArchiveListCommand;
import com.majinnaibu.minecraft.plugins.scorekeeper.commands.ScoreBucketCommand;
import com.majinnaibu.minecraft.plugins.scorekeeper.commands.ScoreGetCommand; import com.majinnaibu.minecraft.plugins.scorekeeper.commands.ScoreGetCommand;
import com.majinnaibu.minecraft.plugins.scorekeeper.commands.ScoreResetCommand; import com.majinnaibu.minecraft.plugins.scorekeeper.commands.ScoreResetCommand;
import com.majinnaibu.minecraft.plugins.scorekeeper.commands.ScoreRunCommand;
import com.majinnaibu.minecraft.plugins.scorekeeper.commands.ScoreSubtractCommand; import com.majinnaibu.minecraft.plugins.scorekeeper.commands.ScoreSubtractCommand;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
public class ScoreKeeperPlugin extends JavaPlugin { public class ScoreKeeperPlugin extends JavaPlugin {
private final HashMap<UUID, Integer> _playerScores = new HashMap<UUID, Integer>(); private final Map<String, ScoreBucket> _buckets = new LinkedHashMap<>();
private final Map<String, Map<UUID, Integer>> _bucketScores = new LinkedHashMap<>();
private final Map<UUID, String> _playerBuckets = new LinkedHashMap<>();
private final Map<String, HighScoreRun> _highScoreRuns = new LinkedHashMap<>();
private final Map<String, ScoreArchive> _scoreArchives = new LinkedHashMap<>();
private String _defaultBucketId = "points";
public final String _logPrefix = "[ScoreKeeper] "; public final String _logPrefix = "[ScoreKeeper] ";
public final Component _messagePrefix = public final Component _messagePrefix =
Component.text("[") Component.text("[")
@@ -44,8 +63,39 @@ public class ScoreKeeperPlugin extends JavaPlugin {
@Override @Override
public void onDisable() { public void onDisable() {
// TODO: save score data to file YamlConfiguration scores = new YamlConfiguration();
logWarning("Unable to save scores to file. This feature is not implemented yet."); scores.set("version", 3);
scores.set("default-bucket", _defaultBucketId);
for (ScoreBucket bucket : _buckets.values()) {
String path = "buckets." + bucket.getId();
scores.set(path + ".singular", bucket.getSingular());
scores.set(path + ".plural", bucket.getPlural());
scores.set(path + ".initial-value", bucket.getInitialValue());
scores.set(path + ".reporting", bucket.getReporting().name().toLowerCase());
for (var entry : _bucketScores.get(bucket.getId()).entrySet()) {
scores.set(path + ".scores." + entry.getKey(), entry.getValue());
}
}
for (var entry : _playerBuckets.entrySet()) {
scores.set("player-buckets." + entry.getKey(), entry.getValue());
}
for (HighScoreRun run : _highScoreRuns.values()) {
String path = "high-score-runs." + run.bucketId;
scores.set(path + ".top-n", run.topN);
scores.set(path + ".reset-scores", run.resetScores);
scores.set(path + ".lifetime", run.lifetime.name().toLowerCase(Locale.ROOT));
scores.set(path + ".target-score", run.targetScore);
scores.set(path + ".expires-at", run.expiresAtMillis);
for (var entry : run.previousScores.entrySet()) {
scores.set(path + ".previous-scores." + entry.getKey(), entry.getValue());
}
}
try {
scores.save(new File(getDataFolder(), "scores.yml"));
} catch (IOException ex) {
logError(ex);
}
saveArchives();
} }
@Override @Override
@@ -55,9 +105,16 @@ public class ScoreKeeperPlugin extends JavaPlugin {
getCommand("score-subtract").setExecutor(new ScoreSubtractCommand(this)); getCommand("score-subtract").setExecutor(new ScoreSubtractCommand(this));
getCommand("score-reset").setExecutor(new ScoreResetCommand(this)); getCommand("score-reset").setExecutor(new ScoreResetCommand(this));
getCommand("score-archive").setExecutor(new ScoreArchiveCommand(this)); getCommand("score-archive").setExecutor(new ScoreArchiveCommand(this));
getCommand("score-archive-list").setExecutor(new ScoreArchiveListCommand(this));
getCommand("score-bucket").setExecutor(new ScoreBucketCommand(this));
getCommand("score-run").setExecutor(new ScoreRunCommand(this));
// TODO: load score data from file _buckets.put("points", new ScoreBucket("points", "point", "points", 0));
logWarning("Unable to load scores from file. This feature is not " + "implemented yet."); _bucketScores.put("points", new LinkedHashMap<>());
loadScores();
loadArchives();
checkHighScoreRuns();
getServer().getScheduler().runTaskTimer(this, this::checkHighScoreRuns, 20L, 20L);
logInfo( logInfo(
getPluginMeta().getName() + " version " + getPluginMeta().getVersion() + " is enabled."); getPluginMeta().getName() + " version " + getPluginMeta().getVersion() + " is enabled.");
@@ -65,29 +122,185 @@ public class ScoreKeeperPlugin extends JavaPlugin {
// region Commands // region Commands
public void addScore(Player player, int amount) { public void addScore(Player player, int amount) {
int oldScore = getPlayerScore(player); addScore(player, getPlayerBucket(player), amount);
setPlayerScore(player, oldScore + amount); }
public void addScore(Player player, String bucketId, int amount) {
setScore(player, bucketId, getScore(player, bucketId) + amount);
} }
public void archiveScore(Player player) { public void archiveScore(Player player) {
logWarning("Unable to archive score for " + player.getName() + "."); archivePlayerScore(player);
}
public String archivePlayerScore(Player player) {
String bucketId = getPlayerBucket(player);
return createScoreArchive(
"player " + player.getName() + " in " + bucketId, List.of(bucketId), player);
}
public String archiveBucketScores(String bucketId) {
requireBucket(bucketId);
return createScoreArchive("bucket " + bucketId, List.of(bucketId), null);
}
public String archiveAllScores() {
return createScoreArchive("all buckets", new ArrayList<>(_buckets.keySet()), null);
}
public List<ScoreArchive> getScoreArchives() {
return List.copyOf(_scoreArchives.values());
}
public ScoreArchive getScoreArchive(String archiveId) {
return _scoreArchives.get(archiveId);
} }
public int getScore(Player player) { public int getScore(Player player) {
return getPlayerScore(player); return getScore(player, getPlayerBucket(player));
}
public int getScore(Player player, String bucketId) {
ScoreBucket bucket = requireBucket(bucketId);
return _bucketScores
.get(bucketId)
.computeIfAbsent(player.getUniqueId(), uuid -> bucket.getInitialValue());
} }
public void resetScore(Player player) { public void resetScore(Player player) {
setPlayerScore(player, 0); resetScore(player, getPlayerBucket(player));
}
public void resetScore(Player player, String bucketId) {
setScore(player, bucketId, requireBucket(bucketId).getInitialValue());
} }
public void setScore(Player player, int score) { public void setScore(Player player, int score) {
setPlayerScore(player, score); setScore(player, getPlayerBucket(player), score);
}
public void setScore(Player player, String bucketId, int score) {
ScoreBucket bucket = requireBucket(bucketId);
int oldScore = getScore(player, bucketId);
_bucketScores.get(bucketId).put(player.getUniqueId(), score);
if (oldScore != score) {
HighScoreRun run = _highScoreRuns.get(bucketId);
if (run == null) {
reportScoreChange(player, bucket, score);
} else {
reportHighScoreRunChange(player, bucket, run, score);
if (run.lifetime == HighScoreLifetime.TARGET_SCORE && score >= run.targetScore) {
finishHighScoreRun(bucketId);
}
}
}
} }
public void subtractScore(Player player, int amount) { public void subtractScore(Player player, int amount) {
int oldScore = getPlayerScore(player); subtractScore(player, getPlayerBucket(player), amount);
setPlayerScore(player, oldScore - amount); }
public void subtractScore(Player player, String bucketId, int amount) {
setScore(player, bucketId, getScore(player, bucketId) - amount);
}
public ScoreBucket createBucket(String id, String singular, String plural, int initialValue) {
return createBucket(id, singular, plural, initialValue, ScoreReporting.NONE);
}
public ScoreBucket createBucket(
String id, String singular, String plural, int initialValue, ScoreReporting reporting) {
ScoreBucket bucket = new ScoreBucket(id, singular, plural, initialValue, reporting);
if (_buckets.containsKey(id)) {
throw new IllegalArgumentException("A score bucket with ID " + id + " already exists");
}
_buckets.put(id, bucket);
_bucketScores.put(id, new LinkedHashMap<>());
return bucket;
}
public ScoreBucket getBucket(String bucketId) {
return _buckets.get(bucketId);
}
public Map<String, ScoreBucket> getBuckets() {
return Map.copyOf(_buckets);
}
public String getPlayerBucket(Player player) {
return _playerBuckets.getOrDefault(player.getUniqueId(), _defaultBucketId);
}
public void switchPlayerBucket(Player player, String bucketId) {
ScoreBucket bucket = requireBucket(bucketId);
UUID playerId = player.getUniqueId();
String previousBucketId = getPlayerBucket(player);
if (bucketId.equals(_defaultBucketId)) {
_playerBuckets.remove(playerId);
} else {
_playerBuckets.put(playerId, bucketId);
}
if (!previousBucketId.equals(bucketId)) {
sendBucketChangeMessage(player, bucket);
}
}
public void switchAllPlayers(String bucketId) {
requireBucket(bucketId);
Map<UUID, String> previousBuckets = new LinkedHashMap<>();
for (Player player : getServer().getOnlinePlayers()) {
previousBuckets.put(player.getUniqueId(), getPlayerBucket(player));
}
_defaultBucketId = bucketId;
_playerBuckets.clear();
ScoreBucket bucket = requireBucket(bucketId);
for (Player player : getServer().getOnlinePlayers()) {
if (!bucketId.equals(previousBuckets.get(player.getUniqueId()))) {
sendBucketChangeMessage(player, bucket);
}
}
}
public void startTargetScoreRun(String bucketId, int topN, boolean resetScores, int targetScore) {
ScoreBucket bucket = requireBucket(bucketId);
if (resetScores && targetScore <= bucket.getInitialValue()) {
throw new IllegalArgumentException("Target score must exceed the bucket's initial value");
}
startHighScoreRun(bucketId, topN, resetScores, HighScoreLifetime.TARGET_SCORE, targetScore, 0L);
}
public void startTimedScoreRun(
String bucketId, int topN, boolean resetScores, Duration duration) {
if (duration == null || duration.isNegative() || duration.isZero()) {
throw new IllegalArgumentException("Run duration must be positive");
}
long durationMillis;
long expiresAtMillis;
try {
durationMillis = duration.toMillis();
expiresAtMillis = Math.addExact(System.currentTimeMillis(), durationMillis);
} catch (ArithmeticException ex) {
throw new IllegalArgumentException("Run duration is too large", ex);
}
if (durationMillis <= 0) {
throw new IllegalArgumentException("Run duration must be at least one millisecond");
}
startHighScoreRun(bucketId, topN, resetScores, HighScoreLifetime.DURATION, 0, expiresAtMillis);
}
public void startUntilDisabledScoreRun(String bucketId, int topN, boolean resetScores) {
startHighScoreRun(bucketId, topN, resetScores, HighScoreLifetime.UNTIL_DISABLED, 0, 0L);
}
public void stopHighScoreRun(String bucketId) {
if (!_highScoreRuns.containsKey(bucketId)) {
throw new IllegalArgumentException("No high-score run is active for bucket " + bucketId);
}
finishHighScoreRun(bucketId);
}
public boolean hasActiveHighScoreRun(String bucketId) {
return _highScoreRuns.containsKey(bucketId);
} }
// endregion // endregion
@@ -97,16 +310,484 @@ public class ScoreKeeperPlugin extends JavaPlugin {
reciever.sendMessage(_messagePrefix.append(message)); reciever.sendMessage(_messagePrefix.append(message));
} }
private int getPlayerScore(Player player) { private ScoreBucket requireBucket(String bucketId) {
UUID uuid = player.getUniqueId(); ScoreBucket bucket = _buckets.get(bucketId);
if (!_playerScores.containsKey(uuid)) { if (bucket == null) {
_playerScores.put(uuid, 0); throw new IllegalArgumentException("Unknown score bucket: " + bucketId);
} }
return _playerScores.get(uuid); return bucket;
} }
private void setPlayerScore(Player player, int score) { private void sendBucketChangeMessage(Player player, ScoreBucket bucket) {
_playerScores.put(player.getUniqueId(), score); int score = getScore(player, bucket.getId());
String unit = score == 1 ? bucket.getSingular() : bucket.getPlural();
sendMessage(
player,
Component.text(
"You are now tracking " + bucket.getId() + ". You have " + score + " " + unit + "."));
}
private String createScoreArchive(String scope, List<String> bucketIds, Player player) {
for (String bucketId : bucketIds) {
if (_highScoreRuns.containsKey(bucketId)) {
throw new IllegalArgumentException(
"Stop the active high-score run for " + bucketId + " before archiving it");
}
}
Map<String, Map<UUID, Integer>> archivedScores = new LinkedHashMap<>();
UUID playerId = player == null ? null : player.getUniqueId();
for (String bucketId : bucketIds) {
ScoreBucket bucket = requireBucket(bucketId);
Map<UUID, Integer> bucketScores = _bucketScores.get(bucketId);
if (playerId == null) {
archivedScores.put(bucketId, new LinkedHashMap<>(bucketScores));
bucketScores.replaceAll((uuid, score) -> bucket.getInitialValue());
} else {
int score = getScore(player, bucketId);
archivedScores.put(bucketId, Map.of(playerId, score));
bucketScores.put(playerId, bucket.getInitialValue());
}
}
String archiveId = UUID.randomUUID().toString();
_scoreArchives.put(
archiveId, new ScoreArchive(archiveId, scope, System.currentTimeMillis(), archivedScores));
return archiveId;
}
private void startHighScoreRun(
String bucketId,
int topN,
boolean resetScores,
HighScoreLifetime lifetime,
int targetScore,
long expiresAtMillis) {
ScoreBucket bucket = requireBucket(bucketId);
if (topN < 1) {
throw new IllegalArgumentException("Top N must be at least 1");
}
if (_highScoreRuns.containsKey(bucketId)) {
throw new IllegalArgumentException("A high-score run is already active for " + bucketId);
}
Map<UUID, Integer> bucketScores = _bucketScores.get(bucketId);
Map<UUID, Integer> previousScores = resetScores ? new LinkedHashMap<>(bucketScores) : Map.of();
if (resetScores) {
bucketScores.replaceAll((playerId, score) -> bucket.getInitialValue());
}
_highScoreRuns.put(
bucketId,
new HighScoreRun(
bucketId, topN, resetScores, lifetime, targetScore, expiresAtMillis, previousScores));
checkHighScoreRuns();
}
private void checkHighScoreRuns() {
long now = System.currentTimeMillis();
List<String> finishedRuns = new ArrayList<>();
for (HighScoreRun run : _highScoreRuns.values()) {
boolean expired = run.lifetime == HighScoreLifetime.DURATION && now >= run.expiresAtMillis;
boolean targetReached =
run.lifetime == HighScoreLifetime.TARGET_SCORE
&& _bucketScores.get(run.bucketId).values().stream()
.anyMatch(score -> score >= run.targetScore);
if (expired || targetReached) {
finishedRuns.add(run.bucketId);
}
}
for (String bucketId : finishedRuns) {
finishHighScoreRun(bucketId);
}
}
private void reportHighScoreRunChange(
Player player, ScoreBucket bucket, HighScoreRun run, int score) {
String message = scoreMessage(player.getName(), bucket, score);
sendMessage(player, Component.text(message));
List<ScoreEntry> standings = getRankedScores(bucket.getId());
for (int place = 0; place < Math.min(run.topN, standings.size()); place++) {
if (standings.get(place).playerId.equals(player.getUniqueId())) {
for (Player recipient : getServer().getOnlinePlayers()) {
if (recipient != player) {
sendMessage(recipient, Component.text(message));
}
}
return;
}
}
}
private void finishHighScoreRun(String bucketId) {
HighScoreRun run = _highScoreRuns.remove(bucketId);
if (run == null) {
return;
}
ScoreBucket bucket = requireBucket(bucketId);
List<ScoreEntry> standings = getRankedScores(bucketId);
StringBuilder table =
new StringBuilder("High-score run for ").append(bucketId).append(" finished.");
int places = Math.min(run.topN, standings.size());
if (places == 0) {
table.append("\nNo scores were recorded.");
}
for (int place = 0; place < places; place++) {
ScoreEntry entry = standings.get(place);
table
.append("\n")
.append(place + 1)
.append(". ")
.append(entry.playerName)
.append(" - ")
.append(entry.score)
.append(" ")
.append(scoreUnit(bucket, entry.score));
}
if (run.resetScores) {
Map<UUID, Integer> bucketScores = _bucketScores.get(bucketId);
bucketScores.clear();
bucketScores.putAll(run.previousScores);
}
logInfo(table.toString().replace('\n', ' '));
for (Player player : getServer().getOnlinePlayers()) {
ScoreEntry personalEntry = null;
int personalPlace = -1;
for (int place = 0; place < standings.size(); place++) {
if (standings.get(place).playerId.equals(player.getUniqueId())) {
personalEntry = standings.get(place);
personalPlace = place + 1;
break;
}
}
int personalScore = personalEntry == null ? bucket.getInitialValue() : personalEntry.score;
String personalResult =
personalPlace < 0
? "Your place: unranked; score: "
+ personalScore
+ " "
+ scoreUnit(bucket, personalScore)
: "Your place: "
+ personalPlace
+ "; score: "
+ personalScore
+ " "
+ scoreUnit(bucket, personalScore);
sendMessage(player, Component.text(table + "\n" + personalResult));
}
}
private List<ScoreEntry> getRankedScores(String bucketId) {
List<ScoreEntry> standings = new ArrayList<>();
for (var entry : _bucketScores.get(bucketId).entrySet()) {
String playerName = getServer().getOfflinePlayer(entry.getKey()).getName();
if (playerName == null || playerName.isBlank()) {
playerName = entry.getKey().toString();
}
standings.add(new ScoreEntry(entry.getKey(), playerName, entry.getValue()));
}
standings.sort(
Comparator.comparingInt((ScoreEntry entry) -> entry.score)
.reversed()
.thenComparing(entry -> entry.playerName, String.CASE_INSENSITIVE_ORDER)
.thenComparing(entry -> entry.playerId.toString()));
return standings;
}
private String scoreMessage(String playerName, ScoreBucket bucket, int score) {
return playerName
+ "'s "
+ bucket.getId()
+ " score is now "
+ score
+ " "
+ scoreUnit(bucket, score)
+ ".";
}
private String scoreUnit(ScoreBucket bucket, int score) {
return score == 1 ? bucket.getSingular() : bucket.getPlural();
}
private void loadScores() {
File scoreFile = new File(getDataFolder(), "scores.yml");
if (!scoreFile.isFile()) {
return;
}
YamlConfiguration scores = YamlConfiguration.loadConfiguration(scoreFile);
ConfigurationSection bucketSection = scores.getConfigurationSection("buckets");
if (bucketSection == null) {
loadLegacyScores(scores);
return;
}
_buckets.clear();
_bucketScores.clear();
for (String id : bucketSection.getKeys(false)) {
try {
ScoreReporting reporting =
parseReporting(bucketSection.getString(id + ".reporting", "none"), id);
createBucket(
id,
bucketSection.getString(id + ".singular", id),
bucketSection.getString(id + ".plural", id),
bucketSection.getInt(id + ".initial-value"),
reporting);
} catch (IllegalArgumentException ex) {
logWarning("Ignoring invalid score bucket " + id + ": " + ex.getMessage());
}
}
if (!_buckets.containsKey("points")) {
createBucket("points", "point", "points", 0);
}
_defaultBucketId = scores.getString("default-bucket", "points");
if (!_buckets.containsKey(_defaultBucketId)) {
logWarning("Unknown default score bucket; using points instead.");
_defaultBucketId = "points";
}
for (String id : _buckets.keySet()) {
ConfigurationSection bucketScores =
scores.getConfigurationSection("buckets." + id + ".scores");
if (bucketScores != null) {
loadPlayerScores(bucketScores, _bucketScores.get(id));
}
}
ConfigurationSection playerBuckets = scores.getConfigurationSection("player-buckets");
if (playerBuckets != null) {
for (String key : playerBuckets.getKeys(false)) {
try {
UUID playerId = UUID.fromString(key);
String bucketId = playerBuckets.getString(key);
if (_buckets.containsKey(bucketId) && !bucketId.equals(_defaultBucketId)) {
_playerBuckets.put(playerId, bucketId);
}
} catch (IllegalArgumentException ex) {
logWarning("Ignoring invalid player bucket UUID: " + key);
}
}
}
loadHighScoreRuns(scores);
}
private void loadArchives() {
File archiveFile = new File(getDataFolder(), "archives.yml");
if (!archiveFile.isFile()) {
return;
}
YamlConfiguration archives = YamlConfiguration.loadConfiguration(archiveFile);
ConfigurationSection archiveSection = archives.getConfigurationSection("archives");
if (archiveSection == null) {
return;
}
for (String archiveId : archiveSection.getKeys(false)) {
String path = "archives." + archiveId;
Map<String, Map<UUID, Integer>> bucketScores = new LinkedHashMap<>();
ConfigurationSection buckets = archives.getConfigurationSection(path + ".buckets");
if (buckets != null) {
for (String bucketId : buckets.getKeys(false)) {
Map<UUID, Integer> playerScores = new LinkedHashMap<>();
ConfigurationSection savedScores =
archives.getConfigurationSection(path + ".buckets." + bucketId + ".scores");
if (savedScores != null) {
loadPlayerScores(savedScores, playerScores);
}
bucketScores.put(bucketId, playerScores);
}
}
_scoreArchives.put(
archiveId,
new ScoreArchive(
archiveId,
archives.getString(path + ".scope", "unknown"),
archives.getLong(path + ".created-at"),
bucketScores));
}
}
private void saveArchives() {
YamlConfiguration archives = new YamlConfiguration();
for (ScoreArchive archive : _scoreArchives.values()) {
String path = "archives." + archive.getId();
archives.set(path + ".scope", archive.getScope());
archives.set(path + ".created-at", archive.getCreatedAtMillis());
for (var bucketEntry : archive.getBucketScores().entrySet()) {
for (var scoreEntry : bucketEntry.getValue().entrySet()) {
archives.set(
path + ".buckets." + bucketEntry.getKey() + ".scores." + scoreEntry.getKey(),
scoreEntry.getValue());
}
}
}
try {
archives.save(new File(getDataFolder(), "archives.yml"));
} catch (IOException ex) {
logError(ex);
}
}
private void loadLegacyScores(YamlConfiguration scores) {
loadPlayerScores(scores, _bucketScores.get("points"));
}
private void loadPlayerScores(ConfigurationSection scores, Map<UUID, Integer> target) {
for (String key : scores.getKeys(false)) {
try {
target.put(UUID.fromString(key), scores.getInt(key));
} catch (IllegalArgumentException ex) {
logWarning("Ignoring score with invalid player UUID: " + key);
}
}
}
private ScoreReporting parseReporting(String value, String bucketId) {
try {
return ScoreReporting.fromString(value);
} catch (IllegalArgumentException ex) {
logWarning("Ignoring invalid reporting policy for bucket " + bucketId + "; using none.");
return ScoreReporting.NONE;
}
}
private void loadHighScoreRuns(YamlConfiguration scores) {
ConfigurationSection runs = scores.getConfigurationSection("high-score-runs");
if (runs == null) {
return;
}
for (String bucketId : runs.getKeys(false)) {
if (!_buckets.containsKey(bucketId)) {
logWarning("Ignoring high-score run for unknown bucket " + bucketId + ".");
continue;
}
try {
String path = "high-score-runs." + bucketId;
int topN = scores.getInt(path + ".top-n");
if (topN < 1) {
throw new IllegalArgumentException("Top N must be at least 1");
}
HighScoreLifetime lifetime =
HighScoreLifetime.valueOf(
scores.getString(path + ".lifetime", "until_disabled").toUpperCase(Locale.ROOT));
Map<UUID, Integer> previousScores = new LinkedHashMap<>();
ConfigurationSection savedScores =
scores.getConfigurationSection(path + ".previous-scores");
if (savedScores != null) {
loadPlayerScores(savedScores, previousScores);
}
_highScoreRuns.put(
bucketId,
new HighScoreRun(
bucketId,
topN,
scores.getBoolean(path + ".reset-scores"),
lifetime,
scores.getInt(path + ".target-score"),
scores.getLong(path + ".expires-at"),
previousScores));
} catch (IllegalArgumentException ex) {
logWarning(
"Ignoring invalid high-score run for bucket " + bucketId + ": " + ex.getMessage());
}
}
}
private void reportScoreChange(Player player, ScoreBucket bucket, int score) {
ScoreReporting reporting = bucket.getReporting();
if (reporting == ScoreReporting.NONE) {
return;
}
String text = scoreMessage(player.getName(), bucket, score);
Component message = Component.text(text);
if (reporting == ScoreReporting.PLAYER) {
sendMessage(player, message);
} else if (reporting == ScoreReporting.GLOBAL) {
for (Player recipient : getServer().getOnlinePlayers()) {
sendMessage(recipient, message);
}
} else if (reporting == ScoreReporting.ADMIN) {
logInfo(text);
for (Player recipient : getServer().getOnlinePlayers()) {
if (recipient.isOp() || recipient.hasPermission("scorekeeper.admin")) {
sendMessage(recipient, message);
}
}
}
}
private enum HighScoreLifetime {
TARGET_SCORE,
DURATION,
UNTIL_DISABLED
}
private static final class HighScoreRun {
private final String bucketId;
private final int topN;
private final boolean resetScores;
private final HighScoreLifetime lifetime;
private final int targetScore;
private final long expiresAtMillis;
private final Map<UUID, Integer> previousScores;
private HighScoreRun(
String bucketId,
int topN,
boolean resetScores,
HighScoreLifetime lifetime,
int targetScore,
long expiresAtMillis,
Map<UUID, Integer> previousScores) {
this.bucketId = bucketId;
this.topN = topN;
this.resetScores = resetScores;
this.lifetime = lifetime;
this.targetScore = targetScore;
this.expiresAtMillis = expiresAtMillis;
this.previousScores = new LinkedHashMap<>(previousScores);
}
}
private record ScoreEntry(UUID playerId, String playerName, int score) {}
public static final class ScoreArchive {
private final String _id;
private final String _scope;
private final long _createdAtMillis;
private final Map<String, Map<UUID, Integer>> _bucketScores;
private ScoreArchive(
String id,
String scope,
long createdAtMillis,
Map<String, Map<UUID, Integer>> bucketScores) {
_id = id;
_scope = scope;
_createdAtMillis = createdAtMillis;
Map<String, Map<UUID, Integer>> copiedScores = new LinkedHashMap<>();
for (var entry : bucketScores.entrySet()) {
copiedScores.put(entry.getKey(), Map.copyOf(entry.getValue()));
}
_bucketScores = Collections.unmodifiableMap(copiedScores);
}
public String getId() {
return _id;
}
public String getScope() {
return _scope;
}
public long getCreatedAtMillis() {
return _createdAtMillis;
}
public Map<String, Map<UUID, Integer>> getBucketScores() {
return _bucketScores;
}
} }
// endregion // endregion

View File

@@ -0,0 +1,38 @@
/*
This file is part of ScoreKeeper.
ScoreKeeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ScoreKeeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ScoreKeeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.minecraft.plugins.scorekeeper;
import java.util.Locale;
public enum ScoreReporting {
ADMIN,
GLOBAL,
PLAYER,
NONE;
public static ScoreReporting fromString(String value) {
if (value == null) {
throw new IllegalArgumentException("Reporting policy cannot be null");
}
try {
return valueOf(value.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException ex) {
throw new IllegalArgumentException("Reporting must be admin, global, player or none", ex);
}
}
}

View File

@@ -20,10 +20,12 @@ package com.majinnaibu.minecraft.plugins.scorekeeper.commands;
import com.majinnaibu.minecraft.plugins.scorekeeper.ScoreKeeperPlugin; import com.majinnaibu.minecraft.plugins.scorekeeper.ScoreKeeperPlugin;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class ScoreArchiveCommand implements CommandExecutor { public class ScoreArchiveCommand implements CommandExecutor {
private final ScoreKeeperPlugin _plugin; private final ScoreKeeperPlugin _plugin;
@@ -34,7 +36,45 @@ public class ScoreArchiveCommand implements CommandExecutor {
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] split) { public boolean onCommand(CommandSender sender, Command command, String label, String[] split) {
_plugin.sendMessage(sender, Component.text("archive command unimplemented")); if (!sender.hasPermission("scorekeeper.admin")) {
sendError(sender, "You do not have permission to archive scores");
return true;
}
try {
String archiveId;
if (split.length == 1 && split[0].equalsIgnoreCase("all")) {
archiveId = _plugin.archiveAllScores();
} else if (split.length == 2 && split[0].equalsIgnoreCase("bucket")) {
archiveId = _plugin.archiveBucketScores(split[1]);
} else if (split.length == 0 && sender instanceof Player player) {
archiveId = _plugin.archivePlayerScore(player);
} else if (split.length == 1) {
Player target = _plugin.getServer().getPlayerExact(split[0]);
if (target == null) {
sendError(sender, "Can't find a player with that name");
return true;
}
archiveId = _plugin.archivePlayerScore(target);
} else {
sendUsage(sender);
return true;
}
_plugin.sendMessage(sender, Component.text("Saved score archive " + archiveId + "."));
} catch (IllegalArgumentException ex) {
sendError(sender, ex.getMessage());
}
return true; return true;
} }
private void sendError(CommandSender sender, String message) {
_plugin.sendMessage(sender, Component.text(message).color(NamedTextColor.RED));
}
private void sendUsage(CommandSender sender) {
_plugin.sendMessage(
sender,
Component.text("Usage: /score-archive [playerName|all] | /score-archive bucket <bucketId>")
.color(NamedTextColor.YELLOW));
}
} }

View File

@@ -0,0 +1,131 @@
/*
This file is part of ScoreKeeper.
ScoreKeeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ScoreKeeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ScoreKeeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.minecraft.plugins.scorekeeper.commands;
import java.time.Instant;
import java.util.Comparator;
import java.util.Map;
import java.util.UUID;
import com.majinnaibu.minecraft.plugins.scorekeeper.ScoreBucket;
import com.majinnaibu.minecraft.plugins.scorekeeper.ScoreKeeperPlugin;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
public class ScoreArchiveListCommand implements CommandExecutor {
private final ScoreKeeperPlugin _plugin;
public ScoreArchiveListCommand(ScoreKeeperPlugin plugin) {
_plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 0) {
var archives = _plugin.getScoreArchives();
if (archives.isEmpty()) {
_plugin.sendMessage(sender, Component.text("No score archives have been saved."));
} else {
archives.stream()
.sorted(
Comparator.comparingLong(
(ScoreKeeperPlugin.ScoreArchive archive) -> archive.getCreatedAtMillis())
.reversed())
.forEach(
archive ->
_plugin.sendMessage(
sender,
Component.text(
archive.getId()
+ " | "
+ archive.getScope()
+ " | "
+ Instant.ofEpochMilli(archive.getCreatedAtMillis()))));
}
return true;
}
if (args.length != 1) {
sendUsage(sender);
return true;
}
ScoreKeeperPlugin.ScoreArchive archive = _plugin.getScoreArchive(args[0]);
if (archive == null) {
_plugin.sendMessage(
sender,
Component.text("No score archive exists with ID " + args[0] + ".")
.color(NamedTextColor.RED));
return true;
}
_plugin.sendMessage(
sender,
Component.text(
"Archive "
+ archive.getId()
+ " ("
+ archive.getScope()
+ ", "
+ Instant.ofEpochMilli(archive.getCreatedAtMillis())
+ ")"));
for (var bucketEntry : archive.getBucketScores().entrySet()) {
ScoreBucket bucket = _plugin.getBucket(bucketEntry.getKey());
_plugin.sendMessage(sender, Component.text("Bucket " + bucketEntry.getKey() + ":"));
bucketEntry.getValue().entrySet().stream()
.sorted(
Map.Entry.<UUID, Integer>comparingByValue()
.reversed()
.thenComparing(entry -> entry.getKey().toString()))
.forEach(
entry ->
_plugin.sendMessage(
sender,
Component.text(
displayName(entry.getKey())
+ " - "
+ entry.getValue()
+ " "
+ scoreUnit(bucket, entry.getValue()))));
}
return true;
}
private String displayName(UUID playerId) {
OfflinePlayer player = _plugin.getServer().getOfflinePlayer(playerId);
return player.getName() == null ? playerId.toString() : player.getName();
}
private String scoreUnit(ScoreBucket bucket, int score) {
if (bucket == null) {
return "scores";
}
return score == 1 ? bucket.getSingular() : bucket.getPlural();
}
private void sendUsage(CommandSender sender) {
_plugin.sendMessage(
sender,
Component.text("Usage: /score-archive-list [archiveId]").color(NamedTextColor.YELLOW));
}
}

View File

@@ -0,0 +1,135 @@
/*
This file is part of ScoreKeeper.
ScoreKeeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ScoreKeeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ScoreKeeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.minecraft.plugins.scorekeeper.commands;
import com.majinnaibu.minecraft.plugins.scorekeeper.ScoreBucket;
import com.majinnaibu.minecraft.plugins.scorekeeper.ScoreKeeperPlugin;
import com.majinnaibu.minecraft.plugins.scorekeeper.ScoreReporting;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class ScoreBucketCommand implements CommandExecutor {
private final ScoreKeeperPlugin _plugin;
public ScoreBucketCommand(ScoreKeeperPlugin plugin) {
_plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 0) {
if (sender instanceof Player player) {
String bucketId = _plugin.getPlayerBucket(player);
ScoreBucket bucket = _plugin.getBucket(bucketId);
_plugin.sendMessage(
sender,
Component.text(
"You are tracking " + bucket.getId() + " (" + bucket.getPlural() + ")."));
} else {
sendUsage(sender);
}
return true;
}
if ((args.length == 5 || args.length == 6) && args[0].equalsIgnoreCase("create")) {
if (!requireAdmin(sender)) {
return true;
}
try {
ScoreReporting reporting =
args.length == 6 ? ScoreReporting.fromString(args[5]) : ScoreReporting.NONE;
_plugin.createBucket(args[1], args[2], args[3], Integer.parseInt(args[4]), reporting);
_plugin.sendMessage(sender, Component.text("Created score bucket " + args[1] + "."));
} catch (IllegalArgumentException ex) {
sendError(sender, ex.getMessage());
}
return true;
}
if (args.length == 1 && sender instanceof Player player) {
switchPlayerBucket(sender, player, args[0]);
return true;
}
if (args.length == 2) {
if (!requireAdmin(sender)) {
return true;
}
if (args[0].equalsIgnoreCase("all")) {
try {
_plugin.switchAllPlayers(args[1]);
_plugin.sendMessage(
sender, Component.text("All players are now tracking " + args[1] + "."));
} catch (IllegalArgumentException ex) {
sendError(sender, ex.getMessage());
}
return true;
}
Player target = _plugin.getServer().getPlayerExact(args[0]);
if (target == null) {
sendError(sender, "Can't find a player with that name");
} else {
switchPlayerBucket(sender, target, args[1]);
}
return true;
}
sendUsage(sender);
return true;
}
private void switchPlayerBucket(CommandSender sender, Player target, String bucketId) {
try {
_plugin.switchPlayerBucket(target, bucketId);
if (sender != target) {
_plugin.sendMessage(
sender, Component.text(target.getName() + " is now tracking " + bucketId + "."));
}
} catch (IllegalArgumentException ex) {
sendError(sender, ex.getMessage());
}
}
private boolean requireAdmin(CommandSender sender) {
if (sender.hasPermission("scorekeeper.admin")) {
return true;
}
sendError(sender, "You do not have permission to manage score buckets");
return false;
}
private void sendError(CommandSender sender, String message) {
_plugin.sendMessage(sender, Component.text(message).color(NamedTextColor.RED));
}
private void sendUsage(CommandSender sender) {
_plugin.sendMessage(
sender,
Component.text(
"Usage: /score-bucket [bucketId] | create <id> <singular> <plural> <initialValue>"
+ " | <player|all> <bucketId>")
.color(NamedTextColor.YELLOW));
}
}

View File

@@ -0,0 +1,123 @@
/*
This file is part of ScoreKeeper.
ScoreKeeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ScoreKeeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with ScoreKeeper. If not, see <https://www.gnu.org/licenses/agpl-3.0.txt>.
*/
package com.majinnaibu.minecraft.plugins.scorekeeper.commands;
import java.time.Duration;
import com.majinnaibu.minecraft.plugins.scorekeeper.ScoreKeeperPlugin;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
public class ScoreRunCommand implements CommandExecutor {
private final ScoreKeeperPlugin _plugin;
public ScoreRunCommand(ScoreKeeperPlugin plugin) {
_plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!sender.hasPermission("scorekeeper.admin")) {
sendError(sender, "You do not have permission to manage high-score runs");
return true;
}
if (args.length == 2 && args[0].equalsIgnoreCase("stop")) {
try {
_plugin.stopHighScoreRun(args[1]);
} catch (IllegalArgumentException ex) {
sendError(sender, ex.getMessage());
}
return true;
}
if (args.length < 5 || !args[0].equalsIgnoreCase("start")) {
sendUsage(sender);
return true;
}
String bucketId = args[1];
try {
int topN = Integer.parseInt(args[2]);
boolean resetScores = parseBoolean(args[3]);
String lifetime = args[4].toLowerCase();
if (lifetime.equals("target") && args.length == 6) {
_plugin.startTargetScoreRun(bucketId, topN, resetScores, Integer.parseInt(args[5]));
} else if (lifetime.equals("duration") && args.length == 6) {
_plugin.startTimedScoreRun(bucketId, topN, resetScores, parseDuration(args[5]));
} else if (lifetime.equals("until-disabled") && args.length == 5) {
_plugin.startUntilDisabledScoreRun(bucketId, topN, resetScores);
} else {
sendUsage(sender);
return true;
}
_plugin.sendMessage(sender, Component.text("Started a high-score run for " + bucketId + "."));
} catch (IllegalArgumentException ex) {
sendError(sender, ex.getMessage());
}
return true;
}
private boolean parseBoolean(String value) {
if (value.equalsIgnoreCase("true")) {
return true;
}
if (value.equalsIgnoreCase("false")) {
return false;
}
throw new IllegalArgumentException("Reset scores must be true or false");
}
private Duration parseDuration(String value) {
if (!value.matches("[0-9]+[smhdw]")) {
throw new IllegalArgumentException(
"Duration must use seconds, minutes, hours, days or weeks (e.g. 4h)");
}
long amount = Long.parseLong(value.substring(0, value.length() - 1));
try {
return switch (value.charAt(value.length() - 1)) {
case 's' -> Duration.ofSeconds(amount);
case 'm' -> Duration.ofMinutes(amount);
case 'h' -> Duration.ofHours(amount);
case 'd' -> Duration.ofDays(amount);
case 'w' -> Duration.ofDays(Math.multiplyExact(amount, 7));
default -> throw new IllegalArgumentException("Unsupported duration unit");
};
} catch (ArithmeticException ex) {
throw new IllegalArgumentException("Duration is too large", ex);
}
}
private void sendError(CommandSender sender, String message) {
_plugin.sendMessage(sender, Component.text(message).color(NamedTextColor.RED));
}
private void sendUsage(CommandSender sender) {
_plugin.sendMessage(
sender,
Component.text(
"Usage: /score-run start <bucket> <topN> <reset:true|false> "
+ "<target <score>|duration <time>|until-disabled> | /score-run stop <bucket>")
.color(NamedTextColor.YELLOW));
}
}

View File

@@ -18,4 +18,17 @@ commands:
score-archive: score-archive:
description: Archives and resets the player's score description: Archives and resets the player's score
usage: /score-archive [playername] usage: /score-archive [playername]
score-archive-list:
description: Lists saved score archives or displays one archive.
usage: /score-archive-list [archiveId]
score-bucket:
description: Selects or manages score buckets.
usage: /score-bucket [bucketId] | create <id> <singular> <plural> <initialValue> [admin|global|player|none] | <player|all> <bucketId>
score-run:
description: Starts or stops a high-score run.
usage: /score-run start <bucket> <topN> <reset:true|false> <target <score>|duration <time>|until-disabled> | /score-run stop <bucket>
permissions:
scorekeeper.admin:
description: Allows managing score buckets.
default: op

View File

@@ -8,8 +8,47 @@
set -euo pipefail set -euo pipefail
TOOLS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" TOOLS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=setup-env.sh PROJECT_ROOT="$(cd "$TOOLS_DIR/.." && pwd)"
source "$TOOLS_DIR/setup-env.sh" if [[ ! -r "$PROJECT_ROOT/.env" ]]; then
echo "Error: $PROJECT_ROOT/.env is missing or unreadable. Copy .env.example to .env and set its values." >&2
exit 1
fi
load_project_env() {
local env_line env_key env_value first_char last_char
while IFS= read -r env_line || [[ -n "$env_line" ]]; do
env_line="${env_line%$'\r'}"
[[ "$env_line" =~ ^[[:space:]]*(#|$) ]] && continue
[[ "$env_line" == *=* ]] || continue
env_key="${env_line%%=*}"
env_value="${env_line#*=}"
env_key="${env_key#"${env_key%%[![:space:]]*}"}"
env_key="${env_key%"${env_key##*[![:space:]]}"}"
[[ "$env_key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue
env_value="${env_value#"${env_value%%[![:space:]]*}"}"
env_value="${env_value%"${env_value##*[![:space:]]}"}"
if (( ${#env_value} >= 2 )); then
first_char="${env_value:0:1}"
last_char="${env_value:$((${#env_value} - 1)):1}"
if [[ "$first_char" == "$last_char" && ( "$first_char" == '"' || "$first_char" == "'" ) ]]; then
env_value="${env_value:1:$((${#env_value} - 2))}"
fi
fi
if [[ -z "${!env_key:-}" ]]; then
export "$env_key=$env_value"
fi
done < "$PROJECT_ROOT/.env"
}
load_project_env
MINECRAFT_SERVER_PATH="${MINECRAFT_SERVER_PATH:-MCServer}"
MINECRAFT_SERVER_PATH="${MINECRAFT_SERVER_PATH/#\~/$HOME}"
[[ "$MINECRAFT_SERVER_PATH" == /* ]] || MINECRAFT_SERVER_PATH="$PROJECT_ROOT/$MINECRAFT_SERVER_PATH"
MINECRAFT_BACKUP_PATH="${MINECRAFT_BACKUP_PATH:-backups}"
MINECRAFT_BACKUP_PATH="${MINECRAFT_BACKUP_PATH/#\~/$HOME}"
[[ "$MINECRAFT_BACKUP_PATH" == /* ]] || MINECRAFT_BACKUP_PATH="$PROJECT_ROOT/$MINECRAFT_BACKUP_PATH"
FORCE=false FORCE=false
LABEL="" LABEL=""

View File

@@ -4,8 +4,43 @@ set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
# shellcheck source=setup-env.sh if [[ ! -r "$PROJECT_ROOT/.env" ]]; then
source "$SCRIPT_DIR/setup-env.sh" echo "Error: $PROJECT_ROOT/.env is missing or unreadable. Copy .env.example to .env and set its values." >&2
exit 1
fi
load_project_env() {
local env_line env_key env_value first_char last_char
while IFS= read -r env_line || [[ -n "$env_line" ]]; do
env_line="${env_line%$'\r'}"
[[ "$env_line" =~ ^[[:space:]]*(#|$) ]] && continue
[[ "$env_line" == *=* ]] || continue
env_key="${env_line%%=*}"
env_value="${env_line#*=}"
env_key="${env_key#"${env_key%%[![:space:]]*}"}"
env_key="${env_key%"${env_key##*[![:space:]]}"}"
[[ "$env_key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue
env_value="${env_value#"${env_value%%[![:space:]]*}"}"
env_value="${env_value%"${env_value##*[![:space:]]}"}"
if (( ${#env_value} >= 2 )); then
first_char="${env_value:0:1}"
last_char="${env_value:$((${#env_value} - 1)):1}"
if [[ "$first_char" == "$last_char" && ( "$first_char" == '"' || "$first_char" == "'" ) ]]; then
env_value="${env_value:1:$((${#env_value} - 2))}"
fi
fi
if [[ -z "${!env_key:-}" ]]; then
export "$env_key=$env_value"
fi
done < "$PROJECT_ROOT/.env"
}
load_project_env
MINECRAFT_SERVER_PATH="${MINECRAFT_SERVER_PATH:-MCServer}"
MINECRAFT_SERVER_PATH="${MINECRAFT_SERVER_PATH/#\~/$HOME}"
[[ "$MINECRAFT_SERVER_PATH" == /* ]] || MINECRAFT_SERVER_PATH="$PROJECT_ROOT/$MINECRAFT_SERVER_PATH"
if [[ -z "$MINECRAFT_SERVER_PATH" ]]; then if [[ -z "$MINECRAFT_SERVER_PATH" ]]; then
echo "Error: MINECRAFT_SERVER_PATH environment variable is not set." echo "Error: MINECRAFT_SERVER_PATH environment variable is not set."

View File

@@ -4,15 +4,44 @@ set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
# Load project config; credentials stay in the project .env. if [[ ! -r "$PROJECT_ROOT/.env" ]]; then
# shellcheck source=setup-env.sh echo "Error: $PROJECT_ROOT/.env is missing or unreadable. Copy .env.example to .env and set its values." >&2
source "$SCRIPT_DIR/setup-env.sh" exit 1
fi
load_project_env() {
local env_line env_key env_value first_char last_char
while IFS= read -r env_line || [[ -n "$env_line" ]]; do
env_line="${env_line%$'\r'}"
[[ "$env_line" =~ ^[[:space:]]*(#|$) ]] && continue
[[ "$env_line" == *=* ]] || continue
env_key="${env_line%%=*}"
env_value="${env_line#*=}"
env_key="${env_key#"${env_key%%[![:space:]]*}"}"
env_key="${env_key%"${env_key##*[![:space:]]}"}"
[[ "$env_key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue
env_value="${env_value#"${env_value%%[![:space:]]*}"}"
env_value="${env_value%"${env_value##*[![:space:]]}"}"
if (( ${#env_value} >= 2 )); then
first_char="${env_value:0:1}"
last_char="${env_value:$((${#env_value} - 1)):1}"
if [[ "$first_char" == "$last_char" && ( "$first_char" == '"' || "$first_char" == "'" ) ]]; then
env_value="${env_value:1:$((${#env_value} - 2))}"
fi
fi
if [[ -z "${!env_key:-}" ]]; then
export "$env_key=$env_value"
fi
done < "$PROJECT_ROOT/.env"
}
load_project_env
# Required env: # Required env:
# MODRINTH_TOKEN # MODRINTH_TOKEN
# MODRINTH_PROJECT_ID or MODRINTH_PROJECT_SLUG # MODRINTH_PROJECT_ID (project ID or slug)
# MODRINTH_VERSION # MODRINTH_GAME_VERSIONS (optional comma-separated list; defaults to 1.21 through 1.21.7)
# MODRINTH_GAME_VERSIONS (optional, comma-separated list, default from project set)
# MODRINTH_LOADERS (optional, comma-separated, default paper) # MODRINTH_LOADERS (optional, comma-separated, default paper)
# MODRINTH_CHANGELOG (optional) # MODRINTH_CHANGELOG (optional)
# Optional: # Optional:
@@ -20,19 +49,43 @@ source "$SCRIPT_DIR/setup-env.sh"
# MODRINTH_FILE (optional path to the jar; defaults to build/libs/*.jar) # MODRINTH_FILE (optional path to the jar; defaults to build/libs/*.jar)
MODRINTH_TOKEN="${MODRINTH_TOKEN:-}" MODRINTH_TOKEN="${MODRINTH_TOKEN:-}"
MODRINTH_PROJECT_ID="${MODRINTH_PROJECT_ID:-${MODRINTH_PROJECT_SLUG:-5NYwxysp}}" MODRINTH_PROJECT_ID="${MODRINTH_PROJECT_ID:-5NYwxysp}"
MODRINTH_VERSION="${MODRINTH_VERSION:-${VERSION:-$(grep -E '^version=' gradle.properties | head -n1 | cut -d= -f2-)}}"
MODRINTH_CHANGELOG="${MODRINTH_CHANGELOG:-Auto release via publish-modrinth.sh}" MODRINTH_CHANGELOG="${MODRINTH_CHANGELOG:-Auto release via publish-modrinth.sh}"
MODRINTH_GAME_VERSIONS="${MODRINTH_GAME_VERSIONS:-1.21,1.21.1,1.21.2,1.21.3,1.21.4,1.21.5,1.21.6,1.21.7}" MODRINTH_GAME_VERSIONS="${MODRINTH_GAME_VERSIONS:-1.21,1.21.1,1.21.2,1.21.3,1.21.4,1.21.5,1.21.6,1.21.7}"
MODRINTH_LOADERS="${MODRINTH_LOADERS:-paper}" MODRINTH_LOADERS="${MODRINTH_LOADERS:-paper}"
MODRINTH_VERSION_TYPE="${MODRINTH_VERSION_TYPE:-}"
MODRINTH_FILE="${MODRINTH_FILE:-}" MODRINTH_FILE="${MODRINTH_FILE:-}"
MODRINTH_DEPENDENCIES="${MODRINTH_DEPENDENCIES:-}" MODRINTH_DEPENDENCIES="${MODRINTH_DEPENDENCIES:-}"
MODRINTH_VERSION=$(
"$PROJECT_ROOT/gradlew" -q -p "$PROJECT_ROOT" properties --property version \
| sed -n 's/^version: //p'
)
if [[ -z "$MODRINTH_VERSION" ]]; then
echo "Error: could not determine the project version from Gradle." >&2
exit 1
fi
if [[ -z "$MODRINTH_VERSION_TYPE" ]]; then
if [[ "$MODRINTH_VERSION" == *-* ]]; then
MODRINTH_VERSION_TYPE="beta"
else
MODRINTH_VERSION_TYPE="release"
fi
fi
case "$MODRINTH_VERSION_TYPE" in
release|beta|alpha) ;;
*) echo "Error: MODRINTH_VERSION_TYPE must be release, beta, or alpha." >&2; exit 1 ;;
esac
MODRINTH_VERSION_NAME="ScoreKeeper $MODRINTH_VERSION"
if [[ -n "$MODRINTH_FILE" && "$MODRINTH_FILE" != /* ]]; then
MODRINTH_FILE="$PROJECT_ROOT/$MODRINTH_FILE"
fi
if [[ -z "$MODRINTH_TOKEN" ]]; then if [[ -z "$MODRINTH_TOKEN" ]]; then
echo "Error: MODRINTH_TOKEN is not set in $PROJECT_ROOT/.env" >&2 echo "Error: MODRINTH_TOKEN is not set in $PROJECT_ROOT/.env" >&2
exit 1 exit 1
fi fi
if [[ -z "$MODRINTH_FILE" ]]; then if [[ -z "$MODRINTH_FILE" ]]; then
MODRINTH_FILE=$(ls -t "$PROJECT_ROOT"/build/libs/*.jar 2>/dev/null | grep -v -- '-all\.jar$' | head -n1 || true) MODRINTH_FILE=$(ls -t "$PROJECT_ROOT"/build/libs/*.jar 2>/dev/null | grep -v -- '-all\.jar$' | head -n1 || true)
fi fi
@@ -40,27 +93,61 @@ if [[ -z "$MODRINTH_FILE" || ! -f "$MODRINTH_FILE" ]]; then
echo "Error: no jar found for Modrinth upload. Build the project first or set MODRINTH_FILE." >&2 echo "Error: no jar found for Modrinth upload. Build the project first or set MODRINTH_FILE." >&2
exit 1 exit 1
fi fi
if ! command -v unzip >/dev/null; then
echo "Error: 'unzip' is required to verify the plugin version in the jar." >&2
exit 1
fi
JAR_VERSION=$(unzip -p "$MODRINTH_FILE" plugin.yml 2>/dev/null | sed -n 's/^version: //p' | head -n1 || true)
if [[ -z "$JAR_VERSION" ]]; then
echo "Error: could not read the plugin version from $MODRINTH_FILE." >&2
exit 1
fi
if [[ "$JAR_VERSION" != "$MODRINTH_VERSION" ]]; then
echo "Error: jar version $JAR_VERSION does not match Gradle version $MODRINTH_VERSION. Rebuild the plugin and retry." >&2
exit 1
fi
csv_to_json_array() { csv_to_json_array() {
jq -cn --arg csv "$1" '$csv | split(",") | map(gsub("^\\s+|\\s+$"; "")) | map(select(length > 0))' jq -cn --arg csv "$1" '$csv | split(",") | map(gsub("^\\s+|\\s+$"; "")) | map(select(length > 0))'
} }
MODRINTH_GAME_VERSIONS_JSON=$(csv_to_json_array "$MODRINTH_GAME_VERSIONS") MODRINTH_GAME_VERSIONS_JSON=$(csv_to_json_array "$MODRINTH_GAME_VERSIONS")
MODRINTH_LOADERS_JSON=$(csv_to_json_array "$MODRINTH_LOADERS") MODRINTH_LOADERS_JSON=$(csv_to_json_array "$MODRINTH_LOADERS")
if [[ -n "$MODRINTH_DEPENDENCIES" ]]; then if [[ -n "$MODRINTH_DEPENDENCIES" ]]; then
MODRINTH_DEPENDENCIES_ARG=(--form "dependencies=$MODRINTH_DEPENDENCIES") if ! MODRINTH_DEPENDENCIES_JSON=$(jq -ce 'if type == "array" then . else error("dependencies must be a JSON array") end' <<<"$MODRINTH_DEPENDENCIES"); then
echo "Error: MODRINTH_DEPENDENCIES must be a JSON array." >&2
exit 1
fi
else else
MODRINTH_DEPENDENCIES_ARG=() MODRINTH_DEPENDENCIES_JSON='[]'
fi fi
curl -fsSL \ MODRINTH_DATA=$(jq -cn \
-X POST "https://api.modrinth.com/v2/version" \ --arg project_id "$MODRINTH_PROJECT_ID" \
-H "Authorization: $MODRINTH_TOKEN" \ --arg name "$MODRINTH_VERSION_NAME" \
-F "project_id=$MODRINTH_PROJECT_ID" \ --arg version_number "$MODRINTH_VERSION" \
-F "version_number=$MODRINTH_VERSION" \ --arg version_type "$MODRINTH_VERSION_TYPE" \
-F "changelog=$MODRINTH_CHANGELOG" \ --arg changelog "$MODRINTH_CHANGELOG" \
-F "game_versions=${MODRINTH_GAME_VERSIONS_JSON}" \ --argjson featured false \
-F "loaders=${MODRINTH_LOADERS_JSON}" \ --argjson dependencies "$MODRINTH_DEPENDENCIES_JSON" \
-F "file=@$MODRINTH_FILE" \ --argjson game_versions "$MODRINTH_GAME_VERSIONS_JSON" \
"${MODRINTH_DEPENDENCIES_ARG[@]}" \ --argjson loaders "$MODRINTH_LOADERS_JSON" \
| jq . '{project_id: $project_id, name: $name, version_number: $version_number, version_type: $version_type, featured: $featured, changelog: $changelog, dependencies: $dependencies, game_versions: $game_versions, loaders: $loaders, file_parts: ["file"], primary_file: "file"}')
CURL_ARGS=(
-X POST "https://api.modrinth.com/v2/version"
-H "Authorization: $MODRINTH_TOKEN"
-F "data=$MODRINTH_DATA;type=application/json"
-F "file=@$MODRINTH_FILE"
)
HTTP_RESPONSE=$(curl -sS -w $'\n%{http_code}' "${CURL_ARGS[@]}")
HTTP_STATUS="${HTTP_RESPONSE##*$'\n'}"
HTTP_BODY="${HTTP_RESPONSE%$'\n'*}"
if [[ "$HTTP_STATUS" != 2?? ]]; then
echo "Error: Modrinth API returned HTTP $HTTP_STATUS:" >&2
if ! printf '%s\n' "$HTTP_BODY" | jq -r '.description // .error // .' >&2; then
printf '%s\n' "$HTTP_BODY" >&2
fi
exit 1
fi
printf '%s\n' "$HTTP_BODY" | jq .

View File

@@ -9,8 +9,47 @@
set -euo pipefail set -euo pipefail
TOOLS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" TOOLS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=setup-env.sh PROJECT_ROOT="$(cd "$TOOLS_DIR/.." && pwd)"
source "$TOOLS_DIR/setup-env.sh" if [[ ! -r "$PROJECT_ROOT/.env" ]]; then
echo "Error: $PROJECT_ROOT/.env is missing or unreadable. Copy .env.example to .env and set its values." >&2
exit 1
fi
load_project_env() {
local env_line env_key env_value first_char last_char
while IFS= read -r env_line || [[ -n "$env_line" ]]; do
env_line="${env_line%$'\r'}"
[[ "$env_line" =~ ^[[:space:]]*(#|$) ]] && continue
[[ "$env_line" == *=* ]] || continue
env_key="${env_line%%=*}"
env_value="${env_line#*=}"
env_key="${env_key#"${env_key%%[![:space:]]*}"}"
env_key="${env_key%"${env_key##*[![:space:]]}"}"
[[ "$env_key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue
env_value="${env_value#"${env_value%%[![:space:]]*}"}"
env_value="${env_value%"${env_value##*[![:space:]]}"}"
if (( ${#env_value} >= 2 )); then
first_char="${env_value:0:1}"
last_char="${env_value:$((${#env_value} - 1)):1}"
if [[ "$first_char" == "$last_char" && ( "$first_char" == '"' || "$first_char" == "'" ) ]]; then
env_value="${env_value:1:$((${#env_value} - 2))}"
fi
fi
if [[ -z "${!env_key:-}" ]]; then
export "$env_key=$env_value"
fi
done < "$PROJECT_ROOT/.env"
}
load_project_env
MINECRAFT_SERVER_PATH="${MINECRAFT_SERVER_PATH:-MCServer}"
MINECRAFT_SERVER_PATH="${MINECRAFT_SERVER_PATH/#\~/$HOME}"
[[ "$MINECRAFT_SERVER_PATH" == /* ]] || MINECRAFT_SERVER_PATH="$PROJECT_ROOT/$MINECRAFT_SERVER_PATH"
MINECRAFT_BACKUP_PATH="${MINECRAFT_BACKUP_PATH:-backups}"
MINECRAFT_BACKUP_PATH="${MINECRAFT_BACKUP_PATH/#\~/$HOME}"
[[ "$MINECRAFT_BACKUP_PATH" == /* ]] || MINECRAFT_BACKUP_PATH="$PROJECT_ROOT/$MINECRAFT_BACKUP_PATH"
ASSUME_YES=false ASSUME_YES=false
SAFETY_BACKUP=true SAFETY_BACKUP=true

View File

@@ -1,39 +0,0 @@
#!/usr/bin/env bash
# Source (bash or zsh) to export the shared server config from ../.env
# (relative to this script):
# PAPER_VERSION, PAPER_BUILD, MINECRAFT_SERVER_PATH, MINECRAFT_SERVER_JAR, MINECRAFT_BACKUP_PATH
_setup_env_self="${BASH_SOURCE[0]:-${(%):-%x}}"
_setup_env_root="$(cd "$(dirname "$_setup_env_self")/.." && pwd)"
_setup_env_file="${MINECRAFT_ENV_FILE:-$_setup_env_root/.env}"
if [[ -f "$_setup_env_file" ]]; then
while IFS= read -r _line || [[ -n "$_line" ]]; do
_line="${_line%$'\r'}"
[[ "$_line" =~ ^[[:space:]]*(#|$) ]] && continue
_key="${_line%%=*}"
_value="${_line#*=}"
_key="${_key//[[:space:]]/}"
[[ "$_key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue
_value="${_value#\"}"; _value="${_value%\"}"
_value="${_value#\'}"; _value="${_value%\'}"
eval "_current=\"\${$_key:-}\""
[[ -z "$_current" ]] && export "$_key=$_value"
done < "$_setup_env_file"
fi
PAPER_VERSION="${PAPER_VERSION:-}"
PAPER_BUILD="${PAPER_BUILD:-}"
MINECRAFT_SERVER_PATH="${MINECRAFT_SERVER_PATH:-MCServer}"
MINECRAFT_SERVER_PATH="${MINECRAFT_SERVER_PATH/#\~/$HOME}"
[[ "$MINECRAFT_SERVER_PATH" == /* ]] || MINECRAFT_SERVER_PATH="$_setup_env_root/$MINECRAFT_SERVER_PATH"
MINECRAFT_BACKUP_PATH="${MINECRAFT_BACKUP_PATH:-backups}"
MINECRAFT_BACKUP_PATH="${MINECRAFT_BACKUP_PATH/#\~/$HOME}"
[[ "$MINECRAFT_BACKUP_PATH" == /* ]] || MINECRAFT_BACKUP_PATH="$_setup_env_root/$MINECRAFT_BACKUP_PATH"
if [[ -z "${MINECRAFT_SERVER_JAR:-}" && -n "$PAPER_VERSION" && -n "$PAPER_BUILD" ]]; then
MINECRAFT_SERVER_JAR="paper-${PAPER_VERSION}-${PAPER_BUILD}.jar"
fi
export PAPER_VERSION PAPER_BUILD MINECRAFT_SERVER_PATH MINECRAFT_SERVER_JAR MINECRAFT_BACKUP_PATH
unset _setup_env_self _setup_env_root _setup_env_file _line _key _value _current

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Downloads (if missing) and runs a Paper server via the Fill v3 API. # Downloads (if missing) and runs a Paper server via the Fill v3 API.
# Server settings come from ../.env relative to this script (see setup-env.sh). # Server settings come from the project .env file.
# #
# Env vars: # Env vars:
# JAVA_OPTS Extra JVM args (default: -Xms2G -Xmx2G) # JAVA_OPTS Extra JVM args (default: -Xms2G -Xmx2G)
@@ -8,8 +8,47 @@
set -euo pipefail set -euo pipefail
TOOLS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" TOOLS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=setup-env.sh PROJECT_ROOT="$(cd "$TOOLS_DIR/.." && pwd)"
source "$TOOLS_DIR/setup-env.sh" if [[ ! -r "$PROJECT_ROOT/.env" ]]; then
echo "Error: $PROJECT_ROOT/.env is missing or unreadable. Copy .env.example to .env and set its values." >&2
exit 1
fi
load_project_env() {
local env_line env_key env_value first_char last_char
while IFS= read -r env_line || [[ -n "$env_line" ]]; do
env_line="${env_line%$'\r'}"
[[ "$env_line" =~ ^[[:space:]]*(#|$) ]] && continue
[[ "$env_line" == *=* ]] || continue
env_key="${env_line%%=*}"
env_value="${env_line#*=}"
env_key="${env_key#"${env_key%%[![:space:]]*}"}"
env_key="${env_key%"${env_key##*[![:space:]]}"}"
[[ "$env_key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue
env_value="${env_value#"${env_value%%[![:space:]]*}"}"
env_value="${env_value%"${env_value##*[![:space:]]}"}"
if (( ${#env_value} >= 2 )); then
first_char="${env_value:0:1}"
last_char="${env_value:$((${#env_value} - 1)):1}"
if [[ "$first_char" == "$last_char" && ( "$first_char" == '"' || "$first_char" == "'" ) ]]; then
env_value="${env_value:1:$((${#env_value} - 2))}"
fi
fi
if [[ -z "${!env_key:-}" ]]; then
export "$env_key=$env_value"
fi
done < "$PROJECT_ROOT/.env"
}
load_project_env
PAPER_VERSION="${PAPER_VERSION:-}"
PAPER_BUILD="${PAPER_BUILD:-}"
MINECRAFT_SERVER_JAR="${MINECRAFT_SERVER_JAR:-}"
MINECRAFT_SERVER_PATH="${MINECRAFT_SERVER_PATH:-MCServer}"
MINECRAFT_SERVER_PATH="${MINECRAFT_SERVER_PATH/#\~/$HOME}"
[[ "$MINECRAFT_SERVER_PATH" == /* ]] || MINECRAFT_SERVER_PATH="$PROJECT_ROOT/$MINECRAFT_SERVER_PATH"
[[ -n "$PAPER_VERSION" ]] || { echo "Error: PAPER_VERSION is not set (see .env)." >&2; exit 1; } [[ -n "$PAPER_VERSION" ]] || { echo "Error: PAPER_VERSION is not set (see .env)." >&2; exit 1; }