Index handling, hash calculation

This commit is contained in:
comp500
2019-04-26 17:16:29 +01:00
parent 7f68115058
commit d7e916e558
3 changed files with 204 additions and 30 deletions

View File

@@ -1,6 +1,11 @@
package core
import (
"crypto/sha256"
"encoding/hex"
"io"
"io/ioutil"
"os"
"path/filepath"
"github.com/BurntSushi/toml"
)
@@ -16,6 +21,7 @@ type Pack struct {
Versions map[string]string `toml:"versions"`
Client map[string]toml.Primitive `toml:"client"`
Server map[string]toml.Primitive `toml:"server"`
flags Flags
}
// LoadPack loads the modpack metadata to a Pack struct
@@ -32,6 +38,56 @@ func LoadPack(flags Flags) (Pack, error) {
if len(modpack.Index.File) == 0 {
modpack.Index.File = "index.toml"
}
modpack.flags = flags
return modpack, nil
}
// LoadIndex attempts to load the index file of this modpack
func (pack Pack) LoadIndex() (Index, error) {
if filepath.IsAbs(pack.Index.File) {
return LoadIndex(pack.Index.File, pack.flags)
}
return LoadIndex(filepath.Join(filepath.Dir(pack.flags.PackFile), pack.Index.File), pack.flags)
}
// UpdateIndexHash recalculates the hash of the index file of this modpack
func (pack *Pack) UpdateIndexHash() error {
indexFile := filepath.Join(filepath.Dir(pack.flags.PackFile), pack.Index.File)
if filepath.IsAbs(pack.Index.File) {
indexFile = pack.Index.File
}
f, err := os.Open(indexFile)
if err != nil {
return err
}
defer f.Close()
// Hash usage strategy (may change):
// Just use SHA256, overwrite existing hash regardless of what it is
// May update later to continue using the same hash that was already being used
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return err
}
hashString := hex.EncodeToString(h.Sum(nil))
pack.Index.HashFormat = "sha256"
pack.Index.Hash = hashString
return nil
}
// Write saves the pack file
func (pack Pack) Write() error {
f, err := os.Create(pack.flags.PackFile)
if err != nil {
return err
}
defer f.Close()
enc := toml.NewEncoder(f)
// Disable indentation
enc.Indent = ""
return enc.Encode(pack)
}