40 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
b122200f5d Adds and fixes build scripts. 2026-09-26 17:47:55 -07:00
1a879be8b7 Script cleanup. 2026-09-26 13:44:44 -07:00
81da9ece26 Merge branch 'develop' 2026-09-24 19:30:32 -07:00
3f49117286 Merge remote-tracking branch 'oldgh/wt/t_a0f48f2a' into temp-merge 2026-09-24 19:27:47 -07:00
3d6195e15d Merge remote-tracking branch 'oldgh/wt/t_2b93fd59' into temp-merge 2026-09-24 19:26:19 -07:00
be91726ccb Merge remote-tracking branch 'oldgh/wt/t_710fadae' into temp-merge 2026-09-24 19:25:00 -07:00
78cd1fbdf0 Adds project description files. 2026-09-24 18:27:22 -07:00
4bb0046b26 docs: add Project.md team reference doc
Lands the synthesized 8-section project reference at the repo root so team
members can understand ScoreKeeper without reading the whole codebase.
Cross-checked against live source: in-memory HashMap<UUID,Integer> scores,
five /score-* commands, /score-archive + persistence as unimplemented stubs.
Sourced from completed children t_2b93fd59 / t_1f4982b3 / t_f5d60eac /
t_710fadae.
2026-09-24 14:16:46 -07:00
c3d76e84f2 docs: Add Project.md reference doc for ScoreKeeper project 2026-09-24 14:01:45 -07:00
03232e90f6 docs: add domain analysis for score tracking & high-score table
Source-grounded write-up (docs/domain-score-tracking.md) covering the
score-entry data model, recording mechanism, the (unimplemented) high-score
table, and scoring formulas, with full file:line citations and edge-case
walk-through. Key finding: live in-memory HashMap<UUID,Integer> only; no
persistence, no high-score table, no formula — the title's 'high-score
table' is an aspirational stub (/score-archive unimplemented).
2026-09-24 13:46:12 -07:00
1e19b4cf4d Document plugin integration and event/command wiring (t_f5d60eac) 2026-09-24 13:24:13 -07:00
Tom Hicks
fefa4a5ecc Adds spotlessCheck and build to the release process. 2026-09-23 21:42:04 -07:00
6d4cffed16 Adds project description docs. 2026-09-23 21:39:36 -07:00
16be005595 Adds .worktrees to gitignore. 2026-09-23 19:57:17 -07:00
fa9d422eca Adds java version to gradle config so it automatically downloads. 2026-06-26 16:24:23 -07:00
Tom Hicks
0c60e4bd0c Adds Windows specific info and powershell scripts to CONTRIBUTING.md. 2025-08-06 20:39:24 -07:00
Tom Hicks
e769ba7088 Enables Null annotation handling. 2025-08-06 20:00:01 -07:00
Tom Hicks
6efed9abf2 Removes improperly added eclipse settings. 2025-08-06 19:59:41 -07:00
Tom Hicks
bd0b4e38aa Updates gradle wrapper to version 8.14.3. 2025-08-06 19:56:54 -07:00
Tom Hicks
eb8bc5ab45 Adds Powershell scripts to tools. 2025-08-06 19:55:54 -07:00
Tom Hicks
76656e471f Adds spotlessCheck and build to the release process. 2025-07-16 05:02:28 -07:00
Tom Hicks
7c3c703fc9 Changes version tagging for releases. 2025-07-16 03:21:26 -07:00
Tom Hicks
815d0be2d8 Makes the release plugin also build the release jar. 2025-07-16 03:20:31 -07:00
Tom Hicks
42e8f6078e [Gradle Release Plugin] - new version commit: '0.2.2-SNAPSHOT'. 2025-07-16 03:20:07 -07:00
Tom Hicks
c0ac52b40a Removes version from build.gradle. 2025-07-16 03:10:10 -07:00
Tom Hicks
e9c53a1b24 Added paper as an ignored snapshot dependency. 2025-07-16 02:57:02 -07:00
49 changed files with 3546 additions and 356 deletions

24
.env.example Normal file
View File

@@ -0,0 +1,24 @@
# Configuration for tools/*.sh. Values are read as KEY=value data, not executed.
# Unquoted values may contain spaces; matching outer quotes are removed.
# Paper server
PAPER_VERSION=26.2
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
# Relative paths are resolved from the project root; ~/ is expanded.
MINECRAFT_SERVER_PATH=./server
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)$'

5
.gitignore vendored
View File

@@ -1,3 +1,8 @@
.gradle/
build/
target/
.worktrees/
bin/
/backups/
/server/
.env

View File

@@ -1,5 +0,0 @@
#Sun Mar 04 01:03:26 PST 2012
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding//src/main/resources=UTF-8
encoding/<project>=UTF-8

View File

@@ -1,2 +0,0 @@
eclipse.preferences.version=1
org.eclipse.jdt.apt.aptEnabled=false

View File

@@ -1,10 +0,0 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.classpath.outputOverlappingAnotherSource=ignore
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore
org.eclipse.jdt.core.compiler.processAnnotations=disabled
org.eclipse.jdt.core.compiler.release=disabled
org.eclipse.jdt.core.compiler.source=1.8

View File

@@ -1,5 +0,0 @@
#Sun Feb 19 04:11:11 PST 2012
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

12
.vscode/settings.json vendored
View File

@@ -1,6 +1,10 @@
{
"[java]": {
"editor.formatOnSave": true
},
"java.configuration.updateBuildConfiguration": "interactive"
"[java]": {
"editor.formatOnSave": true
},
"java.configuration.updateBuildConfiguration": "interactive",
"java.compile.nullAnalysis.mode": "automatic",
"chat.tools.terminal.autoApprove": {
"printf": true
}
}

View File

