5 Commits
go ... v0.1.0

Author SHA1 Message Date
b693f0cda9 Updated deb and generate-rpm parameters
All checks were successful
ci/woodpecker/tag/woodpecker Pipeline was successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-09-19 19:16:22 -04:00
16f2f26236 Updated the start command to not wait on the server process
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-09-19 17:30:57 -04:00
dc9b3a7262 Added a start command
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-09-19 17:21:23 -04:00
da099a11ce Added the 'new' command which creates the scaffolding for a server instance
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-09-19 16:57:10 -04:00
1723c26ba9 Initial rust project structure with clap
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2022-09-19 15:33:34 -04:00
15 changed files with 171 additions and 272 deletions

35
.gitignore vendored
View File

@ -1,26 +1,21 @@
# ---> Go # ---> Rust
# If you prefer the allow list template instead of the deny list, see community template: # Generated by Cargo
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore # will have compiled files and executables
# debug/
# Binaries for programs and plugins target/
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c` # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
*.test # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock
# Output of the go coverage tool, specifically when used with LiteIDE # These are backup files generated by rustfmt
*.out **/*.rs.bk
# Dependency directories (remove the comment below to include it) # MSVC Windows builds of rustc generate these, which store debugging information
# vendor/ *.pdb
# Go workspace file
go.work
# Compiled Go binary
mcst
# Added by cargo
/target

View File

@ -1,20 +1,17 @@
pipeline: pipeline:
build_test: tests:
image: golang:1.16 image: rust:1.63
commands: commands:
- go build - "cargo test"
test:
image: golang:1.16
commands:
- go test -v ./...
build_release: build_release:
image: golang:1.16 image: rust:1.63
commands: commands:
- go mod vendor - "cargo install cargo-deb cargo-generate-rpm"
- GOOS=linux GOARCH=amd64 go build -ldflags "-X git.metaunix.net/BitGoblin/mcst/cmd.version=${CI_COMMIT_TAG}" -o "dist/mcst-linux-amd64-${CI_COMMIT_TAG}" - "cargo build --release"
- GOOS=windows GOARCH=amd64 go build -ldflags "-X git.metaunix.net/BitGoblin/mcst/cmd.version=${CI_COMMIT_TAG}" -o "dist/mcst-windows-amd64-${CI_COMMIT_TAG}.exe" - "cargo deb"
- "cargo generate-rpm"
- "mv target/release/mcst target/release/mcst-${CI_COMMIT_TAG}-linux-x86_64"
when: when:
event: tag event: tag
@ -24,8 +21,10 @@ pipeline:
api_key: api_key:
from_secret: gitea_api_key from_secret: gitea_api_key
base_url: https://git.metaunix.net base_url: https://git.metaunix.net
title: "${CI_COMMIT_TAG}"
files: files:
- dist/mcst-* - "target/release/*${CI_COMMIT_TAG}-linux-x86_64"
- "target/debian/mcst*.deb"
- "target/generate-rpm/mcst*.rpm"
title: "${CI_COMMIT_TAG}"
when: when:
event: tag event: tag

30
Cargo.toml Normal file
View File

@ -0,0 +1,30 @@
[package]
name = "mcst"
description = "Bit Goblin Minecraft server management tool."
version = "0.1.0"
edition = "2021"
readme = "README.md"
license = "BSD 2-Clause"
authors = ["Gregory Ballantine <gballantine@bitgoblin.tech>"]
[dependencies]
clap = { version = "3.2", features = ["derive"] }
reqwest = { version = "0.11", features = ["blocking"] }
shellexpand = "2.1"
[package.metadata.deb]
license-file = "LICENSE"
depends = "openjdk-17-jre"
section = "games"
assets = [
["target/release/mcst", "usr/bin/mcst", "755"],
["README.md", "usr/share/doc/zealot/README", "644"]
]
[package.metadata.generate-rpm]
assets = [
{ source = "target/release/mcst", dest = "/usr/bin/mcst", mode = "755" },
{ source = "README.md", dest = "/usr/share/doc/mcst/README", mode = "644"}
]
[package.metadata.generate-rpm.requires]
java-17-openjdk = "*"

View File

@ -1,18 +1,3 @@
# MCST # mcst
Bit Goblin minecraft server management tool Bit Goblin minecraft server tool
## Installation
Build dependencies:
* go
* make
To install dependencies on Ubuntu: `apt install golang make`
To install dependencies on Red Hat/AlmaLinux: `dnf install go make`
To install MCST as a system utility: `make build && sudo make install`
## Uninstallation
To uninstall MCST (if it was installed through make): `sudo make uninstall`

View File

@ -1,92 +0,0 @@
package cmd
import (
"fmt"
"io"
"log"
"net/http"
"os"
"github.com/spf13/cobra"
"git.metaunix.net/BitGoblin/mcst/util"
)
var (
serverName string
minecraftVersion string
)
var newCmd = &cobra.Command{
Use: "new",
Short: "Create a new Minecraft server instance.",
Long: `Create a new Minecraft server instance.`,
Run: func(cmd *cobra.Command, args []string) {
log.Printf("Creating new server with name '%s', and version '%s'\n", serverName, minecraftVersion)
serverDirectoryPath := util.ResolveTilde(fmt.Sprintf("~/%s", serverName))
err := os.Mkdir(serverDirectoryPath, 0755)
if err != nil && !os.IsExist(err) {
log.Fatal(err)
}
var serverJarURL string = "https://piston-data.mojang.com/v1/objects/f69c284232d7c7580bd89a5a4931c3581eae1378/server.jar"
var serverFilePath string = fmt.Sprintf("%s/server_%s.jar", serverDirectoryPath, minecraftVersion)
log.Printf("Downloading %s to %s\n", serverJarURL, serverFilePath)
file, err := os.Create(serverFilePath)
if err != nil {
log.Fatal(err)
}
client := http.Client{
CheckRedirect: func(r *http.Request, via []*http.Request) error {
r.URL.Opaque = r.URL.Path
return nil
},
}
// Put content on file
resp, err := client.Get(serverJarURL)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
_, err = io.Copy(file, resp.Body)
defer file.Close()
// create the shell script to start the server
log.Printf("Creating start.sh shell script.\n")
var scriptFilePath string = fmt.Sprintf("%s/start.sh", serverDirectoryPath)
scriptFile, err := os.Create(scriptFilePath)
if err != nil {
log.Fatalf("Unable to open file: %v", err)
}
defer scriptFile.Close()
// add text to the file
_, err = scriptFile.WriteString(fmt.Sprintf("#!/bin/sh\n\ncd %s\njava -Xmx2048M -Xms2048M -jar server_%s.jar nogui", serverDirectoryPath, minecraftVersion))
if err != nil {
log.Fatalf("Unable to write data: %v", err)
}
// set permissions on the script
err = os.Chmod(scriptFilePath, 0755)
if err != nil {
log.Fatalf("Unable to change script permissions: %v", err)
}
},
}
func init() {
// bind flags to variables
newCmd.Flags().StringVarP(&serverName, "server-name", "n", "", "The name for your new server.")
newCmd.MarkFlagRequired("server-name")
newCmd.Flags().StringVarP(&minecraftVersion, "minecraft-version", "m", "", "Minecraft Java Edition server version to use.")
newCmd.MarkFlagRequired("minecraft-version")
// add this command to the command root
rootCmd.AddCommand(newCmd)
}

View File

@ -1,30 +0,0 @@
package cmd
import (
"log"
"os"
"github.com/spf13/cobra"
)
var (
version string
)
var rootCmd = &cobra.Command{
Use: "mcst",
Short: "MCST is a tool to manage Minecraft Java edition servers.",
Long: `A flexible yet user-friendly tool to manage Minecraft Java edition server.
Source code available at https://git.metaunix.net/BitGoblin/mcst`,
Run: func(cmd *cobra.Command, args []string) {
log.Printf("This is a test.")
},
Version: version,
}
func Start() {
if err := rootCmd.Execute(); err != nil {
log.Println(err)
os.Exit(1)
}
}

