Compare commits

..

1 commit

Author SHA1 Message Date
Jinks
0e51699c2d Update Forge version to MC 1.21.1 2024-12-09 23:33:25 +01:00
31 changed files with 510 additions and 1338 deletions

View file

@ -1,57 +0,0 @@
name: Bug Report
description: Report an issue with supported versions of ExtBackup
labels: [ bug ]
body:
- type: dropdown
id: mc-version
attributes:
label: Minecraft version
options:
- 1.19.x
- 1.20.x
- 1.21.x
validations:
required: true
- type: input
id: mod-version
attributes:
label: ExtBackup version
placeholder: eg. 1.19.4-1.2.0
validations:
required: true
- type: input
id: forge-version
attributes:
label: (Neo)Forge version
placeholder: eg. 45.0.1
validations:
required: true
- type: input
id: log-file
attributes:
label: The latest.log file
description: |
Please use a paste site such as [gist](https://gist.github.com/) / [pastebin](https://pastebin.com/) / etc.
For more information, see https://git.io/mclogs
validations:
required: true
- type: textarea
id: description
attributes:
label: Issue description
placeholder: A description of the issue.
validations:
required: true
- type: textarea
id: steps-to-reproduce
attributes:
label: Steps to reproduce
placeholder: |
1. First step
2. Second step
3. etc...
- type: textarea
id: additional-information
attributes:
label: Other information
description: Any other relevant information that is related to this issue, such as modpacks, other mods and their versions.

View file

@ -1,11 +0,0 @@
name: Feature request
description: Suggest an idea, or enhancement
labels: [ enhancement ]
body:
- type: textarea
id: description
attributes:
label: Describe your idea
placeholder: A clear and reasoned description of your idea.
validations:
required: true

View file

@ -1,47 +0,0 @@
# Do not edit this file directly
# This file is synced by https://github.com/ChaoticTrials/ModMeta
name: Check NeoForge compatibility
on:
workflow_dispatch:
schedule:
- cron: '0 3 * * 5'
jobs:
check:
runs-on: ubuntu-latest
permissions:
issues: write
contents: write
steps:
- uses: actions/checkout@v4
- name: Set up JDK
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: 21
- name: Extract Minecraft Version
id: extract-minecraft-version
run: |
minecraft_version=$(grep -m 1 "^minecraft_version=" gradle.properties | cut -d'=' -f2)
echo "minecraft_version=$minecraft_version" >> $GITHUB_ENV
- name: Get latest NeoForge
id: get-version
uses: ChaoticTrials/action-latest-forge@v1
with:
minecraft-version: ${{ env.minecraft_version }}
- name: Check compiling
uses: ChaoticTrials/action-test-different-property@v1
with:
gradle-property: neo_version
gradle-value: ${{ steps.get-version.outputs.version }}
properties-file: gradle.properties
issue-title: "[${{ env.minecraft_version }}] NeoForge incompatibility"
issue-comment: |
## NeoForge version
- ${{ steps.get-version.outputs.version }}
issue-labels: Compat, bug

View file

@ -1,88 +0,0 @@
# Do not edit this file directly
# This file is synced by https://github.com/ChaoticTrials/ModMeta
# This workflow was generated with the help of OpenAI's GPT.
name: Check Localization Files
on:
pull_request_target:
paths:
- 'src/main/resources/assets/**/lang/*.json'
permissions:
pull-requests: write
contents: read
jobs:
check-localization:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.ref }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
fetch-depth: 0
- name: Debug PR context
run: |
echo "Pull request number: ${{ github.event.pull_request.number }}"
echo "Repository full name: ${{ github.repository }}"
echo "Event path: $GITHUB_EVENT_PATH"
- name: Check localization files
run: |
PR_NUMBER="${{ github.event.pull_request.number }}"
REPO_FULL_NAME="${{ github.repository }}"
# Ensure GitHub CLI is authenticated and correctly identifies the PR context
echo "Processing PR #$PR_NUMBER for repository $REPO_FULL_NAME"
# Get the list of added or modified localization files
FILES=$(gh pr diff "$PR_NUMBER" --repo "$REPO_FULL_NAME" --name-only | grep -E 'src/main/resources/assets/.*/lang/.*\.json' || true)
if [[ -z "$FILES" ]]; then
echo "No localization files have been modified."
exit 0
fi
# Initialize an array to store the missing keys
MISSING_KEYS=()
# Iterate over each file
for FILE in $FILES; do
# Check if the file is not the default English translation
if [[ $FILE != *"en_us.json" ]]; then
# Get the modid and language key from the file path
MODID=$(echo $FILE | cut -d'/' -f5)
LANGUAGE_KEY=$(echo $FILE | cut -d'/' -f7 | cut -d'.' -f1)
# Check if all keys from the default English translation are included in this file
KEYS=$(jq -n --argfile en src/main/resources/assets/$MODID/lang/en_us.json --argfile current $FILE '($en | keys) - ($current | keys)' )
if [[ $KEYS != "[]" ]]; then
MISSING_KEYS+=("$LANGUAGE_KEY: $KEYS")
fi
fi
done
# Post a comment on the pull request with the missing keys or a success message
if [[ ${#MISSING_KEYS[@]} -gt 0 ]]; then
echo "# 🚨 Missing translation keys 🚨" > review.md
for MISSING_KEY in "${MISSING_KEYS[@]}"; do
LANGUAGE=$(echo $MISSING_KEY | cut -d':' -f1)
KEYS=$(echo $MISSING_KEY | cut -d':' -f2 | jq -r '.[]')
echo "## **$LANGUAGE**" >> review.md
for KEY in $KEYS; do
echo "- $KEY" >> review.md
done
echo "" >> review.md
done
# Request changes on the pull request
gh pr review "$PR_NUMBER" --repo "$REPO_FULL_NAME" --request-changes --body-file review.md
else
echo "## ✅ All localization files have been checked and are complete! ✅" > review.md
echo "Waiting for approval by @MelanX" >> review.md
# Approve the pull request
gh pr review "$PR_NUMBER" --repo "$REPO_FULL_NAME" --comment --body-file review.md
fi
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View file

@ -1,63 +0,0 @@
# Do not edit this file directly
# This file is synced by https://github.com/ChaoticTrials/ModMeta
name: publish
on:
push:
branches:
- '**'
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up JDK 21
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: 21
- name: Determine previous commit
id: determine_previous_commit
run: |
if [ "${{ github.event.before }}" = "0000000000000000000000000000000000000000" ]; then
gitPrevHash=$(git rev-parse HEAD~1)
else
gitPrevHash=${{ github.event.before }}
fi
echo "GIT_PREVIOUS_COMMIT=$gitPrevHash" >> $GITHUB_ENV
- name: Check commit messages
id: check_commit_messages
run: |
commits=$(git log $GIT_PREVIOUS_COMMIT..${{ github.sha }} --pretty=format:'%s')
echo "Commits since last push:"
echo "$commits"
total_commits=$(echo "$commits" | wc -l)
meta_commits=$(echo "$commits" | grep -E '^\[meta\]' | wc -l)
if [ "$total_commits" -eq "$meta_commits" ]; then
echo "Only meta commits present, skip publishing"
echo "run_publish=false" >> $GITHUB_ENV
else
echo "run_publish=true" >> $GITHUB_ENV
fi
- name: Build and publish to maven
if: env.run_publish == 'true'
run: |
chmod +x gradlew
./gradlew clean build publish curseforge modrinth --no-configuration-cache
env:
GIT_COMMIT: ${{ github.sha }}
GIT_PREVIOUS_COMMIT: ${{ github.event.before }}
MODRINTH_TOKEN: ${{ secrets.MODRINTH_TOKEN }}
CURSEFORGE_TOKEN: ${{ secrets.CURSEFORGE_TOKEN }}
MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}

View file

@ -1,22 +0,0 @@
# Do not edit this file directly
# This file is synced by https://github.com/ChaoticTrials/ModMeta
name: Close stale issues and PRs
on:
schedule:
- cron: '0 */6 * * *'
jobs:
stale:
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- uses: actions/stale@v9
with:
stale-issue-message: The required information were not provided yet. Thus, this was marked as stale.
close-issue-message: None of the required information was ever provided. If this is still an issue, feel free to reopen with the required information, or create a new issue.
only-labels: needs more info
days-before-stale: 7
days-before-close: 3

2
.gitignore vendored
View file

@ -20,11 +20,9 @@ build
# other
eclipse
run
/logs
# Files from Forge MDK
forge*changelog.txt
/src/generated/resources/.cache
# VSCode
.vscode

202
LICENSE
View file

@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -1,27 +1,20 @@
# ExtBackup
Minimal Minecraft backup mod, relying on external backup tools.
## Why?
The regular well-known backup mods lack the sophistication of dedicated backup tools.
The regular well know backup mods lack the sophistication of dedicated backup tools.
ExtBackup does not care about storage, retention, rotating old backups, freeing up space or any of that stuff.
All it does is save the world to disk and then call a script or program on a configurable schedule. The external
program can be as simple or as complicated as you want it to be. Connect your Minecraft to borg, restic, Veeam or
All it does is save the world to disk and then call a script or program on a configurabe schedule. The external
program can be as simple or as complicated as you want it to be. Connect your miecraft to borg, restic, Veeam or
whatever you like and backup your worlds however you like.
## Target audience
ExtBackup is aimed at server owners. It's so far only tested on Linux and does not offer much configuration. It just
runs the program with the Minecraft directory as current working directory. It may well work on Windows, or it may not.
ExtBackup is aimed at server owners. It's so far only tested on Linux and does not offer much configuarion. It just runs
the program with the Minecraft directory as current working directory. It may well work on Windows, or it may not.
## Acknowledgements
* [MelanX](https://modrinth.com/user/MelanX) for [Simple Backups](https://modrinth.com/mod/simple-backups) which formed
the base for ExtBackup 2.0, the NeoForge version.
* [LatvianModder](https://github.com/LatvianModder) for his work
on [FTB-Backups](https://github.com/FTBTeam/FTB-Backups)
where I stole a lot of the code for the Forge Version.
* [LatvianModder](https://github.com/LatvianModder) for his work on [FTB-Backups](https://github.com/FTBTeam/FTB-Backups)
where I stole a lot of the code for this.
* [alexbobp](https://github.com/alexbobp) and the [elytra](https://github.com/elytra) group for
[BTFU](https://github.com/elytra/BTFU), which gave me the idea but didn't go quite far enough.

View file

@ -1,217 +1,174 @@
import net.darkhax.curseforgegradle.TaskPublishCurseForge
import org.w3c.dom.Document
import org.w3c.dom.NodeList
import javax.xml.parsers.DocumentBuilderFactory
import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets
plugins {
id 'java-library'
id 'idea'
id 'maven-publish'
id 'net.darkhax.curseforgegradle' version '1.1.18'
id 'com.modrinth.minotaur' version '2.+'
id 'net.neoforged.moddev' version '[2.0,2.1)'
}
version = minecraft_version + "-" + mod_version
buildscript {
repositories {
mavenLocal()
maven { url = 'https://files.minecraftforge.net/maven' }
mavenCentral()
}
dependencies {
classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '6.0.+', changing: true
}
}
apply plugin: 'net.minecraftforge.gradle'
// Only edit below this line, the above code adds and enables the necessary things for Forge to be setup.
apply plugin: 'eclipse'
apply plugin: 'maven-publish'
base {
archivesName = project.name
}
version = '1.21.1-1.2.0'
group = 'com.github.jinks.extbackup' // http://maven.apache.org/guides/mini/guide-naming-conventions.html
archivesBaseName = 'ExtBackup'
java.toolchain.languageVersion = JavaLanguageVersion.of(21)
// Include resources generated by data generators.
sourceSets.main.resources { srcDir 'src/generated/resources' }
configurations {
runtimeClasspath.extendsFrom localRuntime
}
println('Java: ' + System.getProperty('java.version') + ' JVM: ' + System.getProperty('java.vm.version') + '(' + System.getProperty('java.vendor') + ') Arch: ' + System.getProperty('os.arch'))
minecraft {
// The mappings can be changed at any time, and must be in the following format.
// Channel: Version:
// snapshot YYYYMMDD Snapshot are built nightly.
// stable # Stables are built at the discretion of the MCP team.
// official MCVersion Official field/method names from Mojang mapping files
//
// You must be aware of the Mojang license when using the 'official' mappings.
// See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
//
// Use non-default mappings at your own risk. they may not always work.
// Simply re-run your setup task after changing the mappings to update your workspace.
mappings channel: 'official', version: '1.21.1'
// makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable.
neoForge {
version = project.neo_version
validateAccessTransformers = true
parchment {
minecraftVersion = project.parchment_minecraft_version
mappingsVersion = project.parchment_mappings_version
}
// accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg')
// Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs {
client {
client()
workingDirectory project.file('run')
systemProperty 'neoforge.enableGameTestNamespaces', project.modid
}
server {
server()
programArgument '--nogui'
systemProperty 'neoforge.enabledGameTestNamespaces', project.modid
}
data {
data()
programArguments.addAll '--mod', project.modid, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath()
}
gameTestServer {
type = "gameTestServer"
systemProperty 'neoforge.enabledGameTestNamespaces', project.modid
}
configureEach {
// Recommended logging data for a userdev environment
// The markers can be changed as needed.
// "SCAN": For mods scan.
// "REGISTRIES": For firing of registry events.
// "REGISTRYDUMP": For getting the contents of all registries.
systemProperty 'forge.logging.markers', 'REGISTRIES'
logLevel = org.slf4j.event.Level.DEBUG
gameDirectory = project.file('run' + name.capitalize())
}
}
property 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
// You can set various levels here.
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
property 'forge.logging.console.level', 'debug'
mods {
// define mod <-> source bindings
// these are used to tell the game which sources are for which mod
// mostly optional in a single mod project
// but multi mod projects should define one per mod
"${modid}" {
sourceSet(sourceSets.main)
examplemod {
source sourceSets.main
}
}
}
tasks.withType(ProcessResources).configureEach {
var replaceProperties = [
minecraft_version : minecraft_version,
neo_version : neo_version,
loader_version_range: loader_version_range,
modid : modid,
license : license,
mod_version : version
]
inputs.properties replaceProperties
server {
workingDirectory project.file('run')
filesMatching(['META-INF/neoforge.mods.toml']) {
expand replaceProperties
// Recommended logging data for a userdev environment
// The markers can be changed as needed.
// "SCAN": For mods scan.
// "REGISTRIES": For firing of registry events.
// "REGISTRYDUMP": For getting the contents of all registries.
property 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
// You can set various levels here.
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
property 'forge.logging.console.level', 'debug'
mods {
examplemod {
source sourceSets.main
}
}
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
}
data {
workingDirectory project.file('run')
idea {
module {
downloadSources = true
downloadJavadoc = true
// Recommended logging data for a userdev environment
// The markers can be changed as needed.
// "SCAN": For mods scan.
// "REGISTRIES": For firing of registry events.
// "REGISTRYDUMP": For getting the contents of all registries.
property 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
// You can set various levels here.
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
property 'forge.logging.console.level', 'debug'
// Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
args '--mod', 'examplemod', '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/')
mods {
examplemod {
source sourceSets.main
}
}
}
}
}
private static String getVersion(String baseVersion, URL url) {
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection()
connection.setRequestMethod("GET")
// Include resources generated by data generators.
sourceSets.main.resources { srcDir 'src/generated/resources' }
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(connection.getInputStream())
NodeList versionNodes = doc.getElementsByTagName("version")
dependencies {
// Specify the version of Minecraft to use, If this is any group other then 'net.minecraft' it is assumed
// that the dep is a ForgeGradle 'patcher' dependency. And it's patches will be applied.
// The userdev artifact is a special name and will get all sorts of transformations applied to it.
minecraft 'net.minecraftforge:forge:1.21.1-52.0.28'
String latestVersion = null
for (int i = 0; i < versionNodes.getLength(); i++) {
String version = versionNodes.item(i).getTextContent()
if (version.startsWith(baseVersion)) {
latestVersion = version
// You may put jars on which you depend on in ./libs or you may define them like so..
// compile "some.group:artifact:version:classifier"
// compile "some.group:artifact:version"
// Real examples
// compile 'com.mod-buildcraft:buildcraft:6.0.8:dev' // adds buildcraft to the dev env
// compile 'com.googlecode.efficient-java-matrix-library:ejml:0.24' // adds ejml to the dev env
// The 'provided' configuration is for optional dependencies that exist at compile-time but might not at runtime.
// provided 'com.mod-buildcraft:buildcraft:6.0.8:dev'
// These dependencies get remapped to your current MCP mappings
// deobf 'com.mod-buildcraft:buildcraft:6.0.8:dev'
// For more info...
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
}
// Example for how to get properties into the manifest for reading by the runtime..
jar {
manifest {
attributes([
"Specification-Title": "extbackup",
"Specification-Vendor": "jinks",
"Specification-Version": "1", // We are version 1 of ourselves
"Implementation-Title": project.name,
"Implementation-Version": "${version}",
"Implementation-Vendor" :"jinks",
"Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
])
}
}
if (latestVersion == null) {
return baseVersion + ".0"
}
// Example configuration to allow publishing using the maven-publish task
// This is the preferred method to reobfuscate your jar file
jar.finalizedBy('reobfJar')
// However if you are in a multi-project build, dev time needs unobfed jar files, so you can delay the obfuscation until publishing by doing
//publish.dependsOn('reobfJar')
return baseVersion + "." + (Integer.parseInt(latestVersion.substring(latestVersion.lastIndexOf('.') + 1)) + 1)
} catch (FileNotFoundException ignored) {
// This exception is thrown if the maven-metadata.xml file doesn't exist at the provided URL,
// which would be the case if there were no previous publications to this Maven repository with this project
return baseVersion + ".0"
} catch (Exception e) {
throw new RuntimeException(e)
publishing {
publications {
mavenJava(MavenPublication) {
artifact jar
}
}
if (!getProperty('project', 'curse').isEmpty()) {
task curseforge(type: TaskPublishCurseForge) {
apiToken = project.findProperty('curse_token') ?: System.getenv('CURSEFORGE_TOKEN') ?: ''
Closure fileConfig = { file ->
file.releaseType = getProperty('release', 'curse', 'release')
file.changelog = changelog(project)
file.changelogType = 'markdown'
getArray(getProperty('requirements', 'curse')).each { file.addRequirement(it) }
getArray(getProperty('optionals', 'curse')).each { file.addOptional(it) }
getArray(getProperty('versions', 'curse', minecraft_version)).each { file.addGameVersion(it) }
file.addModLoader('neoforge')
}
def mainFile = upload(getProperty('project', 'curse'), jar)
fileConfig(mainFile)
}
project.tasks.getByName('curseforge').dependsOn('build')
}
if (!getProperty('project', 'modrinth').isEmpty()) {
modrinth {
token = project.findProperty('modrinth_token') ?: System.getenv('MODRINTH_TOKEN') ?: ''
projectId = getProperty('project', 'modrinth')
versionNumber = project.version
versionName = jar.getArchiveFileName().get()
uploadFile = jar
dependencies = []
changelog = changelog(project)
versionType = getProperty('release', 'modrinth', 'release')
getArray(getProperty('requirements', 'modrinth')).each { dependencies.add(new com.modrinth.minotaur.dependencies.ModDependency(it, 'required')) }
getArray(getProperty('optionals', 'modrinth')).each { dependencies.add(new com.modrinth.minotaur.dependencies.ModDependency(it, 'optional')) }
gameVersions = getArray(getProperty('versions', 'modrinth', minecraft_version)).toList()
loaders = ['neoforge']
repositories {
maven {
url "file:///${project.projectDir}/mcmodsrepo"
}
}
String getProperty(String entry, String platform) {
return getProperty(entry, platform, '')
}
String getProperty(String entry, String platform, String ret) {
return project.findProperty('upload_' + entry) ?: project.findProperty(platform + '_' + entry) ?: ret
}
static String[] getArray(String deps) {
return deps.split(',')*.strip().toList().findAll { !it.isEmpty() }
}
String changelog(Project project) {
String logFmt = '--pretty=tformat:"- [%s](' + project.changelog_repository.toString() + ') - *%aN*"'
def stdout = new ByteArrayOutputStream()
def gitHash = System.getenv('GIT_COMMIT')
def gitPrevHash = System.getenv('GIT_PREVIOUS_COMMIT')
if (gitPrevHash == "0000000000000000000000000000000000000000") {
gitPrevHash = "HEAD~1"
}
if (gitHash != null && gitPrevHash != null) {
exec {
commandLine 'bash', '-c', "git log ${logFmt} ${gitPrevHash}...${gitHash} | grep -v '^- \\[\\[meta\\]'"
standardOutput = stdout
}
} else {
stdout.write('No changelog provided\n'.getBytes(StandardCharsets.UTF_8))
}
return StandardCharsets.UTF_8.decode(ByteBuffer.wrap(stdout.toByteArray())).toString()
}

View file

@ -1,26 +1,4 @@
org.gradle.jvmargs=-Xmx6G
org.gradle.daemon=true
org.gradle.parallel=true
org.gradle.caching=true
org.gradle.configuration-cache=true
## Mappings
parchment_minecraft_version=1.21
parchment_mappings_version=2024.07.28
## Loader Properties
minecraft_version=1.21
neo_version=21.0.167
loader_version_range=[4,)
## Mod Properties
modid=extbackup
mod_name=ExtBackup
group=net.sweevo
mod_version=2.0.8
## Upload Properties
upload_versions=1.21, 1.21.1
upload_release=release
#modrinth_project=fzSKSXVK
#curse_project=583228
## Misc
license=The Apache License, Version 2.0
license_url=https://www.apache.org/licenses/LICENSE-2.0.txt
changelog_repository=https://github.com/Jinks/ExtBackup/commit/%H
# Sets default memory used for gradle commands. Can be overridden by user or command line properties.
# This is required to provide enough memory for the Minecraft decompilation process.
org.gradle.jvmargs=-Xmx3G
org.gradle.daemon=false

View file

@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME

View file

@ -1,13 +0,0 @@
pluginManagement {
repositories {
mavenLocal()
gradlePluginPortal()
maven { url = 'https://maven.neoforged.net/releases' }
}
}
plugins {
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.8.0'
}
rootProject.name = 'ExtBackup'

View file

@ -0,0 +1,142 @@
package com.github.jinks.extbackup;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
public enum BackupHandler {
INSTANCE;
public long nextBackup = -1L;
public int doingBackup = 0;
public boolean hadPlayersOnline = false;
private boolean youHaveBeenWarned = false;
public void init() {
doingBackup = 0;
nextBackup = System.currentTimeMillis() + ConfigHandler.COMMON.time();
File script = ConfigHandler.COMMON.getScript();
if (!script.exists()) {
script.getParentFile().mkdirs();
try {
Files.write(script.toPath(), "#!/bin/bash\n# Put your backup script here!\n\nexit 0".getBytes(StandardCharsets.UTF_8));
script.setExecutable(true);
ExtBackup.logger.info("No backup script was found, a script has been created at " + script.getAbsolutePath() + ", please modify it to your liking.");
} catch (IOException e) {
ExtBackup.logger.error("Backup script does not exist and cannot be created!");
ExtBackup.logger.error("Disabling ExtBackup!");
ConfigHandler.COMMON.enabled.set(false);
}
}
ExtBackup.logger.info("Active script: " + script.getAbsolutePath());
ExtBackup.logger.info("Next Backup at: " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date(nextBackup)));
}
public boolean run(MinecraftServer server) {
if (doingBackup != 0 || !ConfigHandler.COMMON.enabled.get()) {
return false;
}
if (doingBackup != 0) {
ExtBackup.logger.warn("Tried to start backup while one is already running!");
return false;
}
File script = ConfigHandler.COMMON.getScript();
if (!script.exists() || !script.canExecute()) {
ExtBackup.logger.error("Cannot access or execute backup script. Bailing out!");
return false;
}
doingBackup = 1;
try {
if (server.getPlayerList() != null) {
server.getPlayerList().saveAll();
}
for (ServerLevel level : server.getAllLevels()) {
if (level != null) {
//world.save(null, true, false);
level.noSave = true;
}
}
} catch (Exception ex) {
ExtBackup.logger.error("Saving the world failed!");
enableSaving(server);
ex.printStackTrace();
return false;
}
new Thread(() -> {
try {
doBackup(server, script);
} catch (Exception ex) {
ex.printStackTrace();
}
doingBackup = 2;
}).start();
nextBackup = System.currentTimeMillis() + ConfigHandler.COMMON.time();
return true;
}
private int doBackup(MinecraftServer server, File script) {
if (ConfigHandler.COMMON.silent.get()) {ExtBackup.logger.info("Starting backup.");}
ExtBackupUtil.broadcast(server, "Starting Backup!");
ProcessBuilder pb = new ProcessBuilder(script.getAbsolutePath());
int returnValue = -1;
//Map<String, String> env = pb.environment();
pb.redirectErrorStream(true);
try {
Process backup = pb.start();
returnValue = backup.waitFor();
} catch (Exception ex) {
enableSaving(server);
ExtBackup.logger.error("Something went wrong with the Backup script!");
ExtBackup.logger.error("Check your Backups.");
ex.printStackTrace();
}
enableSaving(server);
youHaveBeenWarned = false;
if (ConfigHandler.COMMON.silent.get()) {ExtBackup.logger.info("Backup done.");}
ExtBackupUtil.broadcast(server, "Backup done!");
ExtBackup.logger.info("Next Backup at: " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date(nextBackup)));
return returnValue;
}
private void enableSaving(MinecraftServer server) {
for (ServerLevel level : server.getAllLevels()) {
if (level != null) {
level.noSave = false;
}
}
}
public void tick(MinecraftServer server, long now) {
if (nextBackup > 0L && nextBackup <= now) {
//ExtBackup.logger.info("Backup time!");
if (!ConfigHandler.COMMON.only_if_players_online.get() || hadPlayersOnline || !server.getPlayerList().getPlayers().isEmpty()) {
hadPlayersOnline = false;
run(server);
}
}
if (doingBackup > 1) {
doingBackup = 0;
} else if (doingBackup > 0) {
if (now - nextBackup > 1200000 && !youHaveBeenWarned) {
ExtBackup.logger.warn("There has been a running backup for more than 20 minutes.");
ExtBackup.logger.warn("Something seems to be wrong.");
youHaveBeenWarned = true;
}
}
}
}

View file

@ -0,0 +1,76 @@
package com.github.jinks.extbackup;
import java.io.File;
import org.apache.commons.lang3.tuple.Pair;
import net.minecraftforge.common.ForgeConfigSpec;
import net.minecraftforge.fml.loading.FMLPaths;
public final class ConfigHandler {
public static class Common {
public final ForgeConfigSpec.BooleanValue enabled;
private final ForgeConfigSpec.IntValue backup_timer;
public final ForgeConfigSpec.BooleanValue silent;
public final ForgeConfigSpec.BooleanValue only_if_players_online;
public final ForgeConfigSpec.BooleanValue force_on_shutdown;
public final ForgeConfigSpec.ConfigValue<String> script;
public Common(ForgeConfigSpec.Builder builder) {
enabled = builder
.comment("backups are enabled")
.define("enabled", true);
backup_timer = builder
.comment("interval in minutes to run the backup script")
.defineInRange("backup_timer", 10, 1 , 3600);
silent = builder
.comment("be silent, do not post backups in chat")
.define("silent", false);
only_if_players_online = builder
.comment("run only if players are online")
.define("only_if_players_online", true);
force_on_shutdown = builder
.comment("run backup on server shutdown")
.define("force_on_shutdown", true);
script = builder
.comment("script location - this script is run on each interval")
.define("script", "local/extbackup/runbackup.sh");
}
public long time() {
return (long) (ConfigHandler.COMMON.backup_timer.get() * 60000L);
}
private static File cachedScript;
public File getScript() {
String scr = ConfigHandler.COMMON.script.get();
if (scr == null) {
ExtBackup.logger.warn("Script is NULL!");
return null;
}
if (cachedScript == null) {
cachedScript = scr.trim().isEmpty() ? new File(FMLPaths.GAMEDIR.get() + "local/extbackup/runbackup.sh") : new File(scr.trim());
}
return cachedScript;
}
}
public static final Common COMMON;
public static final ForgeConfigSpec COMMON_SPEC;
static {
final Pair<Common, ForgeConfigSpec> specPair = new ForgeConfigSpec.Builder().configure(Common::new);
COMMON_SPEC = specPair.getRight();
COMMON = specPair.getLeft();
}
public static void onConfigLoad() {
//BackupHandler.INSTANCE.nextBackup = System.currentTimeMillis() + ConfigHandler.COMMON.time();
//ExtBackup.logger.info("Config Changed, next backup at: " + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date(BackupHandler.INSTANCE.nextBackup)));
}
}

View file

@ -0,0 +1,78 @@
package com.github.jinks.extbackup;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.minecraft.server.MinecraftServer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.event.server.ServerStartedEvent;
import net.minecraftforge.event.server.ServerStoppingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
@Mod(ExtBackup.MOD_ID)
@Mod.EventBusSubscriber(modid = ExtBackup.MOD_ID)
public class ExtBackup {
public static final String MOD_ID = "extbackup";
public static final Logger logger = LogManager.getLogger("ExtBackup");
public ExtBackup() {
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, ConfigHandler.COMMON_SPEC);
IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus();
modBus.addListener(this::setup);
//modBus.addListener((ModConfig.Loading e) -> ConfigHandler.onConfigLoad());
//modBus.addListener((ModConfig.Reloading e) -> ConfigHandler.onConfigLoad());
// Register ourselves for server and other game events we are interested in
IEventBus forgeBus = MinecraftForge.EVENT_BUS;
forgeBus.register(this);
forgeBus.addListener(this::serverAboutToStart);
forgeBus.addListener(this::serverStopping);
}
private void setup(final FMLCommonSetupEvent event) {
ConfigHandler.onConfigLoad();
}
public void serverAboutToStart(ServerStartedEvent event) {
BackupHandler.INSTANCE.init();
}
@SubscribeEvent
public void serverStopping(ServerStoppingEvent event) {
if (ConfigHandler.COMMON.force_on_shutdown.get()) {
MinecraftServer server = event.getServer();
if (server != null) {
BackupHandler.INSTANCE.run(server);
}
}
}
@SubscribeEvent
public static void serverTick(TickEvent.ServerTickEvent event) {
if (event.phase != TickEvent.Phase.START) {
//MinecraftServer server = LogicalSidedProvider.INSTANCE.get(LogicalSide.SERVER);
MinecraftServer server = event.getServer();
if (server != null) {
//logger.debug("Server Tick! " + event.phase);
BackupHandler.INSTANCE.tick(server, System.currentTimeMillis());
}
}
}
@SubscribeEvent
public static void playerLoggedOut(PlayerEvent.PlayerLoggedOutEvent event) {
BackupHandler.INSTANCE.hadPlayersOnline = true;
}
}

View file

@ -0,0 +1,19 @@
package com.github.jinks.extbackup;
import net.minecraft.server.MinecraftServer;
import net.minecraft.Util;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ChatType;
public class ExtBackupUtil {
public static void broadcast(MinecraftServer server, String message) {
if (!ConfigHandler.COMMON.silent.get()) {
//Component bcMessage = new TextComponent("[§1ExtBackup§r] " + message);
Component bcMessage = Component.literal("[§1ExtBackup§r] " + message);
//server.getPlayerList().broadcastMessage(bcMessage, ChatType.SYSTEM, Util.NIL_UUID);
server.getPlayerList().broadcastSystemMessage(bcMessage, true);
}
}
}

View file

@ -1,69 +0,0 @@
package net.sweevo.jinks;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.saveddata.SavedData;
import net.sweevo.jinks.config.CommonConfig;
import javax.annotation.Nonnull;
import java.text.SimpleDateFormat;
public class BackupData extends SavedData {
private long lastSaved;
private boolean paused;
private BackupData() {
// use BackupData.get
}
public static BackupData get(ServerLevel level) {
return BackupData.get(level.getServer());
}
public static BackupData get(MinecraftServer server) {
return server.overworld().getDataStorage().computeIfAbsent(BackupData.factory(), "extbackup");
}
private static SavedData.Factory<BackupData> factory() {
return new SavedData.Factory<>(BackupData::new, (nbt, provider) -> new BackupData().load(nbt, provider));
}
@Nonnull
@Override
public CompoundTag save(@Nonnull CompoundTag nbt, @Nonnull HolderLookup.Provider provider) {
nbt.putLong("lastSaved", this.lastSaved);
nbt.putBoolean("paused", this.paused);
return nbt;
}
public BackupData load(@Nonnull CompoundTag nbt, @Nonnull HolderLookup.Provider provider) {
this.lastSaved = nbt.getLong("lastSaved");
this.paused = nbt.getBoolean("paused");
return this;
}
public boolean isPaused() {
return this.paused;
}
public void setPaused(boolean paused) {
this.paused = paused;
this.setDirty();
}
public long getLastSaved() {
return this.lastSaved;
}
public String getNextBackup() {
return new SimpleDateFormat("HH:mm:ss").format(this.lastSaved + CommonConfig.getTimer());
}
public void updateSaveTime(long time) {
this.lastSaved = time;
this.setDirty();
}
}

View file

@ -1,115 +0,0 @@
package net.sweevo.jinks;
import net.minecraft.ChatFormatting;
import net.minecraft.DefaultUncaughtExceptionHandler;
import net.minecraft.network.chat.Style;
import net.minecraft.server.MinecraftServer;
import net.sweevo.jinks.config.CommonConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class BackupThread extends Thread {
public static final Logger LOGGER = LoggerFactory.getLogger(BackupThread.class);
private final MinecraftServer server;
private final boolean quiet;
private final File script;
private BackupThread(@Nonnull MinecraftServer server, boolean quiet) {
this.server = server;
this.quiet = quiet;
this.setName("ExtBackup");
this.setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler(LOGGER));
this.script = CommonConfig.getScript();
}
public static void tryCreateBackup(MinecraftServer server) {
BackupData backupData = BackupData.get(server);
if (BackupThread.shouldRunBackup(server)) {
long currentTime = System.currentTimeMillis();
BackupThread thread = new BackupThread(server, false);
thread.start();
backupData.updateSaveTime(currentTime);
}
}
public static boolean shouldRunBackup(MinecraftServer server) {
BackupData backupData = BackupData.get(server);
if (!CommonConfig.isEnabled() || backupData.isPaused()) {
return false;
}
return System.currentTimeMillis() - CommonConfig.getTimer() > backupData.getLastSaved();
}
public static void createBackup(MinecraftServer server, boolean quiet) {
BackupData backupData = BackupData.get(server);
long currentTime = System.currentTimeMillis();
BackupThread thread = new BackupThread(server, quiet);
thread.start();
backupData.updateSaveTime(currentTime);
}
@Override
public void run() {
try {
long start = System.currentTimeMillis();
if (!this.quiet) { ChatHelper.broadcast(this.server,"ExtBackup started...", Style.EMPTY.withColor(ChatFormatting.BLUE)); }
ExtBackup.LOGGER.info("Starting backup...");
this.makeWorldBackup();
long end = System.currentTimeMillis();
String time = Timer.getTimer(end - start);
if (!this.quiet) { ChatHelper.broadcast(this.server,"ExtBackup completed in %s", Style.EMPTY.withColor(ChatFormatting.BLUE), time); }
ExtBackup.LOGGER.info("Backup done.");
} catch (Exception e) {
ExtBackup.LOGGER.error("Error backing up", e);
}
}
// vanilla copy with modifications
@SuppressWarnings("CallToPrintStackTrace")
private void makeWorldBackup() {
if (!script.exists() || !script.canExecute()) {
ExtBackup.LOGGER.error("Cannot access or execute backup script. Bailing out!");
}
ProcessBuilder pb = new ProcessBuilder(script.getAbsolutePath());
int returnValue;
pb.redirectErrorStream(true);
try {
Process backup = pb.start();
returnValue = backup.waitFor();
if (returnValue != 0) {
throw new IOException("Backup process returned non-zero result!");
}
} catch (Exception ex) {
ExtBackup.LOGGER.error("Something went wrong with the Backup script!");
ExtBackup.LOGGER.error("Check your Backups.");
ex.printStackTrace();
}
}
private static class Timer {
private static final SimpleDateFormat SECONDS = new SimpleDateFormat("s.SSS");
private static final SimpleDateFormat MINUTES = new SimpleDateFormat("mm:ss");
private static final SimpleDateFormat HOURS = new SimpleDateFormat("HH:mm");
public static String getTimer(long milliseconds) {
Date date = new Date(milliseconds);
double seconds = milliseconds / 1000d;
if (seconds < 60) {
return SECONDS.format(date) + "s";
} else if (seconds < 3600) {
return MINUTES.format(date) + "min";
} else {
return HOURS.format(date) + "h";
}
}
}
}

View file

@ -1,39 +0,0 @@
package net.sweevo.jinks;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.Style;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.sweevo.jinks.config.CommonConfig;
import net.sweevo.jinks.config.ServerConfig;
import javax.annotation.Nullable;
public class ChatHelper {
@SuppressWarnings("null")
public static MutableComponent component(@Nullable ServerPlayer player, String key, Object... parameters) {
if (player != null) { return Component.translatable(key, parameters); }
return Component.literal(String.format(key, parameters));
}
public static void tell(@Nullable ServerPlayer player, String chatMessage, Style style, Object... parameters) {
MutableComponent message = ChatHelper.component(player, chatMessage, parameters);
if (player != null) {
player.sendSystemMessage(message.withStyle(style));
} else {
ExtBackup.LOGGER.info(String.valueOf(message));
}
}
public static void broadcast(MinecraftServer server, String message, Style style, Object... parameters) {
if (CommonConfig.sendMessages()) {
server.execute(() -> server.getPlayerList().getPlayers().forEach(player -> {
if (ServerConfig.messagesForEveryone() || player.hasPermissions(2)) {
player.sendSystemMessage(ChatHelper.component(player, message, parameters).withStyle(style));
}
}));
}
}
}

View file

@ -1,101 +0,0 @@
package net.sweevo.jinks;
import net.minecraft.ChatFormatting;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Style;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.event.RegisterCommandsEvent;
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
import net.neoforged.neoforge.event.server.ServerAboutToStartEvent;
import net.neoforged.neoforge.event.server.ServerStoppingEvent;
import net.neoforged.neoforge.event.tick.LevelTickEvent;
import net.sweevo.jinks.commands.BackupCommand;
import net.sweevo.jinks.commands.PauseCommand;
import net.sweevo.jinks.commands.StatusCommand;
import net.sweevo.jinks.config.CommonConfig;
import net.sweevo.jinks.config.ServerConfig;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class EventListener {
private boolean doBackup;
@SubscribeEvent
public void registerCommands(RegisterCommandsEvent event) {
event.getDispatcher().register(Commands.literal(ExtBackup.MODID)
.requires(stack -> ServerConfig.commandsCheatsDisabled() || stack.hasPermission(2))
.then(BackupCommand.register())
.then(PauseCommand.register()));
event.getDispatcher().register(Commands.literal(ExtBackup.MODID)
.then(StatusCommand.register()));
}
@SuppressWarnings("ResultOfMethodCallIgnored")
@SubscribeEvent
public void onServerStart(ServerAboutToStartEvent event) {
File script = CommonConfig.getScript();
if (!script.exists()) {
try {
script.getParentFile().mkdirs();
Files.writeString(script.toPath(), """
#!/bin/bash
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
# Put your backup script here!
exit 0
""");
script.setExecutable(true);
ExtBackup.LOGGER.info("No backup script was found, a script has been created at {}, please modify it to your liking.", script.getAbsolutePath());
} catch (IOException | SecurityException e) {
ExtBackup.LOGGER.error("Backup script does not exist and cannot be created!");
ExtBackup.LOGGER.error("Disabling ExtBackup!");
CommonConfig.setEnabled(false);
}
}
ExtBackup.LOGGER.info("Active script: {}", script.getAbsolutePath());
}
@SubscribeEvent
public void onServerTick(LevelTickEvent.Post event) {
if (event.getLevel() instanceof ServerLevel level && !level.isClientSide
&& level.getGameTime() % 20 == 0 && level == level.getServer().overworld()) {
if (!level.getServer().getPlayerList().getPlayers().isEmpty() || this.doBackup || CommonConfig.doNoPlayerBackups()) {
this.doBackup = false;
BackupThread.tryCreateBackup(level.getServer());
}
}
}
@SuppressWarnings("null")
@SubscribeEvent
public void onPlayerConnect(PlayerEvent.PlayerLoggedInEvent event) {
ServerPlayer player = (ServerPlayer) event.getEntity();
if (CommonConfig.isEnabled() && event.getEntity().getServer() != null && (ServerConfig.commandsCheatsDisabled() || player.hasPermissions(2))) {
boolean isPaused = BackupData.get(event.getEntity().getServer()).isPaused();
if (isPaused) { ChatHelper.tell(player, "ExtBackup paused!", Style.EMPTY.withColor(ChatFormatting.RED)); }
}
}
@SuppressWarnings("null")
@SubscribeEvent
public void onPlayerDisconnect(PlayerEvent.PlayerLoggedOutEvent event) {
if (event.getEntity() instanceof ServerPlayer player) {
//noinspection ConstantConditions
if (player.getServer().getPlayerList().getPlayers().isEmpty()) {
this.doBackup = true;
}
}
}
@SubscribeEvent
public void onServerShutdown(ServerStoppingEvent event) {
if (CommonConfig.doRunOnShutDown()) {
BackupThread.createBackup(event.getServer(), true);
}
}
}

View file

@ -1,31 +0,0 @@
package net.sweevo.jinks;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.fml.ModContainer;
import net.neoforged.fml.common.Mod;
import net.neoforged.fml.config.ModConfig;
import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent;
import net.neoforged.neoforge.common.NeoForge;
import net.sweevo.jinks.config.CommonConfig;
import net.sweevo.jinks.config.ServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Mod(ExtBackup.MODID)
public class ExtBackup {
public static final Logger LOGGER = LoggerFactory.getLogger(ExtBackup.class);
public static final String MODID = "extbackup";
public ExtBackup(IEventBus modEventBus, ModContainer modContainer) {
modContainer.registerConfig(ModConfig.Type.COMMON, CommonConfig.CONFIG);
modContainer.registerConfig(ModConfig.Type.SERVER, ServerConfig.CONFIG);
NeoForge.EVENT_BUS.register(new EventListener());
modEventBus.addListener(this::setup);
}
private void setup(FMLCommonSetupEvent event) {
// NO-OP
}
}

View file

@ -1,37 +0,0 @@
package net.sweevo.jinks.commands;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.arguments.BoolArgumentType;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.server.MinecraftServer;
import net.sweevo.jinks.BackupThread;
public class BackupCommand implements Command<CommandSourceStack> {
public static ArgumentBuilder<CommandSourceStack, ?> register() {
return Commands.literal("backup")
.then(Commands.literal("start")
.executes(new BackupCommand())
.then(Commands.argument("quiet", BoolArgumentType.bool())
.executes(new BackupCommand())
)
);
}
@Override
public int run(CommandContext<CommandSourceStack> context) {
boolean quiet = false;
try {
quiet = BoolArgumentType.getBool(context, "quiet");
} catch (IllegalArgumentException e) {
// do nothing
}
MinecraftServer server = context.getSource().getServer();
BackupThread.createBackup(server, quiet);
return 1;
}
}

View file

@ -1,43 +0,0 @@
package net.sweevo.jinks.commands;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import net.minecraft.ChatFormatting;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Style;
import net.sweevo.jinks.BackupData;
import net.sweevo.jinks.ChatHelper;
import net.sweevo.jinks.ExtBackup;
public class PauseCommand implements Command<CommandSourceStack> {
private final boolean paused;
private PauseCommand(boolean paused) {
this.paused = paused;
}
public static ArgumentBuilder<CommandSourceStack, ?> register() {
return Commands.literal("backup")
.then(Commands.literal("pause")
.executes(new PauseCommand(true)))
.then(Commands.literal("unpause")
.executes(new PauseCommand(false)));
}
@Override
public int run(CommandContext<CommandSourceStack> context) {
BackupData data = BackupData.get(context.getSource().getServer());
data.setPaused(this.paused);
if (this.paused) {
ChatHelper.tell(context.getSource().getPlayer(), "ExtBackup paused!", Style.EMPTY.withColor(ChatFormatting.RED));
ExtBackup.LOGGER.warn("ExtBackup paused!");}
else {
ChatHelper.tell(context.getSource().getPlayer(), "ExtBackup unpaused!", Style.EMPTY.withColor(ChatFormatting.GREEN));
ExtBackup.LOGGER.info("ExtBackup unpaused!");}
return this.paused ? 1 : 0;
}
}

View file

@ -1,30 +0,0 @@
package net.sweevo.jinks.commands;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.context.CommandContext;
import net.minecraft.ChatFormatting;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Style;
import net.minecraft.server.level.ServerPlayer;
import net.sweevo.jinks.BackupData;
import net.sweevo.jinks.ChatHelper;
public class StatusCommand implements Command<CommandSourceStack> {
public static ArgumentBuilder<CommandSourceStack, ?> register() {
return Commands.literal("status")
.executes(new StatusCommand());
}
@Override
public int run(CommandContext<CommandSourceStack> context) {
BackupData data = BackupData.get(context.getSource().getServer());
String paused = data.isPaused() ? "true" : "false";
String nextUp = data.getNextBackup();
ServerPlayer player = context.getSource().getPlayer();
ChatHelper.tell(player, "Backups paused: %s. - Next backup: %s", Style.EMPTY.withColor(ChatFormatting.BLUE), paused, nextUp);
return 0;
}
}

View file

@ -1,77 +0,0 @@
package net.sweevo.jinks.config;
import net.neoforged.neoforge.common.ModConfigSpec;
import java.io.File;
import static net.neoforged.fml.loading.FMLPaths.GAMEDIR;
public class CommonConfig {
public static final ModConfigSpec CONFIG;
private static final ModConfigSpec.Builder BUILDER = new ModConfigSpec.Builder();
private static ModConfigSpec.BooleanValue enabled;
private static ModConfigSpec.IntValue timer;
private static ModConfigSpec.BooleanValue sendMessages;
private static ModConfigSpec.BooleanValue noPlayerBackups;
private static ModConfigSpec.BooleanValue runOnShutdown;
private static ModConfigSpec.ConfigValue<String> script;
private static File cachedScript;
static {
init(BUILDER);
CONFIG = BUILDER.build();
}
public static void init(ModConfigSpec.Builder builder) {
enabled = builder.comment("If set false, no backups are being made.")
.define("enabled", true);
timer = builder.comment("The time between two backups in minutes", "5 = each 5 minutes", "60 = each hour", "1440 = each day")
.defineInRange("timer", 10, 1, Short.MAX_VALUE);
sendMessages = builder.comment("Should message be sent when backup is in the making?")
.define("sendMessages", true);
noPlayerBackups = builder.comment("Create backups, even if nobody is online")
.define("noPlayerBackups", false);
runOnShutdown = builder.comment("Create backup on server shutdown")
.define("runOnShutdown", true);
script = builder.comment("Script location - this script is run on each interval")
.define("script", "local/extbackup/runbackup.sh");
builder.push("mod_compat");
builder.pop();
}
public static boolean isEnabled() {
return enabled.get();
}
public static void setEnabled(boolean value) {
enabled.set(value);
}
// converts config value from milliseconds to minutes
public static int getTimer() {
return timer.get() * 60 * 1000;
}
public static boolean doNoPlayerBackups() {
return noPlayerBackups.get();
}
public static boolean doRunOnShutDown() {
return runOnShutdown.get();
}
public static boolean sendMessages() {
return sendMessages.get();
}
public static File getScript() {
String scr = script.get();
if (cachedScript == null) {
cachedScript = scr.trim().isEmpty() ? new File(GAMEDIR.get() + "local/extbackup/runbackup.sh") : new File(scr.trim());
}
return cachedScript;
}
}

View file

@ -1,31 +0,0 @@
package net.sweevo.jinks.config;
import net.neoforged.neoforge.common.ModConfigSpec;
public class ServerConfig {
public static final ModConfigSpec CONFIG;
private static final ModConfigSpec.Builder BUILDER = new ModConfigSpec.Builder();
private static ModConfigSpec.BooleanValue commandsCheatsDisabled;
private static ModConfigSpec.BooleanValue messagesForEveryone;
static {
init(BUILDER);
CONFIG = BUILDER.build();
}
public static void init(ModConfigSpec.Builder builder) {
commandsCheatsDisabled = builder.comment("Should commands work without cheats enabled? Mainly recommended for single player, otherwise all users on servers can trigger commands.")
.define("commandsCheatsDisabled", false);
messagesForEveryone = builder.comment("Should all users receive the backup message? Disable to only have users with permission level 2 and higher receive them.")
.define("messagesForEveryone", true);
}
public static boolean commandsCheatsDisabled() {
return commandsCheatsDisabled.get();
}
public static boolean messagesForEveryone() {
return messagesForEveryone.get();
}
}

View file

@ -1,4 +0,0 @@
public net.minecraft.server.MinecraftServer storageSource
public net.minecraft.server.network.ServerCommonPacketListenerImpl connection
public net.minecraft.world.level.storage.LevelStorageSource$LevelStorageAccess checkLock()V
public net.minecraft.world.level.storage.LevelStorageSource$LevelStorageAccess levelId

View file

@ -0,0 +1,34 @@
# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
modLoader="javafml"
# A version range to match for said mod loader - for regular FML @Mod it will be the forge version
# Forge for 1.16.3 is version 34
loaderVersion="[50,)"
# A URL to refer people to when problems occur with this mod
issueTrackerURL="https://github.com/jinks/extbackup/issues"
license="GPL"
[[mods]]
modId="extbackup"
version="${file.jarVersion}"
displayName="ExtBackup"
displayURL="https://github.com/jinks/extbackup"
#logoFile="assets/examplemod/textures/logo.png"
credits="LatVianModder, alexbobp, vazkii"
authors="jinks"
description='''
Minimal Minecraft backup mod, relying on external backup tools.
'''
[[dependencies.extbackup]]
modId="forge"
mandatory=true
versionRange="[52,)"
ordering="NONE"
side="BOTH"
[[dependencies.extbackup]]
modId="minecraft"
mandatory=true
versionRange="[1.21.1]"
ordering="NONE"
side="BOTH"

View file

@ -1,30 +0,0 @@
modLoader = "javafml"
loaderVersion = "${loader_version_range}"
license = "${license}"
issueTrackerURL = "https://git.sweevo.net/jinks/ExtBackup/issues"
[[mods]]
modId = "${modid}"
version = "${mod_version}"
displayName = "ExtBackup"
#updateJSONURL = "N/A"
displayURL = "https://git.sweevo.net/jinks/ExtBackup"
authors = "MelanX, jinks"
displayTest = "IGNORE_ALL_VERSION"
description = '''
A simple mod to create scheduled backups.
'''
[[dependencies.${ modid }]]
modId = "neoforge"
type = "required"
versionRange = "[${neo_version},)"
ordering = "NONE"
side = "BOTH"
[[dependencies.${ modid }]]
modId = "minecraft"
type = "required"
versionRange = "[${minecraft_version},)"
ordering = "NONE"
side = "BOTH"

View file

@ -0,0 +1,7 @@
{
"pack": {
"description": "ExtBackup resources",
"pack_format": 8,
"_comment": "A pack_format of 6 requires json lang files and some texture changes from 1.16.2. Note: we require v6 pack meta for all mods."
}
}