Skip to content

Commit

Permalink
v1.2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
zyxkad committed May 24, 2023
1 parent 5789ad4 commit fff094e
Show file tree
Hide file tree
Showing 18 changed files with 900 additions and 153 deletions.
9 changes: 7 additions & 2 deletions build.sh
Expand Up @@ -8,12 +8,17 @@ echo

export CGO_ENABLED=0 # cross-compile without cgo

pkg_path=$(go list -m)
tag=$(git describe --tags --match v[0-9]* --abbrev=0 2>/dev/null || git log -1 --format="dev-%H")
echo "Tag version: ${tag}"

function _build(){
f="minecraft_installer-${GOOS}-${GOARCH}"
[ "$GOOS" == 'windows' ] && f="${f}.exe"
echo "==> Building '$f'..."
go build\
-trimpath -gcflags "-trimpath=${GOPATH}" -asmflags "-trimpath=${GOPATH}" -ldflags "-w -s"\
go build \
-trimpath -gcflags "-trimpath=${GOPATH}" -asmflags "-trimpath=${GOPATH}" \
-ldflags "-w -s -X '${pkg_path}.PkgVersion=${tag}'" \
-o "./output/$f" "./cli"
return $?
}
Expand Down
116 changes: 96 additions & 20 deletions cli/main.go
Expand Up @@ -5,11 +5,28 @@ import (
"flag"
"fmt"
"os"
"strings"
"net/url"

"github.com/kmcsr/go-logger"
"github.com/kmcsr/go-logger/logrus"
installer "github.com/kmcsr/server-installer"
)

var loger logger.Logger

func initLogger(){
loger = logrus.Logger
if os.Getenv("DEBUG") == "true" {
loger.SetLevel(logger.TraceLevel)
}
_, err := logger.OutputToFile(loger, "./server-installer.log", os.Stdout)
if err != nil {
panic(err)
}
installer.SetLogger(loger)
return
}