@@ -3,44 +3,154 @@
Thank you for your interest in contributing to the ScoreKeeper plugin! This guide will help you set up your development environment and follow best practices for working with the project.
## Development Environment Setup
# Getting Started
Pick a folder to hold your minecraft server and this project I'm going to use `$HOME/Projects`. My Minecraft server will be in `$HOME/Projects/MCServer` and this project will be in `$HOME/Projects/ScoreKeeper`.
To develop and test the ScoreKeeper plugin, you will need:
- A Paper Minecraft server (for plugin deployment and testing)
- The official Minecraft Java Edition client (for connecting to your test server)
Setup our project folder.
### 1. Setting up the Paper Server (macOS/Linux/WSL)
1. Download the latest Paper server jar from [https://papermc.io/downloads](https://papermc.io/downloads).
2. Create a directory for your test server and place the Paper jar inside.
3. Set the following environment variables in your shell profile (e.g., `.bashrc`, `.zshrc`, or manually in your terminal):
```bash
export MINECRAFT_SERVER_PATH=/path/to/your/server
export MINECRAFT_SERVER_JAR=paper-<version>.jar # Can be relative to MINECRAFT_SERVER_PATH or absolute
```
4. Use the provided scripts to manage your server:
- To start (or restart) the server: `tools/bash/start-server.sh`
- To stop the server: `tools/bash/stop-server.sh`
These scripts use the environment variables above to locate and manage your server.
5. On first run, accept the EULA by editing `eula.txt` and setting `eula=true` in your server directory.
6. Place your built plugin jar in the `plugins/` directory.
7. Use the start script again to restart the server and load the plugin.
**Linux, macOS, and WSL**
```bash
PROJECTS_DIR="$HOME/Projects"
MINECRAFT_SERVER_PATH="$PROJECTS_DIR/MCServer"
# Set this to the latest download url on the Paper downloads page [https://papermc.io/downloads](https://papermc.io/downloads) and update the jar name.
MINECRAFT_SERVER_DOWNLOAD_URI="https://fill-data.papermc.io/v1/objects/fb73c7e310215016955617ab957022d9e1d47aeba206df3a98c5ecb43756527c/paper-1.21.8-25.jar"
MINECRAFT_SERVER_JAR="paper-1.21.8-25.jar"
mkdir -p "$MINECRAFT_SERVER_PATH"
# Keep this shell open we will use these variables later.
```
### 2. Setting up the Minecraft Client
- **macOS/Linux:**
**Windows**
```powershell
$projectsDir="$HOME\Projects"
$minecraftServerDir="$projectsDir\MCServer"
# Set this to the latest download url on the Paper downloads page [https://papermc.io/downloads](https://papermc.io/downloads) and update the jar name.
$minecraftServerDownloadUri="https://fill-data.papermc.io/v1/objects/fb73c7e310215016955617ab957022d9e1d47aeba206df3a98c5ecb43756527c/paper-1.21.8-25.jar"
$minecraftServerJar="paper-1.21.8-25.jar"
New-Item -Type Directory $projectsDir
New-Item -Type Directory $minecraftServerDir
# Keep this shell open we will use these variables later.
```
## Install the JDK
**Linux / WSL**
```bash
apt install openjdk-21-jdk
```
**macOS**
```zsh
brew install --cask microsoft-openjdk@21
```
**Windows**
From Powershell
```powershell
winget install --id Microsoft.OpenJDK.21 --source winget
```
## Setup a PaperMC Server
**Linux, macOS, and WSL**
```bash
# You're probably still here, but if not go to the server dir.
cd "$MINECRAFT_SERVER_PATH"
curl -O "$MINECRAFT_SERVER_DOWNLOAD_URI"
java -jar "$MINECRAFT_SERVER_JAR"
nano eula.txt # Change eula=false to eula=true, then save and exit.
java -jar "$MINECRAFT_SERVER_JAR"
```
**Windows**
```powershell
# You're probably still here, but if not go to the server dir.
Set-Location $minecraftServerDir
Invoke-WebRequest -Uri $minecraftServerDownloadUri -OutFile (Split-Path $minecraftServerDownloadUri -Leaf)
java -jar $minecraftServerJar
notepad eula.txt
# Change eula=false to eula=true, then save and close the file.
java -jar $minecraftServerJar
```
If you get windows security popups about java with the little java dude allow them. It's because the server is listening on the network. Now you should have the server running and be dropped at a prompt like `> `. Type `stop` and hit enter to kill the server. You can also try CTRL + C.
## Get the Code
**Linux, macOS, and WSL**
```bash
cd "$PROJECTS_DIR"
git clone https://github.com/headhunter45/ScoreKeeper.git
code ScoreKeeper
```
```powershell
Set-Location $projectsDir
git clone https://github.com/headhunter45/ScoreKeeper.git
# Then to open VSCode
code ScoreKeeper
```
## Building the Plugin
This should download the preferred version of our build tool (gradle) and use it to build the project. Among other intermediate files it will create `build/libs/ScoreKeeper-${Version}.jar`. This is the plugin jar that you copy to the minecraft server to install the plugin. From now on you will use the utility scripts in `tools\powershell\*.ps1` or `tools/bash/*.sh` to build and deploy the plugin to our test server.
**Linux, macOS, and WSL**
```bash
./gradlew build
```
**Windows**
```powershell
.\gradlew.bat build
```
## Using the Utility Scripts
Our scripts depend on two environment variables. You can set them each time you open a shell or set them once for every shell your user opens. The variables are `MINECRAFT_SERVER_PATH` and `MINECRAFT_SERVER_JAR`. They are used by the scripts to know where the server is so they can control it and deploy the plugin.
**Linux, macOS, and WSL**
To set them for the current session run these commands. To set for every new session add these commands to your `.bashrc` or `.zshrc` file.
```bash
MINECRAFT_SERVER_PATH="$HOME/Projects/MCServer"
MINECRAFT_SERVER_JAR="paper-1.21.8-25.jar"
```
**Windows**
To set them for a single session run these commands.
```powershell
$env:MINECRAFT_SERVER_PATH = "$HOME\Projects\MCServer"
$env:MINECRAFT_SERVER_JAR = "paper-1.21.8-25.jar"
```
If you want them available in all of your powershell sessions you can set them permanently like this.
```powershell
[Environment]::SetEnvironmentVariable("MINECRAFT_SERVER_PATH", "$HOME\Projects\MCServer", "User")
[Environment]::SetEnvironmentVariable("MINECRAFT_SERVER_JAR", "paper-1.21.8-25.jar", "User")
```
### Start-Server.ps1 and start-server.sh
Run `tools\powershell\Start-Server.ps1` or `tools/bash/start-server.sh` to start the server and open a GUI to manage it.
### Stop-Server.ps1 and stop-server.sh
Run `tools\powershell\Stop-Server.ps1` or `tools/bash/stop-server.sh` to stop the server. You can also safely close the GUI.
### Build-Plugin.ps1 and build-plugin.sh
Run `tools\powershell\Build-Plugin.ps1` or `tools/bash/build-plugin.sh` to build the plugin. This builds the plugin in `build/libs` as a jar named `ScoreKeeper-${VERSION}.jar`. To install the plugin manually you can copy this to `$env:MINECRAFT_SERVER_PATH\plugins` or `$MINECRAFT_SERVER_PATH/plugins` and restart the server.
### Deploy-Plugin.ps1 and deploy-plugin.sh
Run `tools\powershell\Deploy-Plugin.ps1` or `tools/bash/deploy-plugin.sh` to copy the plugin to the server plugins directory. This checks if the built plugin is up to date with the source code. If it is, then the script copies the plugin to the plugins directory to install it. To use the new plugin restart the server.
# Setting up the Minecraft Client
- **macOS / Linux:**
- Download and install the official Minecraft Launcher from [minecraft.net](https://www.minecraft.net/en-us/download).
- Log in with your Mojang/Microsoft account and launch the Java Edition client.
- **WSL (Windows Subsystem for Linux):**
- **Windows / WSL (Windows Subsystem for Linux):**
- For best performance, run the Minecraft client directly under Windows, not inside WSL.
- Download and install the official Minecraft Launcher for Windows from [minecraft.net](https://www.minecraft.net/en-us/download).
- Use WSL for server and plugin development, and connect to your test server from the Windows client.
### 3. Connecting the Client to Your Server
# Connecting the Client to Your Server
- Start your Paper server (see above).
- In the Minecraft client, add a new server with the address:
- `localhost` (if running both client and server on the same machine)
- Or use your machine's IP address if connecting across devices.
### 4. Notes
- You can automate server startup and plugin deployment with bash scripts for faster testing.
- For automated testing or CI, run the Paper server in a headless Linux environment (including WSL, Docker, or CI runners).
# Notes
- Always use the provided scripts and environment variables for consistent server management.

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": []
}
}

280
Project.md Normal file
View File

@@ -0,0 +1,280 @@
# ScoreKeeper — Project Reference
> **For a developer joining the team cold.** Read top-to-bottom in ~8 minutes;
> you'll know where to look and what's real vs. planned on day one.
---
## 1. What is ScoreKeeper?
ScoreKeeper is a **Paper Minecraft plugin** (Java 21, Bukkit/Adventure APIs) that manages player
score tracking. It exposes five in-game/console commands (`/score-get`, `/score-add`,
`/score-subtract`, `/score-reset`, `/score-archive`) for manual score manipulation — no events,
no timers, no automation.
**State of the project:** live in-memory scores work today; the \"high-score table\" advertised
in the README name and `/score-archive` description is **not implemented**. Persistence, ranking,
and scoring formulas are all **future scope**. See §4 for the gap between *what exists* and
*what is planned*.
---
## 2. Tech Stack & Build
| Item | Value |
|------|-------|
| Language | Java 21 (Gradle auto-downloads toolchain) |
| Runtime target | Paper 1.21.7 (Bukkit + Adventure APIs) |
| Build tool | Gradle 8.14.3 (`gradlew`) |
| Linting | Spotless (`googleJavaFormat()` + license header from `config/license-header.txt`) |
| 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. |
| 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
```bash
./gradlew build # compiles, runs tests (none yet)
./gradlew spotlessApply # format to project style
./gradlew assemble # produces jar in build/libs/
```
Drop the resulting jar onto a Paper server's `plugins/` directory.
---
## 3. Architecture Overview
### Directory layout
```
├── src/main/java/com/majinnaibu/minecraft/plugins/scorekeeper/
│ ├── ScoreKeeperPlugin.java ← entry point, onEnable/onDisable, score CRUD core
│ └── commands/
│ ├── ScoreGetCommand.java → /score-get [player]
│ ├── ScoreAddCommand.java → /score-add [player] <amount>
│ ├── ScoreSubtractCommand.java → /score-subtract [player] <amount>
│ ├── ScoreResetCommand.java → /score-reset [player]
│ └── ScoreArchiveCommand.java → /score-archive [player] (stub)
├── src/main/resources/
│ └── plugin.yml ← command manifest + main-class declare
├── tools/bash/ & tools/powershell/ ← dev helper scripts
├── config/license-header.txt ← Spotless license header
├── build.gradle ← Gradle build config (above)
├── gradle.properties ← version, group coordinates
├── CONTRIBUTING.md ← dev env setup
└── README.md ← user-facing command reference + notes
```
### Data flow (text diagram)
```
ADMIN / CONSOLE / RCON ──▶ types a /score-* command
│
▼
┌──────────────────────┐
│ 5× Score*Command.java│ executors parse args,
│ resolves target │ resolvePlayerExact(name) (online-only)
└──────────┬───────────┘
│ calls
▼
┌──────────────────────────────┐
│ ScoreKeeperPlugin │
│ │
│ addScore / subtractScore │ read-modify-write
│ resetScore / setScore │
│ getScore (read) │
│ archiveScore (STUB — no-op) │
└──────────┬───────────────────┘
│
▼
HashMap<UUID, Integer> ← in RAM only
_playerScores ← ScoreKeeperPlugin:38
```
**Key architectural facts:**
- **Single class owns everything.** `ScoreKeeperPlugin` holds the scores map, score CRUD
methods, logging helpers (logWarning/logInfo/logError), and the Adventure component builder
for chat color. There is no service layer or boundary separation.
- **No event listeners.** Zero `@EventHandler`/`Listener` registrations across the codebase.
Game events (join, death, kill) do not affect scores. Only manual commands change state.
- **No scheduler or tick logic.** No periodic tasks, no countdowns, no automated scoring.
- **No permission nodes.** Every command is available to every sender (player, console, RCON).
### File: ScoreKeeperPlugin.java (`ScoreKeeperPlugin`)
- `main` class in `plugin.yml` (Bukkit plugin entry point)
- `HashMap<UUID, Integer> _playerScores` at line 38 — the sole score store
- `onEnable()` (line 52): wires five command executors, logs \"load not implemented\" warning
- `onDisable()` (line 46): logs \"save not implemented\" warning — scores lost on shutdown
- Score CRUD methods: `addScore`, `subtractScore`, `resetScore`, `setScore`, `getScore`,
`archiveScore` (lines 67–91, 76–86, 72–74)
- Private helpers: `getPlayerScore(Player)` (get-or-create at 0), `setPlayerScore(Player,int)`
---
## 4. Domain Model & Scoring Logic
### 4.1 What exists today (REAL — in code)
| Aspect | Detail | Source |
|--------|--------|--------|
| Score model | Single `int` per player, keyed by UUID | `ScoreKeeperPlugin:38` |
| Storage container | `HashMap<UUID, Integer>` on plugin instance | same file |
| Default value | `0` — lazy-created on first map access | `getPlayerScore:100-106` |
| Live only | **No persistence.** Scores erased on server restart | `onEnable:59`, `onDisable:47` |
| Scoring direction | Any integer (negatives allowed, no floor) | add/subtract are raw `+`/`-` |
| Recording method | Manual commands only — `/score-add`, `/score-subtract` | command executors |
| Auto-scoring | **None** — no events, no timers | proven by grep across src/ |
| Permissions | **None declared.** All commands open to all senders | `plugin.yml`, no permission guard in code |
### 4.2 Open Score Lifecycle (what exists + what is planned)
```
Stage 1. First access — getPlayerScore() auto-creates key at 0 [REAL]
2. Admin runs /score-add player N or /score-subtract [REAL]
3. Player accumulates points over the session [REAL]
4. Read via /score-get (read-only, lazily registers) [REAL]
5. Server restart — scores LOST on shutdown [REAL]
6. Intended: /score-archive freezes score → table [GAP ✓ not built]
7. Intended: high-score table display command [GAP ✓ not built]
```
### 4.3 The "high-score table" — status
| Feature | Status | Details |
|---------|--------|---------|
| `/score-archive` | **Stub** | Command prints \"archive command unimplemented\"; `archiveScore()` method only logs, never writes a table or resets the player's score |
| Persistence (save) | **Not built** | `onDisable()` is a TODO stub — map discarded at shutdown |
| Persistence (load) | **Not built** | `onEnable()` is a TODO stub — map always starts empty `{}` |
| Sorting / ranking | **Not coded** | No sort, no tie-breaking, no entry cap, no decay logic exists |
| Scoring formulas | **Not coded** | Scores are plain integer accumulators (`Σ(adds) − Σ(subtracts)`) |
**Design decisions to be made (none answered by code today):**
- Storage format for the table (YAML per Bukkit convention; JSON? SQLite?)
- What an entry looks like (name + score + timestamp? name is not stored with score today)
- Sort order and tie-breaking strategy
- Max entries / leaderboard cap
- Whether `/score-archive` also resets the live score (README says it does)
---
## 5. Plugin Integration & Reference Table
### 5.1 Command → Handler → Effect on score data
| Trigger | Usage | Handler | Effect |
|---------|-------|---------|--------|
| `/score-get [player]` | Self or other | `ScoreGetCommand.java:38-84`, delegated to `getScore → getPlayerScore` | **Read-only.** Returns integer. Lazily creates entry at `0` if unseen. |
| `/score-add [player] <N>` | Self (omit name) or target others | `ScoreAddCommand.java` | `score += N`. Amount must parse as int. No direction validation (negative N still adds). |
| `/score-subtract [player] <N>` | Same | `ScoreSubtractCommand.java` | `score -= N`. No minimum clamping; negatives freely produced. |
| `/score-reset [player]` | Same | `ScoreResetCommand.java` | `score = 0`. Key created at `0` if absent. |
| `/score-archive [player]` | Same | `ScoreArchiveCommand.java` | **No-op.** Prints \"archive command unimplemented\". Does NOT call the `archiveScore()` method. |
### 5.2 Shared behavior details
Every executor follows this pattern:
1. Parse arguments — if `split.length == 1` and sender is a player, target = self (RCON/console
requires an explicit `<playerName>` or prints usage).
2. Resolve target player via `server.getPlayerExact(name)` — **exact, case-sensitive, online-only.**
3. Call the corresponding `ScoreKeeperPlugin` method.
4. Echo color-coded result; return `true`.
### 5.3 Inter-plugin / public API surface
`ScoreKeeperPlugin` exposes these public methods that other plugins *could* call if they hold a reference
(but there is **no formal service registration**):
| Method | Visibility | Called by commands? | Notes |
|--------|------------|---------------------|-------|
| `addScore(Player, int)` | `public` | Yes (`/score-add`) | Read-modify-write on `_playerScores` |
| `subtractScore(Player, int)` | `public` | Yes (`/score-subtract`) | Same pattern |
| `getScore(Player)` | `public` | Yes (`/score-get`) | Wrapper around `getPlayerScore` |
| `setScore(Player, int)` | `public` | **No** | Internal write path only; not hooked to any command |
| `resetScore(Player)` | `public` | Yes (`/score-reset`) | Sets to `0` |
| `archiveScore(Player)` | `public` | **No** | Only logs a warning; never called by the archive command |
### 5.4 Concurrency note
The map is a plain `HashMap`. Safe because Paper dispatches commands on the server's single main
thread — but it is **not safe for off-thread use**. Any future event-driven scoring that runs
asynchronously could corrupt state via non-atomic read-modify-write.
---
## 6. Configuration Reference
| File | Format | Purpose |
|------|--------|---------|
| `plugin.yml` | YAML (Bukkit manifest) | Declares main class, api-version, five commands + descriptions/usage strings |
| `build.gradle` | Gradle Kotlin (Groovy DSL) | Dependencies, task config, release/spotless settings |
| `gradle.properties` | Properties | Project version and group coordinates (for Maven publishing) |
| **No `config.yml`** | — | ScoreKeeper has **no player-editable configuration**. |
| **No `permissions:` block** | — | No permission nodes declared; all commands are open. Plans say \"permissions coming after archive works.\" |
---
## 7. Running & Testing Locally
### Build
```bash
./gradlew assemble # produces ScoreKeeper.jar in build/libs/
```
### Run locally (Paper server)
1. Download Paper 1.21.7 from `https://papermc.io`
2. Copy the built jar into `plugins/`
3. Start the server, verify onEnable logs:
```
[ScoreKeeper] ScoreKeeper version X.Y.Z is enabled.
[ScoreKeeper] Unable to load scores from file. This feature is not implemented yet.
```
### Commands (in-game or via RCON/console)
| Test scenario | Command | Expected output |
|--------------|---------|-----------------|
| Check own score | `/score-get` | \"Your score is 0\" (creates entry at 0) |
| Add points to self | `/score-add 10` | \"You gained 10 points! Now have 10.\" |
| Subtract from self | `/score-subtract 5` | \"You lost 5 points! Now have 5.\" |
| Check another player | `/score-get PlayerName` | \"PlayerName's score is N.\" (must be online) |
| Reset own score | `/score-reset` | \"Your score has been reset to 0.\" |
| Archive (stub) | `/score-archive` | \"archive command unimplemented\" |
### Tests
- **No unit/integration tests exist yet.** `./gradlew test` runs an empty suite. Consider
adding tests for `ScoreKeeperPlugin`'s private `Player` score state mocking in a future task.
---
## 8. Where to Look First
| I want to understand… | Go to |
|----------------------|-------|
| The entire live data model | `ScoreKeeperPlugin:38` — one `HashMap<UUID, Integer>` field |
| How scores change (write path) | `addScore(/:67-70)`, `subtractScore(/:88-91)`, `setPlayerScore(/:108-110)` |
| How a player is looked up | `getPlayerExact(name)` online only — see any `*Command.java` line ~50 |
| First-time-player behavior | `getPlayerScore(/:100-106)` — auto-inserts `0` on first access |
| High-score / archive table | **Does not exist.** See `archiveScore(/:72-74)` stub; design decisions in §4.3 |
| Persistence (save/load) | `onDisable(/:47)`, `onEnable(/:59)` — both TODO, nothing writes to disk |
| What's declared/intended but not wired | `plugin.yml:18-20` (`/score-archive`), `README.md:11` and README notes |
| Command implementations | `commands/Score*Command.java` (all 5 handlers) |
| Build/runtime config | `build.gradle`, `plugin.yml`, `gradle.properties` |
| Dev env / CONTRIBUTING | `CONTRIBUTING.md` |
---
## Appendix: Risk Summary
| # | Issue | Impact | Section |
|---|-------|--------|---------|
| 1 | **Data loss on restart** — no save/load implemented | Every server boot wipes all scores (§4.1) | §4.1 |
| 2 | **No permissions** — any player can self-add points | Integrity of scoring is unenforceable today (§5.2) | §5.2 |
| 3 | **Race condition on add/subtract** — non-atomic read-modify-write on plain `HashMap` | Corrupt state if future event-driven scoring runs async (§5.4) | §5.4 |
| 4 | **No `int` overflow safety** — Java wrapping semantics apply | Undetectable score corruption near ±2.1 billion | §4.1 |
| 5 | **Name lookups online-only & case-sensitive** | Can't target offline players; \"Alice\" ≠ \"alice\" (§5.2) | §5.2 |

23
ProjectDescription.json Normal file
View File

@@ -0,0 +1,23 @@
{
"id": "scorekeeper",
"title": "ScoreKeeper",
"description": "Paper Minecraft plugin for tracking and managing player scores.",
"docId": "ScoreKeeper",
"image": {
"url": "https://image.pollinations.ai/prompt/pixel%20art%20Minecraft%20server%20scoreboard%20with%20a%20glowing%20diamond%20and%20number%20counters%2C%20clean%20square%20game%20plugin%20thumbnail%2C%20no%20text",
"alt": "Pixel art scoreboard with a diamond for the ScoreKeeper Minecraft plugin",
"prompt": "Pixel art Minecraft server scoreboard with a glowing diamond and number counters, clean square game plugin thumbnail, no text",
"width": 1024,
"height": 1024,
"backgroundClassName": "bg-surface"
},
"url": "/projects/scorekeeper",
"tags": [],
"source": {
"type": "",
"url": ""
},
"feedback": {
"url": ""
}
}

16
ProjectDescription.md Normal file
View File

@@ -0,0 +1,16 @@
# ScoreKeeper
ScoreKeeper is a Paper Minecraft plugin for tracking player scores during server activities, events, or games. It keeps scores per player in memory and exposes commands for viewing, changing, resetting, and archiving scores.
## Details
- Built for Paper API 1.21.7 with Java 21 and Gradle.
- Registers `/score-get`, `/score-add`, `/score-subtract`, `/score-reset`, and `/score-archive`.
- Commands use the executing player when a player name is omitted.
- Scores are currently held in memory and are not persisted when the server stops.
- Score archiving is planned, but the current implementation reports that archiving is unavailable.
- The project is packaged as a Java plugin with a `plugin.yml` descriptor.
## Image
No project image asset is included in the repository. The JSON description includes a prompt-backed image URL for a future project thumbnail.

View File

@@ -4,18 +4,41 @@
### Commands
* `/score-get [playerName]` - Displays the player's score.
* `/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.
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.
NOTES:
* All commands will use the executing player in place of [playerName] if it is omitted.
* Permissions support is coming AFTER I get archive to work.
* 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-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 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
See [CONTRIBUTING.md](CONTRIBUTING.md) for development environment setup instructions.
Tooling note:
* 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
- [x] Update logger usage to use getLogger() from JavaPlugin
- [x] Remove or modernize any old/deprecated event registration (use @EventHandler and registerEvents)
- [x] Review and update player lookup logic to use getPlayerExact or handle case sensitivity
- [x] Ensure all commands are properly defined in plugin.yml
- [x] Initialize Gradle build system
- [x] Set project metadata in build.gradle
- [x] Add repositories and dependencies
- [x] Configure Java version
- [x] Ensure resource handling for plugin.yml
- [x] Add Gradle plugins as needed (e.g., Shadow)
- [x] Update .gitignore for Gradle
- [x] Remove Maven files
- [x] Update documentation and scripts
- [x] Test the Gradle build
| ID | Status | Title |
|:-----:|:--------:|:------|
| SK-01 | Done | Save scores between server launches. |
| 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. |\
| 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.
| 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}." |
| 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. |
| 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. |
| 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. |
| 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. |
| 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. |
| 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. |
| 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. |
| 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. |
| SK-13 | Ready | Add a an option to `/score-get` to get the score for a specific bucket. |

View File

@@ -2,13 +2,17 @@ plugins {
id 'com.diffplug.spotless' version '6.22.0'
id 'java-library'
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'
version = '0.2.1-SNAPSHOT'
description = "ScoreKeeper"
gitSemVer {
minimumVersion.set('0.2.1')
versionPrefix.set('v')
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
// options.compilerArgs << "-Xlint:deprecation"
@@ -24,14 +28,30 @@ dependencies {
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
// Paper 26.1+ requires Java 25.
languageVersion = JavaLanguageVersion.of(25)
}
}
tasks.named('wrapper') {
gradleVersion = '9.8.0'
distributionType = Wrapper.DistributionType.BIN
distributionBase = Wrapper.PathBase.PROJECT
distributionPath = '.gradle/wrapper/dists'
archiveBase = Wrapper.PathBase.PROJECT
archivePath = '.gradle/wrapper/dists'
}
tasks.named('updateDaemonJvm') {
languageVersion = JavaLanguageVersion.of(25)
}
def pluginVersion = project.version.toString()
processResources {
inputs.property "version", project.version
inputs.property "version", pluginVersion
filesMatching('plugin.yml') {
expand(project.properties)
expand(version: pluginVersion)
}
}
@@ -43,13 +63,6 @@ publishing {
}
}
release {
failOnSnapshotDependencies = true
revertOnFail = true
tagTemplate = '$version'
versionPropertyFile = 'gradle.properties'
}
repositories {
mavenCentral()
maven { url = 'https://repo.papermc.io/repository/maven-public/' }
@@ -57,7 +70,7 @@ repositories {
spotless {
java {
googleJavaFormat()
googleJavaFormat('1.27.0')
importOrder 'java', 'javax', 'com', 'net', 'org', ''
licenseHeaderFile 'config/license-header.txt'
target 'src/**/*.java'

View File

@@ -0,0 +1,365 @@
# ScoreKeeper — Score-Tracking & "High-Score Table" Domain Analysis
> **Scope of this document:** the domain logic that tracks player scores and (intended) the
> high-score table. Written for a new team member who must understand the scoring system
> *without opening the source*. Every claim below is traced to a file/line so it can be
> re-verified.
>
> **Bottom line up front (read this first):** ScoreKeeper currently tracks **live scores
> only, in memory, for the running server session**. It has **no persistence** and **no
> high-score table**. The high-score table is *described as a planned feature* in the
> README and is where the `/score-archive` command is *intended* to land scores, but
> **that code path is an unimplemented stub today.** There is no sorting, no tie-breaking,
> no entry cap, no decay, and no scoring formula/weighting anywhere in the codebase.
> This is a greenfield/early-stage domain — the write-up documents the *real* state and
> flags the gap, because documenting features that don't exist as if they did would mislead
> the next engineer.
---
## 0. How to read the rest of this doc against the task's four questions
The task asks for (1) the score-entry data model + persistence format, (2) how scores are
recorded, (3) the high-score-table algorithm, and (4) scoring formulas/weighting.
For each question the answer is: **the mechanism that exists vs. the mechanism the project
intends**, so readers never conflate the two.
| # | Question | Short answer |
|---|----------|--------------|
| 1 | Score-entry data model & persistence | Live score = `UUID -> int` in a `HashMap`. **No persistence** (load/save are `TODO` stubs). |
| 2 | How scores are recorded | **Manual, event-free:** the *administrator* runs a command. No game events, no timers. |
| 3 | High-score-table algorithm | **Not implemented.** No sort/tie-break/cap/decay. Only an aspirational `/score-archive`. |
| 4 | Scoring formulas / weighting | **None.** Scores are plain integer accumulators; no weighting, no decay, no bonuses. |
---
## 1. The score-entry data model & persistence *(task Q1)*
### 1.1 What a "score entry" actually is (current reality)
The entire live-score domain is **one field** in the plugin's entry-point class:
- **File:** `src/main/java/com/majinnaibu/minecraft/plugins/scorekeeper/ScoreKeeperPlugin.java:38`
- **Declaration:** `private final HashMap<UUID, Integer> _playerScores = new HashMap<UUID, Integer>();`
That is the whole model:
| Aspect | Value |
|--------|-------|
| Record shape | A single `Integer` (the score), keyed by a player's `UUID`. |
| Key type | `java.util.UUID` — the player's `UniqueId`, *not* the name string. |
| Value type | `int` (Java `Integer`), autoboxed into the map. |
| Container | one `java.util.HashMap` on the plugin instance. |
| Uniqueness | one entry per `UUID`. A player can have exactly one live score at a time. |
| Default for a new player | `0` — see §3.1 ("first-time player" edge case). |
There is **no `Score`/`ScoreEntry`/`PlayerStats` value class**, no timestamp, no
name stored alongside the score (name is looked up from the live server only — see §2.3),
and no secondary index.
### 1.2 Persistence format: **none exists**
Persistence is *intended* but *not built*. Three concrete stubs prove this:
1. **On disable (server stop):** `ScoreKeeperPlugin.java:46-49` `onDisable()` logs
*"Unable to save scores to file. This feature is not implemented yet."* — the map
is **discarded** on shutdown; nothing is written.
2. **On enable (server start):** `ScoreKeeperPlugin.java:59-60` `onEnable()` logs
*"Unable to load scores from file. This feature is not implemented yet."* — the map
always starts **empty** `{}` every server start.
3. **Archive:** `ScoreKeeperPlugin.java:72-74` `archiveScore(Player)` logs
*"Unable to archive score for <name>."* and returns — the "save to high-score table"
action is a no-op.
So there is **no SQLite, no JSON, no YAML, no flat file, no config.yml**. The only file on
disk that concerns scores is `plugin.yml` (the command manifest — it lists the commands but
stores no scores). A grep of the whole tree for `sql / json / yaml / saveResource /
YamlConfiguration / File / Files. / Gson / Jackson` finds **zero hits** other than the
TODO/log strings.
**Persistence format today = "in RAM only, lost on server restart."**
> Implication for a new engineer: any "who's the top player" question answered *across
> restarts* is impossible today. Scores reset to the map being empty on every server boot.
---
## 2. How scores are recorded *(task Q2)*
### 2.1 The recording model is **manual and command-driven — no events, no timers**
Scores move only when an administrator (or console/RCON) **types a command**. There is:
- **No** `implements Listener`, no `@EventHandler`, no `registerEvents(...)`, no
`getServer().getPluginManager().registerEvents(...)`.
- **No** scheduler: no `getScheduler()`, no `runTask`, no `Timer`.
- **No** automatic hook to game events (e.g. a player killing a mob or reaching a goal
awards points automatically — *nothing like that exists*).
A grep for `EventListener|@EventHandler|Listener|Scheduler|runTask` across `src/` returns
**zero**.
So "scoring" happens **on demand**, by a person, via one of the four mutating commands:
| Command | Effect on the map | Source |
|---------|-------------------|--------|
| `/score-add [player] <amount>` | `score += amount` | `ScoreKeeperPlugin.addScore` `:67-70` |
| `/score-subtract [player] <amount>` | `score -= amount` | `ScoreKeeperPlugin.subtractScore` `:88-91` |
| `/score-reset [player]` | `score = 0` | `ScoreKeeperPlugin.resetScore` `:80-82` |
| `/score-archive [player]` | **intended** to snapshot to a high-score table and reset to 0; **actually a no-op** | `ScoreKeeperPlugin.archiveScore` `:72-74` |
`/score-get [player]` is read-only (returns the score, §2.4).
### 2.2 The add/subtract primitives (the only real "write" path)
Both funnel through one private setter:
```
addScore(player, n) -> old = getPlayerScore(player); setPlayerScore(player, old + n) :67-70
subtractScore(player,n)-> old = getPlayerScore(player); setPlayerScore(player, old - n) :88-91
setScore(player, s) -> setPlayerScore(player, s) :84-86
resetScore(player) -> setPlayerScore(player, 0) :80-82
setPlayerScore(p, v) -> _playerScores.put(p.getUniqueId(), v) :108-110
```
Notes a new engineer must internalize:
- **Read-modify-write.** `addScore`/`subtractScore` read the current value, compute, write
back in two map operations. (There is no concurrency control — see §5 risks.)
- **`int` math.** Values are Java `int`; a score can go **negative** (there is no floor at
0 — `/score-subtract 50` on a 10-score yields `-40`), and can overflow `int` only after
`~2.1e9` points, which is not a practical concern.
- **No validation of the direction.** The only validation is *syntactic*: the amount must
parse as an integer (see §2.3).
### 2.3 Command surface (who/what is allowed to record a score)
Every command executor lives in `src/main/java/.../scorekeeper/commands/` and shares one
shape: parse args, resolve the target player, call the `ScoreKeeperPlugin` method, return
`true` (consumed). Two behavioral details matter:
- **Self-target default:** if a *player* runs a command and omits the name, they target
*themselves*: `targetPlayer = (Player) sender`. (e.g. `ScoreGetCommand.java:44`,
`ScoreAddCommand.java:48`, `ScoreResetCommand.java:47-49`.)
- **RCON/console path:** if the sender is **not** a player (console/RCON), a player name
is **required** — omitting it prints usage instead of acting
(`ScoreGetCommand.java:46-48`, `ScoreAddCommand.java:45-47`,
`ScoreResetCommand.java:44-46`).
- **Name resolution:** `getServer().getPlayerExact(name)` — **exact, case-sensitive**
lookup by the *currently online* name (`ScoreGetCommand.java:50`,
`ScoreAddCommand.java:57`, `ScoreResetCommand.java:50`). A name that is not online
yields `null` → "Can't find a player with that name". Note the *map key is a UUID*, but
*lookup by name only works while that player is online* — you cannot change an offline
player's score by name today.
- **No permission nodes anywhere.** `plugin.yml` declares no `permission:`/`permissions:`
and the code checks none. The README's note ("the commands aside from get are intended
for admins … Permissions support is coming") is **intent, not enforcement** — a vanilla
player can run `/score-add` today.
### 2.4 Reading a score (`/score-get`)
`ScoreGetCommand.java:38-84` → `ScoreKeeperPlugin.getScore(player)` → `getPlayerScore(player)`
(`ScoreKeeperPlugin.java:76-78, 100-106`). It returns the live integer (0 for a known-but-
unwritten player, which also *materializes* a 0 entry, see §3.1). Output formatting
("Your score is N" vs. "PLAYER's score is N") depends only on whether the sender is the
target or not — it carries no ranking or table.
---
## 3. The high-score-table algorithm *(task Q3)*
### 3.1 What exists: **nothing. It is aspirational.**
There is **no high-score table, no ranking structure, no sort, no tie-break rule, no max
entry count, and no decay/rotation** anywhere in the codebase. The task's premise ("the
high-score table") reflects the **product intent** in the README, not the **code**. Concretely:
- The README (`README.md:11`) says `/score-archive` *"Saves the player's score to a
'High Scores' table and resets their current score to 0."*
- The manifest (`plugin.yml:18-20`) declares `/score-archive` with that very description.
- But the command is a stub: `ScoreArchiveCommand.java:37-39` (`onCommand` body) replies
*"archive command unimplemented"*, and the underlying `archiveScore`
(`ScoreKeeperPlugin.java:72-74`) only logs and returns — it neither writes a table nor
resets anything.
Therefore the "algorithm" is: **no-op.** A new engineer asked to "implement the high-score
table" is starting from zero; the design questions in §3.2 are **open**, not answered by code.
### 3.2 Open design questions the table must settle (no code today decides these)
Since no implementation exists, these are *decisions to be made*, recorded here so the
implementation task doesn't reinvent the debate:
- **Storage/persistence format.** The load/save TODOs (`:47`, `:59`) say "to file";
`plugin.yml`/Bukkit convention favors YAML (`YamlConfiguration`), but JSON/SQLite are all
viable. **Unchosen.** Persisting to `data/` via `getDataFolder()` is the idiomatic Bukkit
path.
- **What an entry is.** Today a live score is just `{uuid -> int}`. A high-score entry
likely needs **player name + score + (timestamp?) + (date earned?)**. Name is *not*
currently stored with the score, so a durable table must capture the name at archive
time (a UUID-only entry can't render a leaderboard without the name being resolvable).
- **Sorting / ordering.** Almost certainly **descending by score**.
- **Tie-breaking.** Undefined. Candidate rules: by *score only*; by *earliest* archived
first (stable, time-ordered); by *name* (alphabetical); or "first to reach that score."
- **Max entries / cap.** Undefined. A leaderboard needs a cap (e.g. top 10 / top 30);
today there is no cap because there is no table.
- **Decay / rotation / time window.** None, and none described in docs — so the safe
default is **"scores are permanent, no decay."**
- **Reset semantics on archive.** README promises archive *resets to 0* *and* records.
`ScoreArchiveCommand` must decide: does archiving also reset? Does it allow multi-entries
(a player appearing more than once) or one row per player? All open.
### 3.3 Full lifecycle of a score: creation → (intended) display on the high-score table
This is the acceptance-criterion walk-through. Each stage is marked **[REAL]** (in code now)
or **[GAP]** (intended, not built).
1. **Player joins / acts** — a score *doesn't* exist yet. First interaction with the map is
lazy (see stage 4a). **[REAL]**
2. **Admin records a score** — `admin: /score-add Alice 10`. Parsed in `ScoreAddCommand`,
routed to `addScore`. The first time this runs for Alice, `getPlayerScore` **creates**
her entry at 0 and returns it; then `10` is written. **[REAL]**
3. **Score accumulates** — later `/score-add Alice 5` → 15; `/score-subtract Alice 2` → 13;
`/score-reset Alice` → 0. All in the in-memory map, live only. **[REAL]**
4. **Read** — `/score-get Alice` → "Alice's score is 13". No ranking shown. **[REAL]**
5. **Server restart** — `onDisable` *cannot* save (stub), `onEnable` *cannot* load (stub);
the map is **lost**. Alice's 13 is gone; every score starts empty again. **[REAL] —
this is the current data-loss reality.**
6. **Intended: archive to the high-score table** — `admin: /score-archive Alice` should
freeze Alice's 13 into a durable, sorted leaderboard and reset her live score to 0, so
it survives restarts. **[GAP]** — currently returns "archive command unimplemented".
7. **Intended: display on the high-score table** — a command (not yet built) renders the
capped, sorted list. **[GAP]** — no such command, no structure to render.
**Edge cases (explicitly, per the acceptance criteria):**
- **First-time player / first write.** A player has no map entry until `getPlayerScore` is
called, which **inserts `0` on first access** (`ScoreKeeperPlugin.java:100-106`). So a
first `/score-add X 10` yields **10, not** `10 - 0` ambiguity, and a first `/score-subtract
X 3` yields **−3** (no minimum-0 clamp). A first `/score-get X` returns **0** and
*materializes* the entry at 0. This `get-or-create-0` behavior is the de-facto "first-time
player" rule. **[REAL]**
- **Ties.** **Undefined** because no table exists. When the table is built, decide a
tie-break (§3.2). No code today can observe or sort ties — `HashMap` gives no order. **[GAP]**
- **Table full.** **Undefined** because no cap exists. When a cap is introduced, decide
what happens to the displaced entry: drop it, or "rotate" it into overflow. No code
today enforces a maximum. **[GAP]**
- **Offline / unknown name.** `getPlayerExact(name)` returns `null` for anyone not
currently online or any misspelling → the command prints "Can't find a player with that
name" and changes nothing. You **cannot** archive or reset an *offline* player by name
today; by-UUID writes (if a future table stores names+UUIDs) would fix that. **[REAL]**
- **Negative / large scores.** No clamp; negatives allowed, `int` overflow only near
~2.1 billion. **[REAL]**
- **Double-spawn / relogin.** Keyed by `UUID`, **not name**, so a name change or two
players sharing a name can't collide on the *live* map; but a *name* is never stored,
so a future table that only persists the UUID can later fail to render a name.
---
## 4. Scoring formulas & weighting *(task Q4)*
**None.** There is:
- No formula, no multiplier, no combo/bonus/streak logic.
- No weighting between action types.
- No time-based decay or "points per game" normalization.
Scores are **pure integer accumulators**: `score = Σ(adds) − Σ(subtracts)` over the session,
resettable to 0 by `/score-reset` (intended: on `/score-archive`). The only "arithmetic" in
the code is the `+`/`−` in `addScore`/`subtractScore` and the `0` floor written by
`resetScore`. `int` semantics apply (wrapping overflow; no checked arithmetic). Any
formula/weighting is a **future-design** decision, not encoded today.
---
## 5. Data-flow diagram (text)
```
ADMINISTRATOR / CONSOLE / RCON (no game events, no scheduler, no auto-scoring)
│ types a command
▼
┌─────────────────────────────┐
│ command executors │ commands/Score*Command.java
│ parse args + resolve player│ getPlayerExact(name) ── must be ONLINE (name→UUID)
│ (self-target if player) │ no permission checks
└──────────────┬──────────────┘
│ calls
▼
┌───────────────────────────────────────────────┐
│ ScoreKeeperPlugin (entry point; plugin.yml main)│
│ │
│ addScore / subtractScore / resetScore / setScore │ read-modify-write on...
│ getScore (read) archiveScore (STUB)│
└──────────────┬───────────────────────┬──────────┘
│ read-modify-write │ (intended: snapshot→table, reset 0)
▼ ▼
live map: HashMap<UUID, int> ╳ NOT IMPLEMENTED
"score entry = one int per UUID" high-score table:
default 0, no clamp, in RAM only ─ no structure, no sort,
│ ─ no persistence,
├─ READ: /score-get → "N" ─ no cap/decay
│
└─ LIFECYCLE:
onEnable : load from file → TODO (stays {} ; lost on restart)
onDisable : save to file → TODO (map discarded at shutdown)
PERSISTENCE: none │ SCORE FORMULA: none │ EVENTS/TIMERS: none │
PERMISSIONS: none │ HIGH-SCORE TABLE: aspirational stub only
```
---
## 6. Quick reference — "where to look first"
| I want to understand… | Go to |
|-----------------------|-------|
| The entire live data model | `ScoreKeeperPlugin.java:38` (one `HashMap<UUID,Integer>`) |
| How a score changes | `addScore`/`subtractScore`/`resetScore`/`setScore` `:67-91` |
| How a score is read | `getScore` `:76-78` → `getPlayerScore` `:100-106` (note get-or-create-0) |
| The "high-score table" | **Doesn't exist** — see `archiveScore` stub `:72-74`; design open in §3.2 |
| Persistence (save/load) | `onDisable` `:46-49`, `onEnable` `:59-60` — both `TODO`, not built |
| Command behaviors | `commands/Score*Command.java` (self-target default; RCON requires a name; exact online-name lookup) |
| What's declared/intended but not wired | `plugin.yml:18-20` (`/score-archive`), `README.md:11`, `README.md` notes |
| Build/runtime target | `build.gradle` (paper-api 1.21.7, Java 21), `plugin.yml` (`api-version: 1.21`) |
---
## 7. Risks a new engineer should know (correctness gaps in the *current* live domain)
These are real, not future-work — flagging because the doc's job is to prevent a new
developer from assuming the system is more mature than it is:
1. **Data loss on restart.** No save/load (`:47`, `:59`). Every server boot wipes all
scores. Any "leaderboard across sessions" is broken by design.
2. **No permissions.** Anyplayer can self-add points. README says this is by intent
("coming after I get archive to work") but it is not enforced.
3. **Race condition on add/subtract.** `read → compute → write` is not atomic and the
`HashMap` is not thread-safe; concurrent command executions could lose an update.
(Low likelihood today since commands are serial on one thread, but it's a latent bug for
any async/event-driven scoring that gets added.)
4. **No minimum-0 / no validation of amount sign.** Subtracts produce negatives freely.
5. **Name lookups are online-only & exact.** Can't target offline players by name;
case-sensitive; "Alice" ≠ "alice".
6. **No high-score table.** The flagship advertised feature (`/score-archive` → "High
Scores" table) is a no-op; a new engineer must not expect ranking/persistence to work.
---
## 8. Summary for the synthesizer (`Project.md` § "domain model & scoring logic")
Distilled, code-grounded, and honest:
- **Model:** one `int` per player `UUID`, held in `ScoreKeeperPlugin._playerScores`
(`HashMap`), default `0`.
- **Recording:** manual, admin-driven commands; **no events/timers**; no permission guard.
- **Persistence:** **none** — load/save are `TODO`; scores are lost on restart.
- **High-score table:** **does not exist** — `/score-archive` is a stub; sorting/tie-break/
cap/decay are **undecided design items** (listed in §3.2).
- **Formula/weighting:** **none** — plain `int` accumulation.
- **Lifecycle:** create-on-first-access (0) → add/subtract/reset (live only) → read via
`/score-get` → *intended* archive+reset + table display **not built** → lost on restart.
- **Edge cases:** first-time/first-write ⇒ 0-or-delta, no floor; ties/table-full ⇒ undefined
(no table yet); offline/unknown name ⇒ "can't find", unchanged.
Everything below the "high-score table" line of the README is **future work**, and the
write-up's job is to make that boundary explicit so the next team member isn't misled.

View File

@@ -0,0 +1,166 @@
# ScoreKeeper — Plugin Integration & Event/Command Reference
> Analysis for the ScoreKeeper codebase. Scope: how the plugin hooks into the
> Minecraft (Paper) server runtime — event listeners, command registrations,
> scheduled/tick logic, and inter-plugin/API surface — with a table mapping each
> trigger → handler class → effect on score data.
>
> Platform: **Paper** (`io.papermc.paper:paper-api:1.21.7-R0.1-SNAPSHOT`), Java 21,
> Gradle. Main class: `com.majinnaibu.minecraft.plugins.scorekeeper.ScoreKeeperPlugin`.
---
## 1. TL;DR for a new developer
ScoreKeeper is almost entirely **command-driven**. It registers **no Bukkit event
listeners**, declares **no `@EventHandler` methods, no `Listener` implementations,
and calls `getPluginManager().registerEvents(...)` nowhere**. It also schedules
**no timed tasks** (no `BukkitScheduler`/`BukkitRunnable`/tick logic).
The only things that touch score state are **five console/chat commands**
(`score-get`, `score-add`, `score-subtract`, `score-reset`, `score-archive`).
Score state lives in an **in-memory `HashMap<UUID, Integer>`** and is **not
persisted** — `onEnable`/`onDisable` have `TODO` stubs, so data is lost on restart.
There is a **`highscore` / high-score table in the project name and the task
prompt, but no such command or logic exists yet** — it is unimplemented.
---
## 2. Event listeners (Bukkit/Adventure)
**None.** The plugin listens to no server events. Confirmed by absence of any of:
`@EventHandler`, `implements Listener`, `registerEvents(`, `PlayerJoinEvent`,
`PlayerQuitEvent`, `PlayerDeathEvent`, or any other event import/registration.
| Server event | Handler | Effect on score data |
|---|---|---|
| PlayerJoin | *none* | none |
| PlayerQuit | *none* | none |
| PlayerDeath | *none* | none |
| (all other Bukkit events) | *none* | none |
| Custom/plugin-injected events | *none* | none |
**Implication:** nothing about a player's score changes as a result of gameplay
events (joining, quitting, dying, scoring points in-game, etc.). The only way
score data changes is through the commands in §3.
---
## 3. Command registrations & permissions
Commands are declared in `src/main/resources/plugin.yml` (no `aliases`, no
`permissions:` block, and no per-command `permission:` — so **every command is
available to every sender with no permission gating**). Each is wired to an
executor in `ScoreKeeperPlugin.onEnable()`.
Argument-resolution idiom shared by every handler:
`boolean rcon = !(sender instanceof Player);` — an RCON caller has no self
context, so the "target = self" shortcut is unavailable and a `<playerName>`
must be supplied.
`<playerName>` is resolved with `server.getPlayerExact(name)` — an **exact,
case-sensitive lookup of currently-online players only**. Score operations
therefore apply to **online players**, and an unknown/offline name yields a
"Can't find a player with that name" error (except where noted).
### Reference table — command → handler class → effect on score data
| Trigger (command) | Usage | Handler class | Delegates to | Effect on score data |
|---|---|---|---|---|
| `score-get` | `/score-get [player]` | `ScoreGetCommand` | `ScoreKeeperPlugin.getScore(Player)` → `getPlayerScore` | **Read only.** Returns the player's current score. Side effect: lazily registers the player at `0` if unseen. No persistent change. |
| `score-add` | `/score-add [player] <amount>` | `ScoreAddCommand` | `ScoreKeeperPlugin.addScore(Player,int)` | `score = old + amount` (integer `amount` in `[1..]`). |
| `score-subtract` | `/score-subtract [player] <amount>` | `ScoreSubtractCommand` | `ScoreKeeperPlugin.subtractScore(Player,int)` | `score = old - amount` (can go negative). |
| `score-reset` | `/score-reset [player]` | `ScoreResetCommand` | `ScoreKeeperPlugin.resetScore(Player)` | `score = 0` (writes 0; key created if absent). |
| `score-archive` | `/score-archive [player]` | `ScoreArchiveCommand` | *nothing* | **No state change.** Handler prints `"archive command unimplemented"`. It does **not** call `ScoreKeeperPlugin.archiveScore(...)` — see §5. |
### Command behaviour details
- **Sender vs. target.** Single-arg form means "operate on the invoking player"
(`split.length == 1` → `targetPlayer = sender`). Two-arg form means
`<playerName> <amount>` (add/subtract) or `<playerName>` (get/reset). For an
RCON sender, the single-arg form is treated as missing a target and prints
usage instead.
- **Amount parsing.** `score-add`/`score-subtract` require an integer
`amount`; a non-integer prints `"amount must be an integer"`.
- **Error/usage messaging.** `echoError` (red) and `echoUsage` (colour-coded)
differ between player and RCON call sites (`/score-add` vs `score-add`).
All handlers `return true` (command handled).
- **Permissions.** None declared → no operator/permission requirement; any
player or RCON can run them.
---
## 4. Scheduled tasks / tick-based logic
**None.** Confirmed by absence of `getScheduler()`, `runTask`,
`BukkitRunnable`, `BukkitTask`, `scheduleSync*`, or any periodic/repeating
logic. ScoreKeeper runs no background or tick-driven work.
---
## 5. Inter-plugin dependencies & API exposure
- **Declared dependencies:** plugin.yml has no `depend`, `softdepend`, `load`,
or `load-before` → **no declared inter-plugin coupling**.
- **Build dependency:** the only third-party dependency is
`io.papermc.paper:paper-api` (marked `compileOnly`, and explicitly ignored as a
snapshot by the release plugin). No other plugin/API is referenced.
- **Public API surface.** `ScoreKeeperPlugin` is a plain `JavaPlugin` exposing
`public` methods that other plugins *could* call if they hold a reference:
- `void addScore(Player, int)`
- `void subtractScore(Player, int)`
- `int getScore(Player)`
- `void setScore(Player, int)` — **public but used by no command** (internal
write path; the only writer not reachable via a command).
- `void resetScore(Player)`
- `void archiveScore(Player)` — **public but called by nothing**; it only logs
a warning. The `/score-archive` command does **not** invoke it.
- `void sendMessage(CommandSender, Component)`, `logInfo/logWarning/logError`
- **No formal service registration.** There is no `registerService`/`asService`
(ServiceLoader), no dedicated API artifact, and no `api:` block in plugin.yml.
Exposure is by **public method surface only** — informal and not discoverable
by other plugins.
- **Persistence (unimplemented).** `onEnable` logs a warning that load-from-file
is unimplemented; `onDisable` logs that save-to-file is unimplemented. The
`HashMap<UUID,Integer>` is the sole state store and is **forgotten on restart**.
---
## 6. Lifecycle
| Hook | What it does |
|---|---|
| `onEnable()` | Wires the five `score-*` command executors; logs the "load not implemented" warning and an enable log line. |
| `onDisable()` | Logs the "save not implemented" warning. **All in-memory scores are lost on shutdown.** |
---
## 7. State model (quick reference)
- **Store:** `private HashMap<UUID,Integer> _playerScores` on `ScoreKeeperPlugin`
(one map field for the whole plugin).
- **Keying:** by `Player.getUniqueId()` (UUID), so scores are per-player and
survive name changes *within a single server run*; lost on restart.
- **Lazy init:** any read (including `get`/`score-get`) auto-creates the key at `0`.
- **Writers:** `addScore`, `subtractScore`, `resetScore`, `setScore`, all funneled
through `setPlayerScore(player, value)`.
- **Concurrency:** plain `HashMap`; safe today only because command dispatch
runs on the server's main thread. Not thread-safe for off-thread use.
---
## 8. "Which server trigger causes which state change" — summary
| Trigger | State change |
|---|---|
| `/score-add [player] <amount>` | `_playerScores[uuid] += amount` |
| `/score-subtract [player] <amount>` | `_playerScores[uuid] -= amount` |
| `/score-reset [player]` | `_playerScores[uuid] = 0` |
| `/score-get [player]` | none (reads; lazily registers at 0) |
| `/score-archive [player]` | none (not implemented) |
| Any Minecraft/Bukkit event (join/quit/death/etc.) | **none — no listeners exist** |
| Server tick / scheduled task | **none — no scheduler exists** |
| Server enable | no data change (registration + log only) |
| Server disable | in-memory scores discarded (no persistence) |
| `addScore`/`subtractScore`/`setScore`/`archiveScore` via the public API | same table where called; only reachable by code holding a plugin reference, not by in-game events or commands (except add/subtract/reset which do have commands) |

View File

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

Binary file not shown.

View File

@@ -1,5 +1,8 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionBase=PROJECT
distributionPath=.gradle/wrapper/dists
distributionSha256Sum=bafd5ce9cfaea0fbccfdc8439a1ac42fbd4cd9c89dc9a988228d8a2639a58e6c
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.0-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=PROJECT
zipStorePath=.gradle/wrapper/dists

313
gradlew vendored
View File

@@ -1,78 +1,129 @@
#!/usr/bin/env sh
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# 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
#
# https://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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
##
## Gradle start up script for UN*X
##
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
MAX_FD=maximum
warn () {
echo "$*"
}
} >&2
die () {
echo
echo "$*"
echo
exit 1
}
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -81,96 +132,120 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# Collect all arguments for the java command, following the shell quoting and substitution rules
if $JAVACMD --add-opens java.base/java.lang=ALL-UNNAMED -version ; then
DEFAULT_JVM_OPTS="--add-opens java.base/java.lang=ALL-UNNAMED $DEFAULT_JVM_OPTS"
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

80
gradlew.bat vendored
View File

@@ -1,4 +1,22 @@
@if "%DEBUG%" == "" @echo off
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@@ -9,25 +27,29 @@
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
@@ -35,48 +57,36 @@ goto fail
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal

View File

@@ -1 +1,5 @@
plugins {
id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0'
}
rootProject.name = 'ScoreKeeper'

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;
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.logging.Level;
import com.majinnaibu.minecraft.plugins.scorekeeper.commands.ScoreAddCommand;
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.ScoreResetCommand;
import com.majinnaibu.minecraft.plugins.scorekeeper.commands.ScoreRunCommand;
import com.majinnaibu.minecraft.plugins.scorekeeper.commands.ScoreSubtractCommand;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.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 Component _messagePrefix =
Component.text("[")
@@ -44,8 +63,39 @@ public class ScoreKeeperPlugin extends JavaPlugin {
@Override
public void onDisable() {
// TODO: save score data to file
logWarning("Unable to save scores to file. This feature is not implemented yet.");
YamlConfiguration scores = new YamlConfiguration();
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
@@ -55,9 +105,16 @@ public class ScoreKeeperPlugin extends JavaPlugin {
getCommand("score-subtract").setExecutor(new ScoreSubtractCommand(this));
getCommand("score-reset").setExecutor(new ScoreResetCommand(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
logWarning("Unable to load scores from file. This feature is not " + "implemented yet.");
_buckets.put("points", new ScoreBucket("points", "point", "points", 0));
_bucketScores.put("points", new LinkedHashMap<>());
loadScores();
loadArchives();
checkHighScoreRuns();
getServer().getScheduler().runTaskTimer(this, this::checkHighScoreRuns, 20L, 20L);
logInfo(
getPluginMeta().getName() + " version " + getPluginMeta().getVersion() + " is enabled.");
@@ -65,29 +122,185 @@ public class ScoreKeeperPlugin extends JavaPlugin {
// region Commands
public void addScore(Player player, int amount) {
int oldScore = getPlayerScore(player);
setPlayerScore(player, oldScore + amount);
addScore(player, getPlayerBucket(player), amount);
}
public void addScore(Player player, String bucketId, int amount) {
setScore(player, bucketId, getScore(player, bucketId) + amount);
}
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) {
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) {
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) {
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) {
int oldScore = getPlayerScore(player);
setPlayerScore(player, oldScore - amount);
subtractScore(player, getPlayerBucket(player), 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
@@ -97,16 +310,484 @@ public class ScoreKeeperPlugin extends JavaPlugin {
reciever.sendMessage(_messagePrefix.append(message));
}
private int getPlayerScore(Player player) {
UUID uuid = player.getUniqueId();
if (!_playerScores.containsKey(uuid)) {
_playerScores.put(uuid, 0);
private ScoreBucket requireBucket(String bucketId) {
ScoreBucket bucket = _buckets.get(bucketId);
if (bucket == null) {
throw new IllegalArgumentException("Unknown score bucket: " + bucketId);
}
return _playerScores.get(uuid);
return bucket;
}
private void setPlayerScore(Player player, int score) {
_playerScores.put(player.getUniqueId(), score);
private void sendBucketChangeMessage(Player player, ScoreBucket bucket) {
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

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 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 ScoreArchiveCommand implements CommandExecutor {
private final ScoreKeeperPlugin _plugin;
@@ -34,7 +36,45 @@ public class ScoreArchiveCommand implements CommandExecutor {
@Override
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;
}
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:
description: Archives and resets the player's score
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

103
tools/backup-server.sh Executable file
View File

@@ -0,0 +1,103 @@
#!/usr/bin/env bash
# Backs up plugins, config, worlds, and settings from MINECRAFT_SERVER_PATH
# to MINECRAFT_BACKUP_PATH/backup-<timestamp>[-label].tar.bz2.
#
# Usage: backup-server.sh [-f|--force] [label]
# -f Back up even if the server is running (worlds may be inconsistent).
set -euo pipefail
TOOLS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$TOOLS_DIR/.." && pwd)"
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
LABEL=""
for arg in "$@"; do
case "$arg" in
-f|--force) FORCE=true ;;
-h|--help) sed -n '2,7p' "$0"; exit 0 ;;
-*) echo "Unknown option: $arg" >&2; exit 1 ;;
*) LABEL="$arg" ;;
esac
done
[[ -d "$MINECRAFT_SERVER_PATH" ]] || { echo "Error: $MINECRAFT_SERVER_PATH does not exist." >&2; exit 1; }
if pgrep -f "java.*paper-.*\.jar" >/dev/null && ! $FORCE; then
echo "Error: the server is running. Stop it first (tools/stop-server.sh) or pass --force." >&2
exit 1
fi
cd "$MINECRAFT_SERVER_PATH"
shopt -s nullglob
ITEMS=()
[[ -d plugins ]] && ITEMS+=(plugins)
[[ -d config ]] && ITEMS+=(config)
for dir in */; do
dir="${dir%/}"
[[ -f "$dir/level.dat" ]] && ITEMS+=("$dir")
done
for f in *.yml *.yaml *.json *.properties eula.txt; do
ITEMS+=("$f")
done
if (( ${#ITEMS[@]} == 0 )); then
echo "Error: nothing to back up in $MINECRAFT_SERVER_PATH." >&2
exit 1
fi
# Keep labels filename-safe.
LABEL="${LABEL//[^A-Za-z0-9._-]/_}"
NAME="backup-$(date +%Y%m%d-%H%M%S)${LABEL:+-$LABEL}.tar.bz2"
mkdir -p "$MINECRAFT_BACKUP_PATH"
ARCHIVE="$MINECRAFT_BACKUP_PATH/$NAME"
echo "Backing up: ${ITEMS[*]}"
trap 'rm -f "$ARCHIVE.part"' EXIT
tar --exclude 'plugins/.paper-remapped' --exclude '*/session.lock' \
-cjf "$ARCHIVE.part" "${ITEMS[@]}"
mv "$ARCHIVE.part" "$ARCHIVE"
trap - EXIT
echo "Created $ARCHIVE ($(du -h "$ARCHIVE" | awk '{print $1}'))"

View File

@@ -1,10 +0,0 @@
#!/usr/bin/env bash
set -e
# Find project root (two directories above this script)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
./gradlew build

View File

@@ -1,25 +0,0 @@
#!/usr/bin/env bash
set -e
if [[ -z "$MINECRAFT_SERVER_PATH" ]]; then
echo "Error: MINECRAFT_SERVER_PATH environment variable is not set."
exit 1
fi
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
PLUGIN_JAR=$(ls -t "$PROJECT_ROOT"/build/libs/*.jar 2>/dev/null | head -n1)
if [[ ! -f "$PLUGIN_JAR" ]]; then
echo "Error: No plugin jar found in $PROJECT_ROOT/build/libs. Build the plugin first."
exit 1
fi
# Optional: Warn if jar is older than any source file
if find "$PROJECT_ROOT/src/main/java" "$PROJECT_ROOT/src/main/resources" -type f -newer "$PLUGIN_JAR" | grep -q .; then
echo "Warning: The built plugin jar is older than some source files. Consider rebuilding."
fi
mkdir -p "$MINECRAFT_SERVER_PATH/plugins"
cp "$PLUGIN_JAR" "$MINECRAFT_SERVER_PATH/plugins/"
echo "Deployed $PLUGIN_JAR to $MINECRAFT_SERVER_PATH/plugins/"

View File

@@ -1,27 +0,0 @@
#!/usr/bin/env bash
set -e
# Check required environment variables
if [[ -z "$MINECRAFT_SERVER_PATH" || -z "$MINECRAFT_SERVER_JAR" ]]; then
echo "Error: MINECRAFT_SERVER_PATH and MINECRAFT_SERVER_JAR must be set."
exit 1
fi
cd "$MINECRAFT_SERVER_PATH"
# Find running server process (java with the server jar)
SERVER_PID=$(pgrep -f "java.*$MINECRAFT_SERVER_JAR" || true)
if [[ -n "$SERVER_PID" ]]; then
echo "Minecraft server is running (PID: $SERVER_PID). Stopping it..."
kill "$SERVER_PID"
sleep 5
else
echo "Minecraft server is not running."
fi
# Start the server (in a detached screen session)
pushd "${MINECRAFT_SERVER_PATH}"
java -jar "${MINECRAFT_SERVER_JAR}"
popd

View File

@@ -1,21 +0,0 @@
#!/usr/bin/env bash
set -e
if [[ -z "$MINECRAFT_SERVER_PATH" || -z "$MINECRAFT_SERVER_JAR" ]]; then
echo "Error: MINECRAFT_SERVER_PATH and MINECRAFT_SERVER_JAR must be set."
exit 1
fi
cd "$MINECRAFT_SERVER_PATH"
SERVER_PID=$(pgrep -f "java.*$MINECRAFT_SERVER_JAR" || true)
if [[ -n "$SERVER_PID" ]]; then
echo "Minecraft server is running (PID: $SERVER_PID). Stopping it..."
kill "$SERVER_PID"
sleep 5
echo "Minecraft server stopped."
else
echo "Minecraft server is not running."
fi

44
tools/build-plugin.sh Executable file
View File

@@ -0,0 +1,44 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
export GRADLE_USER_HOME="${GRADLE_USER_HOME:-$PROJECT_ROOT/.gradle/user-home}"
mkdir -p "$GRADLE_USER_HOME/jdks"
ensure_java_25() {
local version="25"
local os arch archive java_bin actual_home
case "$(uname -s)" in
Darwin) os="mac" ;;
Linux) os="linux" ;;
*) echo "Unsupported OS: $(uname -s)" >&2; exit 1 ;;
esac
case "$(uname -m)" in
arm64|aarch64) arch="aarch64" ;;
x86_64|amd64) arch="x64" ;;
*) echo "Unsupported architecture: $(uname -m)" >&2; exit 1 ;;
esac
java_bin=$(find "$GRADLE_USER_HOME/jdks" -path '*/bin/java' -type f 2>/dev/null | head -n 1 || true)
if [[ -z "$java_bin" ]]; then
echo "Downloading Temurin JDK $version into $GRADLE_USER_HOME/jdks..."
archive="$GRADLE_USER_HOME/jdks/temurin-$version.tar.gz"
curl -fsSL "https://api.adoptium.net/v3/binary/latest/$version/ga/${os}/${arch}/jdk/hotspot/normal/eclipse" -o "$archive"
tar -xzf "$archive" -C "$GRADLE_USER_HOME/jdks"
rm -f "$archive"
java_bin=$(find "$GRADLE_USER_HOME/jdks" -path '*/bin/java' -type f 2>/dev/null | head -n 1 || true)
fi
[[ -n "$java_bin" ]] || { echo "Error: could not locate installed JDK 25." >&2; exit 1; }
actual_home="$(dirname "$(dirname "$java_bin")")"
export JAVA_HOME="$actual_home"
export PATH="$JAVA_HOME/bin:$PATH"
}
ensure_java_25
cd "$PROJECT_ROOT"
./gradlew build "$@"

63
tools/deploy-plugin.sh Executable file
View File

@@ -0,0 +1,63 @@
#!/usr/bin/env bash
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
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"
if [[ -z "$MINECRAFT_SERVER_PATH" ]]; then
echo "Error: MINECRAFT_SERVER_PATH environment variable is not set."
exit 1
fi
PLUGIN_JAR=$(ls -t "$PROJECT_ROOT"/build/libs/*.jar 2>/dev/null | grep -v -- '-all\.jar$' | head -n1)
if [[ ! -f "$PLUGIN_JAR" ]]; then
echo "Error: No plugin jar found in $PROJECT_ROOT/build/libs. Build the plugin first."
exit 1
fi
# Optional: Warn if jar is older than any source file
if find "$PROJECT_ROOT/src/main/java" "$PROJECT_ROOT/src/main/resources" -type f -newer "$PLUGIN_JAR" | grep -q .; then
echo "Warning: The built plugin jar is older than some source files. Consider rebuilding."
fi
mkdir -p "$MINECRAFT_SERVER_PATH/plugins"
cp "$PLUGIN_JAR" "$MINECRAFT_SERVER_PATH/plugins/"
echo "Deployed $PLUGIN_JAR to $MINECRAFT_SERVER_PATH/plugins/"

View File

@@ -0,0 +1,20 @@
#!/usr/bin/env pwsh
# Set strict mode for better error handling
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
# Find project root (two directories above this script)
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$ProjectRoot = Split-Path -Parent (Split-Path -Parent $ScriptDir)
# Save current location and change to project root
Push-Location $ProjectRoot
try {
# Build the project using Gradle
& ".\gradlew.bat" build
} finally {
# Always restore the original location
Pop-Location
}

View File

@@ -0,0 +1,49 @@
#!/usr/bin/env pwsh
# Set strict mode for better error handling
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
# Check required environment variable
if (-not $env:MINECRAFT_SERVER_PATH) {
Write-Error "Error: MINECRAFT_SERVER_PATH environment variable is not set."
exit 1
}
# Find project root (two directories above this script)
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$ProjectRoot = Split-Path -Parent (Split-Path -Parent $ScriptDir)
# Find the most recent plugin jar file
$LibsPath = Join-Path $ProjectRoot "build\libs"
$PluginJar = Get-ChildItem -Path "$LibsPath\*.jar" -ErrorAction SilentlyContinue |
Sort-Object LastWriteTime -Descending |
Select-Object -First 1
if (-not $PluginJar) {
Write-Error "Error: No plugin jar found in $LibsPath. Build the plugin first."
exit 1
}
# Optional: Warn if jar is older than any source file
$SourcePaths = @(
(Join-Path $ProjectRoot "src\main\java"),
(Join-Path $ProjectRoot "src\main\resources")
)
$NewerSourceFiles = Get-ChildItem -Path $SourcePaths -Recurse -File -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTime -gt $PluginJar.LastWriteTime }
if ($NewerSourceFiles) {
Write-Host "Warning: The built plugin jar is older than some source files. Consider rebuilding." -ForegroundColor Yellow
}
# Create plugins directory if it doesn't exist
$PluginsPath = Join-Path $env:MINECRAFT_SERVER_PATH "plugins"
if (-not (Test-Path $PluginsPath)) {
New-Item -ItemType Directory -Path $PluginsPath -Force | Out-Null
}
# Copy the plugin jar to the plugins directory
Copy-Item -Path $PluginJar.FullName -Destination $PluginsPath -Force
Write-Host "Deployed $($PluginJar.Name) to $PluginsPath\"

View File

@@ -0,0 +1,34 @@
#!/usr/bin/env pwsh
# Set strict mode for better error handling
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
# Check required environment variables
if (-not $env:MINECRAFT_SERVER_PATH -or -not $env:MINECRAFT_SERVER_JAR) {
Write-Error "Error: MINECRAFT_SERVER_PATH and MINECRAFT_SERVER_JAR must be set."
exit 1
}
Push-Location $env:MINECRAFT_SERVER_PATH
# Find running server process (java with the server jar)
$ServerProcess = Get-Process -Name "java" -ErrorAction SilentlyContinue | Where-Object {
$_.CommandLine -like "*$($env:MINECRAFT_SERVER_JAR)*"
}
if ($ServerProcess) {
Write-Host "Minecraft server is running (PID: $($ServerProcess.Id)). Stopping it..."
Stop-Process -Id $ServerProcess.Id -Force
Start-Sleep -Seconds 5
} else {
Write-Host "Minecraft server is not running."
}
# Start the server in a new window
try {
$ServerJob = Start-Process -FilePath "java" -ArgumentList "-jar", $env:MINECRAFT_SERVER_JAR -PassThru
Write-Host "Minecraft server started in new window with PID: $($ServerJob.Id)"
} finally {
Pop-Location
}

View File

@@ -0,0 +1,25 @@
#!/usr/bin/env pwsh
# Set strict mode for better error handling
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
# Check required environment variables
if (-not $env:MINECRAFT_SERVER_PATH -or -not $env:MINECRAFT_SERVER_JAR) {
Write-Error "Error: MINECRAFT_SERVER_PATH and MINECRAFT_SERVER_JAR must be set."
exit 1
}
# Find running server process (java with the server jar)
$ServerProcess = Get-Process -Name "java" -ErrorAction SilentlyContinue | Where-Object {
$_.CommandLine -like "*$($env:MINECRAFT_SERVER_JAR)*"
}
if ($ServerProcess) {
Write-Host "Minecraft server is running (PID: $($ServerProcess.Id)). Stopping it..."
Stop-Process -Id $ServerProcess.Id -Force
Start-Sleep -Seconds 5
Write-Host "Minecraft server stopped."
} else {
Write-Host "Minecraft server is not running."
}

44
tools/publish-local.sh Executable file
View File

@@ -0,0 +1,44 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
export GRADLE_USER_HOME="${GRADLE_USER_HOME:-$PROJECT_ROOT/.gradle/user-home}"
mkdir -p "$GRADLE_USER_HOME/jdks"
ensure_java_25() {
local version="25"
local os arch archive java_bin actual_home
case "$(uname -s)" in
Darwin) os="mac" ;;
Linux) os="linux" ;;
*) echo "Unsupported OS: $(uname -s)" >&2; exit 1 ;;
esac
case "$(uname -m)" in
arm64|aarch64) arch="aarch64" ;;
x86_64|amd64) arch="x64" ;;
*) echo "Unsupported architecture: $(uname -m)" >&2; exit 1 ;;
esac
java_bin=$(find "$GRADLE_USER_HOME/jdks" -path '*/bin/java' -type f 2>/dev/null | head -n 1 || true)
if [[ -z "$java_bin" ]]; then
echo "Downloading Temurin JDK $version into $GRADLE_USER_HOME/jdks..."
archive="$GRADLE_USER_HOME/jdks/temurin-$version.tar.gz"
curl -fsSL "https://api.adoptium.net/v3/binary/latest/$version/ga/${os}/${arch}/jdk/hotspot/normal/eclipse" -o "$archive"
tar -xzf "$archive" -C "$GRADLE_USER_HOME/jdks"
rm -f "$archive"
java_bin=$(find "$GRADLE_USER_HOME/jdks" -path '*/bin/java' -type f 2>/dev/null | head -n 1 || true)
fi
[[ -n "$java_bin" ]] || { echo "Error: could not locate installed JDK 25." >&2; exit 1; }
actual_home="$(dirname "$(dirname "$java_bin")")"
export JAVA_HOME="$actual_home"
export PATH="$JAVA_HOME/bin:$PATH"
}
ensure_java_25
cd "$PROJECT_ROOT"
./gradlew publishToMavenLocal "$@"

153
tools/publish-modrinth.sh Executable file
View File

@@ -0,0 +1,153 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
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
# Required env:
# MODRINTH_TOKEN
# MODRINTH_PROJECT_ID (project ID or slug)
# MODRINTH_GAME_VERSIONS (optional comma-separated list; defaults to 1.21 through 1.21.7)
# MODRINTH_LOADERS (optional, comma-separated, default paper)
# MODRINTH_CHANGELOG (optional)
# Optional:
# MODRINTH_DEPENDENCIES (optional JSON array or a single JSON string)
# MODRINTH_FILE (optional path to the jar; defaults to build/libs/*.jar)
MODRINTH_TOKEN="${MODRINTH_TOKEN:-}"
MODRINTH_PROJECT_ID="${MODRINTH_PROJECT_ID:-5NYwxysp}"
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_LOADERS="${MODRINTH_LOADERS:-paper}"
MODRINTH_VERSION_TYPE="${MODRINTH_VERSION_TYPE:-}"
MODRINTH_FILE="${MODRINTH_FILE:-}"
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
echo "Error: MODRINTH_TOKEN is not set in $PROJECT_ROOT/.env" >&2
exit 1
fi
if [[ -z "$MODRINTH_FILE" ]]; then
MODRINTH_FILE=$(ls -t "$PROJECT_ROOT"/build/libs/*.jar 2>/dev/null | grep -v -- '-all\.jar$' | head -n1 || true)
fi
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
exit 1
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() {
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_LOADERS_JSON=$(csv_to_json_array "$MODRINTH_LOADERS")
if [[ -n "$MODRINTH_DEPENDENCIES" ]]; then
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
MODRINTH_DEPENDENCIES_JSON='[]'
fi
MODRINTH_DATA=$(jq -cn \
--arg project_id "$MODRINTH_PROJECT_ID" \
--arg name "$MODRINTH_VERSION_NAME" \
--arg version_number "$MODRINTH_VERSION" \
--arg version_type "$MODRINTH_VERSION_TYPE" \
--arg changelog "$MODRINTH_CHANGELOG" \
--argjson featured false \
--argjson dependencies "$MODRINTH_DEPENDENCIES_JSON" \
--argjson game_versions "$MODRINTH_GAME_VERSIONS_JSON" \
--argjson loaders "$MODRINTH_LOADERS_JSON" \
'{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 .

107
tools/restore-server.sh Executable file
View File

@@ -0,0 +1,107 @@
#!/usr/bin/env bash
# Restores a backup made by backup-server.sh into MINECRAFT_SERVER_PATH.
# Each top-level item in the archive (plugins, config, worlds, settings) is
# replaced; a "pre-restore" backup of the current state is taken first.
#
# Usage: restore-server.sh [-y|--yes] [--no-backup] [backup-file|name]
# Defaults to the newest backup in MINECRAFT_BACKUP_PATH.
set -euo pipefail
TOOLS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$TOOLS_DIR/.." && pwd)"
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
SAFETY_BACKUP=true
ARCHIVE=""
for arg in "$@"; do
case "$arg" in
-y|--yes) ASSUME_YES=true ;;
--no-backup) SAFETY_BACKUP=false ;;
-h|--help) sed -n '2,8p' "$0"; exit 0 ;;
-*) echo "Unknown option: $arg" >&2; exit 1 ;;
*) ARCHIVE="$arg" ;;
esac
done
if [[ -z "$ARCHIVE" ]]; then
ARCHIVE=$(ls -t "$MINECRAFT_BACKUP_PATH"/backup-*.tar.bz2 2>/dev/null | head -n1 || true)
[[ -n "$ARCHIVE" ]] || { echo "Error: no backups found in $MINECRAFT_BACKUP_PATH." >&2; exit 1; }
elif [[ ! -f "$ARCHIVE" && -f "$MINECRAFT_BACKUP_PATH/$ARCHIVE" ]]; then
ARCHIVE="$MINECRAFT_BACKUP_PATH/$ARCHIVE"
fi
[[ -f "$ARCHIVE" ]] || { echo "Error: backup not found: $ARCHIVE" >&2; exit 1; }
ARCHIVE="$(cd "$(dirname "$ARCHIVE")" && pwd)/$(basename "$ARCHIVE")"
if pgrep -f "java.*paper-.*\.jar" >/dev/null; then
echo "Error: the server is running. Stop it first (tools/stop-server.sh)." >&2
exit 1
fi
ENTRIES=$(tar -tjf "$ARCHIVE")
if grep -qE '^/|(^|/)\.\.(/|$)' <<<"$ENTRIES"; then
echo "Error: archive contains absolute or '..' paths; refusing to restore." >&2
exit 1
fi
TOP_LEVEL=$(sed -E 's#^\./##; s#/.*##' <<<"$ENTRIES" | { grep -vE '^\.?$' || true; } | sort -u)
[[ -n "$TOP_LEVEL" ]] || { echo "Error: backup is empty." >&2; exit 1; }
echo "Restore $(basename "$ARCHIVE") into $MINECRAFT_SERVER_PATH"
echo "These items will be replaced:"
sed 's/^/ /' <<<"$TOP_LEVEL"
if ! $ASSUME_YES; then
read -r -p "Continue? [y/N] " reply
[[ "$reply" =~ ^[Yy]$ ]] || { echo "Aborted."; exit 1; }
fi
mkdir -p "$MINECRAFT_SERVER_PATH"
if $SAFETY_BACKUP && [[ -n "$(ls -A "$MINECRAFT_SERVER_PATH")" ]]; then
"$TOOLS_DIR/backup-server.sh" pre-restore
fi
while IFS= read -r item; do
rm -rf "${MINECRAFT_SERVER_PATH:?}/$item"
done <<<"$TOP_LEVEL"
tar -xjf "$ARCHIVE" -C "$MINECRAFT_SERVER_PATH"
echo "Restored $(basename "$ARCHIVE")."

131
tools/start-server.sh Executable file
View File

@@ -0,0 +1,131 @@
#!/usr/bin/env bash
# Downloads (if missing) and runs a Paper server via the Fill v3 API.
# Server settings come from the project .env file.
#
# Env vars:
# JAVA_OPTS Extra JVM args (default: -Xms2G -Xmx2G)
set -euo pipefail
TOOLS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$TOOLS_DIR/.." && pwd)"
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; }
PAPER_PROJECT="paper"
JAVA_OPTS="${JAVA_OPTS:--Xms2G -Xmx2G}"
FILL_API="https://fill.papermc.io/v3/projects/${PAPER_PROJECT}/versions/${PAPER_VERSION}"
# Fill requires a non-generic User-Agent with contact info.
USER_AGENT="${PAPER_USER_AGENT:-majinnaibu-plugin-dev/1.0 (https://github.com/majinnaibu)}"
for cmd in curl jq java shasum; do
command -v "$cmd" >/dev/null || { echo "Error: '$cmd' is required." >&2; exit 1; }
done
api_get() {
curl -fsSL -H "User-Agent: $USER_AGENT" "$1"
}
mkdir -p "$MINECRAFT_SERVER_PATH"
cd "$MINECRAFT_SERVER_PATH"
JAR_BUILD="${MINECRAFT_SERVER_JAR:-}"
JAR_BUILD="${JAR_BUILD#paper-"$PAPER_VERSION"-}"; JAR_BUILD="${JAR_BUILD%.jar}"
if [[ -z "$PAPER_BUILD" && "$JAR_BUILD" =~ ^[0-9]+$ ]]; then
PAPER_BUILD="$JAR_BUILD"
fi
if [[ -z "$PAPER_BUILD" ]]; then
echo "Resolving latest stable build for Paper $PAPER_VERSION..."
PAPER_BUILD=$(api_get "$FILL_API/builds" \
| jq -r 'map(select(.channel == "STABLE")) | max_by(.id) | .id // empty') || true
if [[ -z "$PAPER_BUILD" ]]; then
# Offline or no stable build: fall back to the newest local jar for this version.
for f in paper-"$PAPER_VERSION"-*.jar; do
b="${f#paper-"$PAPER_VERSION"-}"; b="${b%.jar}"
[[ "$b" =~ ^[0-9]+$ ]] && (( b > ${PAPER_BUILD:-0} )) && PAPER_BUILD="$b"
done
[[ -n "$PAPER_BUILD" ]] || { echo "Error: no stable build found for $PAPER_VERSION." >&2; exit 1; }
echo "Could not resolve from API; using local build $PAPER_BUILD."
fi
fi
EXPECTED_JAR="paper-${PAPER_VERSION}-${PAPER_BUILD}.jar"
if [[ -n "${MINECRAFT_SERVER_JAR:-}" && "$MINECRAFT_SERVER_JAR" != "$EXPECTED_JAR" ]]; then
echo "Error: MINECRAFT_SERVER_JAR=$MINECRAFT_SERVER_JAR does not match PAPER_VERSION/PAPER_BUILD ($EXPECTED_JAR)." >&2
exit 1
fi
MINECRAFT_SERVER_JAR="$EXPECTED_JAR"
if [[ ! -f "$MINECRAFT_SERVER_JAR" ]]; then
echo "Downloading $MINECRAFT_SERVER_JAR..."
BUILD_JSON=$(api_get "$FILL_API/builds/$PAPER_BUILD")
DOWNLOAD_URL=$(jq -r '.downloads."server:default".url // empty' <<<"$BUILD_JSON")
EXPECTED_SHA=$(jq -r '.downloads."server:default".checksums.sha256 // empty' <<<"$BUILD_JSON")
[[ -n "$DOWNLOAD_URL" ]] || { echo "Error: no download for $PAPER_VERSION build $PAPER_BUILD." >&2; exit 1; }
TMP_JAR="$MINECRAFT_SERVER_JAR.part"
trap 'rm -f "$TMP_JAR"' EXIT
curl -fL --progress-bar -H "User-Agent: $USER_AGENT" -o "$TMP_JAR" "$DOWNLOAD_URL"
ACTUAL_SHA=$(shasum -a 256 "$TMP_JAR" | awk '{print $1}')
if [[ -n "$EXPECTED_SHA" && "$ACTUAL_SHA" != "$EXPECTED_SHA" ]]; then
echo "Error: checksum mismatch (expected $EXPECTED_SHA, got $ACTUAL_SHA)." >&2
exit 1
fi
mv "$TMP_JAR" "$MINECRAFT_SERVER_JAR"
trap - EXIT
fi
export MINECRAFT_SERVER_PATH MINECRAFT_SERVER_JAR
"$TOOLS_DIR/stop-server.sh"
if ! grep -qs '^eula=true' eula.txt; then
echo "Note: accept the EULA by setting eula=true in $MINECRAFT_SERVER_PATH/eula.txt (server will exit until then)."
fi
echo "Starting $MINECRAFT_SERVER_JAR in $MINECRAFT_SERVER_PATH..."
# shellcheck disable=SC2086
exec java $JAVA_OPTS -jar "$MINECRAFT_SERVER_JAR" --nogui

34
tools/stop-server.sh Executable file
View File

@@ -0,0 +1,34 @@
#!/usr/bin/env bash
# Stops any running Paper server (java process running a paper-*.jar).
set -euo pipefail
STOP_TIMEOUT="${STOP_TIMEOUT:-60}"
SERVER_PIDS=$(pgrep -f "java.*paper-.*\.jar" || true)
if [[ -z "$SERVER_PIDS" ]]; then
echo "Minecraft server is not running."
exit 0
fi
for pid in $SERVER_PIDS; do
echo "Stopping Minecraft server (PID: $pid)..."
# SIGTERM lets Paper run its shutdown hook and save worlds.
kill "$pid"
done
for ((i = 0; i < STOP_TIMEOUT; i++)); do
remaining=""
for pid in $SERVER_PIDS; do
kill -0 "$pid" 2>/dev/null && remaining="$remaining $pid"
done
if [[ -z "$remaining" ]]; then
echo "Minecraft server stopped."
exit 0
fi
sleep 1
done
echo "Server did not stop within ${STOP_TIMEOUT}s; forcing:$remaining"
kill -9 $remaining