TraktorNmlUtils/models/history/HistoryHandler.go

76 lines
1.6 KiB
Go

package history
import (
"encoding/xml"
"errors"
"os"
"strings"
)
// ReadFileAndConvertToHistory reads a file and converts it to the NML struct
func ReadFileAndConvertToHistory(filePath string) (*NML, error) {
// Read the file content
fileContent, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}
// Unmarshal the XML content into the NML struct
var nml NML
err = xml.Unmarshal(fileContent, &nml)
if err != nil {
return nil, err
}
// Check if the file is a history file based on the content
if IsHistoryFile(filePath) {
return &nml, nil
}
return nil, errors.New("file is not a history file")
}
func HistoryFromString(content string) (*NML, error) {
// Unmarshal the XML content into the NML struct
var nml NML
err := xml.Unmarshal([]byte(content), &nml)
if err != nil {
return nil, err
}
// Check if the file is a history file based on the content
if IsHistoryString(content) {
return &nml, nil
}
return nil, errors.New("file is not a history file")
}
func IsHistoryFile(path string) bool {
content, err := os.ReadFile(path)
if err != nil {
return false
}
return strings.Contains(string(content), "HistoryData")
}
func IsHistoryString(content string) bool {
return strings.Contains(content, "HistoryData")
}
func SaveHistoryToFile(history *NML, filePath string) error {
// Marshal the NML struct into XML content
content, err := xml.MarshalIndent(history, "", " ")
if err != nil {
return err
}
// Write the XML content to the file
err = os.WriteFile(filePath, content, 0644)
if err != nil {
return err
}
return nil
}