14
go.mod
View File

@ -1,14 +0,0 @@
module git.metaunix.net/BitGoblin/mcst
go 1.18
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/spf13/cobra v1.5.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/objx v0.4.0 // indirect
github.com/stretchr/testify v1.8.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

24
go.sum
View File

@ -1,24 +0,0 @@
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU=
github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0 h1:M2gUjqZET1qApGOWNSnZ49BAIMX4F/1plDv3+l31EJ4=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -1,9 +0,0 @@
package main
import (
"git.metaunix.net/BitGoblin/mcst/cmd"
)
func main() {
cmd.Start()
}

2
src/cmd/mod.rs Normal file
View File

@ -0,0 +1,2 @@
pub mod new;
pub mod start;

37
src/cmd/new.rs Normal file
View File

@ -0,0 +1,37 @@
extern crate reqwest;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::io;
use std::io::prelude::*;
pub fn new_command(server_name: &str, minecraft_version: &str) -> Result<(), Box<dyn std::error::Error>> {
println!("Creating new server with name '{}' using version '{}'.", server_name, minecraft_version);
let home_path = shellexpand::tilde("~");
let server_directory_path = format!("{}/{}", home_path, server_name);
let server_file_path = format!("{}/server_{}.jar", server_directory_path, minecraft_version);
// create the server directory
println!("Creating server directory {}.", server_directory_path);
fs::create_dir(&server_directory_path)?;
// download the Minecraft server JAR file
let server_jar_url = "https://piston-data.mojang.com/v1/objects/f69c284232d7c7580bd89a5a4931c3581eae1378/server.jar";
println!("Downloading {} to {}.", server_jar_url, server_file_path);
let mut resp = reqwest::blocking::get(server_jar_url)?;
let mut out = fs::File::create(server_file_path)?;
io::copy(&mut resp, &mut out)?;
// create the start.sh shell script
let script_file_path = format!("{}/start.sh", server_directory_path);
println!("Creating start.sh script.");
let mut script_file = fs::File::create(script_file_path)?;
let script_file_contents = format!("#!/bin/sh\n\ncd {}\njava -Xmx2048M -Xms2048M -jar server_{}.jar nogui", server_directory_path, minecraft_version);
script_file.write_all(script_file_contents.as_bytes())?;
// set the file permissions on the start.sh script
script_file.set_permissions(fs::Permissions::from_mode(0o755))?;
// return empty result to signify everything is okay
Ok(())
}