var (
TargetVersion string = "latest"
ServerType string = "vanilla"
Expand All @@ -18,42 +35,101 @@ var (
)

func parseArgs(){
flag.StringVar(&ServerType, "server", ServerType,
"type of the server [" + strings.Join(installer.GetInstallerNames(), ",") + "] ")
flag.StringVar(&TargetVersion, "version", TargetVersion,
"the version of the server need to be installed, default is the latest")
flag.StringVar(&InstallPath, "output", InstallPath,
"the path need to be installed")
flag.StringVar(&ExecutableName, "name", ExecutableName,
"the executable name, without suffix such as '.sh' or '.jar'")
flag.Usage = func() {
flag.Usage = func(){
out := flag.CommandLine.Output()
fmt.Fprintf(out, "Usage of %s:\n", os.Args[0])
fmt.Fprintf(out, "Usage of %s (%s):\n", os.Args[0], installer.PkgVersion)
fmt.Fprint(out, UsageText)
fmt.Fprintln(out, "Flags:")
fmt.Fprintln(out, " -h, -help")
fmt.Fprintln(out, " Show this help page")
flag.PrintDefaults()
fmt.Fprintln(out, "Args:")
fmt.Fprintln(out, " <server_type> string")
fmt.Fprintf (out, " type of the server %v (default %q )\n", installer.GetInstallerNames(), ServerType)
fmt.Fprintln(out, " <modpack_file> filepath | URL")
fmt.Fprintln(out, " the modpack's local path or an URL. If it's an URL, installer will download the modpack first")
}
flag.Parse()
if flag.NArg() > 0 {
ServerType = flag.Arg(0)
}
}

func main(){
parseArgs()
initLogger()

fmt.Printf(`
Get version %q for %s server
Install into %q with name %q
`, TargetVersion, ServerType, InstallPath, ExecutableName)
fmt.Println()
switch ServerType {
case "modpack":
if flag.NArg() < 2 {
flag.Usage()
loger.Fatal("Missing argument <modpack_file>")
}
path := flag.Arg(1)
if _, err := url.ParseRequestURI(path); err == nil {
var mpath string
loger.Infof("Downloading modpack %q ...", path)
if mpath, err = installer.DefaultHTTPClient.DownloadTmp(path, "server-*.mrpack", 0, nil, -1, nil); err != nil {
loger.Fatalf("Couldn't download modpack %q: %v", path, err)
}
defer os.Remove(mpath)
path = mpath
}
loger.Infof("Loading modpack %q ...", path)
pack, err := installer.OpenMrpack(path)
if err != nil {
loger.Fatalf("Couldn't load modpack %q: %v", path, err)
}
err = pack.InstallServer(InstallPath)
pack.Close()
if err != nil {
loger.Fatalf("Install modpack error: %v", err)
}
var installed string
minecraft, mok := pack.Deps["minecraft"]
if forge, ok := pack.Deps["forge"]; ok {
installed, err = installer.DefaultForgeInstaller.InstallWithLoader(InstallPath, ExecutableName, minecraft, forge)
}else if fabric, ok := pack.Deps["fabric-loader"]; ok {
installed, err = installer.DefaultFabricInstaller.InstallWithLoader(InstallPath, ExecutableName, minecraft, fabric)
}else if quilt, ok := pack.Deps["quilt-loader"]; ok {
loger.Fatalf("Quilt is not supported yet")
_ = quilt
// installed, err = installer.DefaultQuiltInstaller.InstallWithLoader(InstallPath, ExecutableName, minecraft, quilt)
}else if mok {
installed, err = installer.VanillaIns.Install(InstallPath, ExecutableName, minecraft)
}else{
loger.Warnf("Mod pack didn't contain any dependencies")
fmt.Println("\nServer executable file installed to:\nNULL")
return
}
if err != nil {
loger.Fatalf("Install error: %v", err)
}
loger.Infof("installed: %s", installed)
fmt.Println("\nServer executable file installed to:")
fmt.Println(installed)
default:
loger.Infof("Getting version %q for %s server", TargetVersion, ServerType)
loger.Infof("Install into %q with name %q", InstallPath, ExecutableName)
fmt.Println()

ir, ok := installer.Get(ServerType)
if !ok {
fmt.Printf("Error: Could not found installer for server %q\n", ServerType)
os.Exit(1)
}
installed, err := ir.Install(InstallPath, ExecutableName, TargetVersion)
if err != nil {
fmt.Printf("Error: Install error: %v\n", err)
os.Exit(1)
ir, ok := installer.Get(ServerType)
if !ok {
loger.Fatalf("Could not found installer for server %q", ServerType)
}
installed, err := ir.Install(InstallPath, ExecutableName, TargetVersion)
if err != nil {
loger.Fatalf("Install error: %v", err)
}
loger.Infof("installed: %s", installed)
fmt.Println("\nServer executable file installed to:")
fmt.Println(installed)
}
fmt.Printf("\nServer executable file installed to: %s\n", installed)
}
22 changes: 17 additions & 5 deletions cli/usage.go
@@ -1,14 +1,26 @@

package main

const UsageText =
`Example:
minecraft_installer -name minecraft_server -version 1.7.10
const UsageText = `
minecraft_installer [...flags] [<server_type>]
minecraft_installer [...flags] modpack <modpack_file>
Example:
Install servers:
minecraft_installer -name minecraft_server -version 1.7.10
Install minecraft 1.7.10 vanilla server into minecraft_server.jar
minecraft_installer -name minecraft_server -version 1.19.2 -server forge
minecraft_installer -name minecraft_server -version 1.19.2 forge
Install minecraft 1.19.2 forge server into current directory and the executable is minecraft_server.sh
Hint: forge installer will make run scripts for the minecraft version that higher or equal than 1.17
for version that less than 1.17, you still need to use 'java -jar' to run the server
minecraft_installer -name minecraft_server -version 1.19.2 -server fabric -output server
minecraft_installer -name minecraft_server -version 1.19.2 -output server fabric
Install minecraft 1.19.2 fabric server into server/minecraft_server.jar
Install modpacks:
minecraft_installer -name modpack_server modpack /path/to/modrinch-modpack.mrpack
Install the modpack from local to the current directory
Hint: Only support modrinch modpack for now, curseforge is in progress
minecraft_installer -name modpack_server modpack 'https://cdn-raw.modrinth.com/data/sl6XzkCP/versions/i4agaPF2/Automation%20v3.3.mrpack'
Install the modpack from internet to the current directory
Hint: if you want to install modpack from the internet,
you must add the prefixs [https://, http://]
`
50 changes: 50 additions & 0 deletions errors.go
@@ -0,0 +1,50 @@

package installer

import (
"fmt"
"net/http"
)

type UnsupportGameErr struct {
Game string
}

func (e *UnsupportGameErr)Error()(string){
return fmt.Sprintf("Unsupport game type %q", e.Game)
}

type NotLocalPathErr struct {
Path string
}

func (e *NotLocalPathErr)Error()(string){
return fmt.Sprintf("%q is not a local path", e.Path)
}

type HashErr struct {
Hash string
Sum string
Expect string
}

func (e *HashErr)Error()(string){
return fmt.Sprintf("Unexpect %s hash %s, expect %s", e.Hash, e.Sum, e.Expect)
}

type HttpStatusError struct{
Code int
}

func (e *HttpStatusError)Error()(string){
return fmt.Sprintf("Unexpect http status %d %s", e.Code, http.StatusText(e.Code))
}

type ContentLengthNotMatchErr struct {
ContentLength int64
Expect int64
}

func (e *ContentLengthNotMatchErr)Error()(string){
return fmt.Sprintf("Unexpect content length %d, expect %d", e.ContentLength, e.Expect)
}
36 changes: 19 additions & 17 deletions fabric_installer.go
Expand Up @@ -3,7 +3,6 @@ package installer

import (
"fmt"
"net/http"
"net/url"
"path/filepath"
)
Expand All @@ -21,22 +20,27 @@ type (
}
)

var _ Installer = (*FabricInstaller)(nil)
var DefaultFabricInstaller = &FabricInstaller{
MetaUrl: "https://meta.fabricmc.net",
}
var _ Installer = DefaultFabricInstaller

func init(){
Installers["fabric"] = &FabricInstaller{
MetaUrl: "https://meta.fabricmc.net",
}
Installers["fabric"] = DefaultFabricInstaller
}

const fabricServerLauncherProfile = "fabric-server-launcher.properties"
const fabricServerLauncherLink = "https://meta.fabricmc.net/v2/versions/loader/%s/stable/stable/server/jar"
const fabricServerLauncherLink = "https://meta.fabricmc.net/v2/versions/loader/%s/%s/stable/server/jar"

func (r *FabricInstaller)Install(path, name string, target string)(installed string, err error){
return r.InstallWithLoader(path, name, target, "")
}

func (r *FabricInstaller)InstallWithLoader(path, name string, target string, loader string)(installed string, err error){
foundVersion := target
if target == "" || target == "latest" || target == "latest-snapshot" {
var versions VanillaVersions
fmt.Println("Getting minecraft version manifest...")
loger.Info("Getting minecraft version manifest...")
if versions, err = VanillaIns.GetVersions(); err != nil {
return
}
Expand All @@ -48,17 +52,15 @@ func (r *FabricInstaller)Install(path, name string, target string)(installed str
foundVersion += "(" + target + ")"
}
}

serverLauncherUrl := fmt.Sprintf(fabricServerLauncherLink, target)
fmt.Printf("Getting fabric server launcher %s at %q...\n", foundVersion, serverLauncherUrl)
var resp *http.Response
if resp, err = http.DefaultClient.Get(serverLauncherUrl); err != nil {
return
if loader == "" {
loader = "stable"
}
defer resp.Body.Close()
fmt.Printf("Downloading %q...\n", serverLauncherUrl)

serverLauncherUrl := fmt.Sprintf(fabricServerLauncherLink, target, loader)
loger.Infof("Getting fabric server launcher %s at %q...", foundVersion, serverLauncherUrl)
installed = filepath.Join(path, name + ".jar")
if err = safeDownload(resp.Body, installed); err != nil {
if err = DefaultHTTPClient.Download(serverLauncherUrl, installed, 0644, nil, -1,
downloadingCallback(serverLauncherUrl)); err != nil {
return
}
return installed, nil
Expand All @@ -69,7 +71,7 @@ func (r *FabricInstaller)GetInstallers()(res []FabricInstallerVersion, err error
if err != nil {
return
}
if err = getHttpJson(tg, &res); err != nil {
if err = DefaultHTTPClient.GetJson(tg, &res); err != nil {
return
}
return
Expand Down

0 comments on commit fff094e

Please sign in to comment.