PKGBUILD/pkg/storage/logfile/xml.go

85 lines
2.0 KiB
Go
Raw Normal View History

package logfile
2019-07-03 16:46:19 +00:00
import (
"encoding/xml"
"fmt"
"os"
"path/filepath"
2019-07-03 16:46:19 +00:00
"github.com/volker-raschek/flucky/pkg/types"
2019-07-03 16:46:19 +00:00
)
type xmlLogfile struct {
logfile string
}
func (xl *xmlLogfile) GetLogfile() string {
return xl.logfile
}
func (xl *xmlLogfile) Read() ([]*types.MeasuredValue, error) {
2019-07-03 16:46:19 +00:00
if _, err := os.Stat(xl.logfile); os.IsNotExist(err) {
if _, err := os.Stat(filepath.Dir(xl.logfile)); os.IsNotExist(err) {
if err := os.MkdirAll(filepath.Dir(xl.logfile), 0755); err != nil {
return nil, fmt.Errorf("%v: %v", errorDirectoryCreate, filepath.Dir(xl.logfile))
}
}
f, err := os.Create(xl.logfile)
if err != nil {
return nil, fmt.Errorf("%v: %v", errorLogfileCreate, xl.logfile)
}
f.Close()
2019-07-03 16:46:19 +00:00
}
f, err := os.Open(xl.logfile)
if err != nil {
return nil, fmt.Errorf("%v: %v", errorLogfileOpen, xl.logfile)
}
defer f.Close()
measuredValues := new(MeasuredValues)
if err := xml.NewDecoder(f).Decode(&measuredValues); err != nil {
return nil, fmt.Errorf("%v: %v", errorLogfileDecode, err)
}
cachedMeasuredValues := make([]*types.MeasuredValue, 0)
for _, measuredValue := range measuredValues.MeasuredValues {
cachedMeasuredValues = append(cachedMeasuredValues, measuredValue.MeasuredValue)
}
return cachedMeasuredValues, nil
}
func (xl *xmlLogfile) Write(measuredValues []*types.MeasuredValue) error {
f, err := os.Create(xl.logfile)
if err != nil {
return fmt.Errorf("%v: %v", errorLogfileCreate, xl.logfile)
}
defer f.Close()
cachedMeasuredValues := new(MeasuredValues)
for _, measuredValue := range measuredValues {
cachedMeasuredValue := &MeasuredValue{
MeasuredValue: measuredValue,
}
cachedMeasuredValues.MeasuredValues = append(cachedMeasuredValues.MeasuredValues, cachedMeasuredValue)
}
bytes, err := xml.MarshalIndent(cachedMeasuredValues, "", " ")
if err != nil {
return fmt.Errorf("%v: %v", errorLogfileMarshal, err)
}
_, err = f.Write(bytes)
if err != nil {
return fmt.Errorf("%v: %v", errorLogfileWrite, err)
}
return nil
}