PKGBUILD/pkg/logfile/json.go

61 lines
1.4 KiB
Go

package logfile
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/go-flucky/flucky/pkg/types"
)
type jsonLogfile struct {
logfile string
}
func (jl *jsonLogfile) Read() ([]*types.MeasuredValue, error) {
if _, err := os.Stat(jl.logfile); os.IsNotExist(err) {
return nil, fmt.Errorf("%v: %v", errorLogfileNotFound, jl.logfile)
}
f, err := os.Open(jl.logfile)
if err != nil {
return nil, fmt.Errorf("%v %v: %v", errorLogfileOpen, jl.logfile, err)
}
measuredValues := make([]*types.MeasuredValue, 0)
if err := json.NewDecoder(f).Decode(&measuredValues); err != nil {
return nil, fmt.Errorf("%v %v: %v", errorLogfileDecode, jl.logfile, err)
}
return measuredValues, nil
}
func (jl *jsonLogfile) Write(measuredValues []*types.MeasuredValue) error {
if _, err := os.Stat(filepath.Dir(jl.logfile)); os.IsNotExist(err) {
if err := os.MkdirAll(filepath.Dir(jl.logfile), 755); err != nil {
return fmt.Errorf("Directory for the logfile can not be created: %v", err)
}
}
writeCreationDate(measuredValues)
f, err := os.Create(jl.logfile)
if err != nil {
return fmt.Errorf("%v %v: %v", errorLogfileCreate, jl.logfile, err)
}
jsonEncoder := json.NewEncoder(f)
jsonEncoder.SetIndent("", " ")
err = jsonEncoder.Encode(measuredValues)
if err != nil {
return fmt.Errorf("%v %v: %v", errorLogfileEncode, jl.logfile, err)
}
return nil
}