27
src/cmd/start.rs Normal file
View File

@ -0,0 +1,27 @@
use std::process::{Command, Stdio};
pub fn start_command(server_name: &str) -> Result<(), Box<dyn std::error::Error>> {
println!("Starting server {}.", server_name);
// set up our path variables
let home_path = shellexpand::tilde("~");
let server_directory_path = format!("{}/{}", home_path, server_name);
let script_file_path = format!("{}/start.sh", server_directory_path);
let eula_file_path = format!("{}/eula.txt", server_directory_path);
// check if eula.txt exists - if it doesn't then warn the user they'll need to accept it and possibly modify server settings
if !std::path::Path::new(&eula_file_path).exists() {
println!("The eula.txt does not exist - you will need to accept the EULA located at {} by changing 'false' to 'true'.", eula_file_path);
println!("This appears to be a new server instance. Don't forget to modify server.properties!");
}
// run the start command
Command::new(script_file_path)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()?;
// return okay signal
Ok(())
}

45
src/main.rs Normal file
View File

@ -0,0 +1,45 @@
mod cmd;
use clap::{Parser, Subcommand};
#[derive(Parser)]
#[clap(name = "Minecraft server management tool", author, version, about = "Bit Goblin's Minecraft server management tool.", long_about = None)]
#[clap(propagate_version = true)]
struct Cli {
#[clap(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
// new server subcommand
#[clap(name = "new", about = "Create a new Minecraft java edition server instance.")]
New {
#[clap(short = 'n', long, required = true, help = "[REQUIRED] The name for your new server.")]
server_name: String,
#[clap(short = 'm', long, required = true, help = "[REQUIRED] Minecraft Java Edition server version to use.")]
minecraft_version: String,
},
#[clap(name = "start", about = "Start a Minecraft java edition server instance.")]
Start {
#[clap(short = 'n', long, required = true, help = "[REQUIRED] The name of your Minecraft server instance.")]
server_name: String,
}
}
fn main() {
// start the Clap CLI
let cli = Cli::parse();
// map subcommands back to the main command
let res = match &cli.command {
Commands::New { server_name, minecraft_version } => cmd::new::new_command(&server_name, &minecraft_version),
Commands::Start { server_name } => cmd::start::start_command(&server_name),
};
match res {
Ok(_) => {},
Err(e) => panic!("MCST ran into an error: {}", e),
};
}

View File

@ -1,23 +0,0 @@
package util
import (
"path/filepath"
"os/user"
"strings"
)
func ResolveTilde(path string) string {
usr, _ := user.Current()
dir := usr.HomeDir
if path == "~" {
// In case of "~", which won't be caught by the "else if"
path = dir
} else if strings.HasPrefix(path, "~/") {
// Use strings.HasPrefix so we don't match paths like
// "/something/~/something/"
path = filepath.Join(dir, path[2:])
}
return path
}

View File

@ -1,29 +0,0 @@
package util
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
// define our test suite struct
type EnvTestSuite struct {
suite.Suite
}
// the tilde should expand to user's home directory
func (s *EnvTestSuite) TestResolveTilde() {
resolvedPath := ResolveTilde("~")
assert.NotEqual(s.T(), resolvedPath, "~")
}
// ensure the tilde + relative path gets expanded fully
func (s *EnvTestSuite) TestResolveTildePath() {
resolvedPath := ResolveTilde("~/test")
assert.NotEqual(s.T(), resolvedPath, "~/test")
}
// this is needed to run the test suite
func TestEnvTestSuite(t *testing.T) {
suite.Run(t, new(EnvTestSuite))
}