package logfile import ( "encoding/xml" "fmt" "os" "github.com/go-flucky/flucky/pkg/types" ) type xmlLogfile struct { logfile string } func (xl *xmlLogfile) GetLogfile() string { return xl.logfile } func (xl *xmlLogfile) Read() ([]*types.MeasuredValue, error) { if _, err := os.Stat(xl.logfile); os.IsNotExist(err) { return nil, fmt.Errorf("%v: %v", errorLogfileNotFound, xl.logfile) } 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() writeCreationDate(measuredValues) 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 }