kemoforge/pkg/KFData/KFConfig/KFConfig.go

85 lines
1.9 KiB
Go
Raw Normal View History

2024-06-26 01:08:19 +00:00
package KFConfig
import (
"encoding/json"
"io"
"io/fs"
"os"
"g.r-io.lu/shynd/kemoforge/pkg/KFData/KFError"
)
// Game is the config for the currently running game if any
var Game = NewBlankConfig()
// KFConfig is the struct that holds all the information about a config
type KFConfig struct {
// Name of the project
Name string `json:"Name"`
// Author of the project
Author string `json:"Author"`
// Version of the project
Version string `json:"Version"`
// Credits for the project
Credits string `json:"Credits"`
// Webpage for the project
Webpage string `json:"Webpage"`
// Icon for the project
Icon string `json:"Icon"`
// EncryptionKey for the project
EncryptionKey string `json:"EncryptionKey"`
}
// NewConfig creates a new config with given name, author, version and credits
func NewConfig(name, version, author, credits string) *KFConfig {
return &KFConfig{
Name: name,
Version: version,
Author: author,
Credits: credits,
}
}
// NewBlankConfig creates a new blank config
func NewBlankConfig() *KFConfig {
return &KFConfig{}
}
// Load loads the config from the given file
func (c *KFConfig) Load(file fs.File) error {
defer file.Close()
// read the file
data, err := io.ReadAll(file)
if err != nil {
return KFError.NewErrConfigLoad(err.Error())
}
// unmarshal the data
err = json.Unmarshal(data, c)
if err != nil {
return KFError.NewErrConfigLoad(err.Error())
}
return nil
}
// Save saves the config to the given file
//
// this is an editor only function and should not be used in the final game
func (c *KFConfig) Save(path string) error {
//Marshal the data
data, err := json.MarshalIndent(c, "", " ")
if err != nil {
return KFError.NewErrConfigSave(err.Error())
}
//Write the data to the file
err = os.WriteFile(path, data, os.ModePerm)
if err != nil {
return KFError.NewErrConfigSave(err.Error())
}
return nil
}