diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index 33fe8bd9..841f11de 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -23,7 +23,7 @@ }, { "ImportPath": "github.com/fatih/structs", - "Rev": "c00d27128bb88e9c1adab1a53cda9c72c6d1ff9b" + "Rev": "c06d8730d42f16f3e8dddc236c7d69c0952a8a2c" }, { "ImportPath": "github.com/minio-io/check", diff --git a/Godeps/_workspace/src/github.com/fatih/structs/README.md b/Godeps/_workspace/src/github.com/fatih/structs/README.md index 87fccf24..1dc34048 100644 --- a/Godeps/_workspace/src/github.com/fatih/structs/README.md +++ b/Godeps/_workspace/src/github.com/fatih/structs/README.md @@ -43,6 +43,10 @@ m := structs.Map(server) // => ["gopher", 123456, true] v := structs.Values(server) +// Convert the names of a struct to a []string +// (see "Names methods" for more info about fields) +n := structs.Names(server) + // Convert the values of a struct to a []*Field // (see "Field methods" for more info about fields) f := structs.Fields(server) @@ -73,6 +77,7 @@ s := structs.New(server) m := s.Map() // Get a map[string]interface{} v := s.Values() // Get a []interface{} f := s.Fields() // Get a []*Field +n := s.Names() // Get a []string f := s.Field(name) // Get a *Field based on the given field name f, ok := s.FieldsOk(name) // Get a *Field based on the given field name n := s.Name() // Get the struct name diff --git a/Godeps/_workspace/src/github.com/fatih/structs/structs.go b/Godeps/_workspace/src/github.com/fatih/structs/structs.go index 47bf3545..1c1f68bb 100644 --- a/Godeps/_workspace/src/github.com/fatih/structs/structs.go +++ b/Godeps/_workspace/src/github.com/fatih/structs/structs.go @@ -171,6 +171,25 @@ func (s *Struct) Fields() []*Field { return getFields(s.value, s.TagName) } +// Names returns a slice of field names. A struct tag with the content of "-" +// ignores the checking of that particular field. Example: +// +// // Field is ignored by this package. +// Field bool `structs:"-"` +// +// It panics if s's kind is not struct. +func (s *Struct) Names() []string { + fields := getFields(s.value, s.TagName) + + names := make([]string, len(fields)) + + for i, field := range fields { + names[i] = field.Name() + } + + return names +} + func getFields(v reflect.Value, tagName string) []*Field { if v.Kind() == reflect.Ptr { v = v.Elem() @@ -387,6 +406,12 @@ func Fields(s interface{}) []*Field { return New(s).Fields() } +// Names returns a slice of field names. For more info refer to Struct types +// Names() method. It panics if s's kind is not struct. +func Names(s interface{}) []string { + return New(s).Names() +} + // IsZero returns true if all fields is equal to a zero value. For more info // refer to Struct types IsZero() method. It panics if s's kind is not struct. func IsZero(s interface{}) bool { diff --git a/Godeps/_workspace/src/github.com/fatih/structs/structs_test.go b/Godeps/_workspace/src/github.com/fatih/structs/structs_test.go index 02788b10..83261760 100644 --- a/Godeps/_workspace/src/github.com/fatih/structs/structs_test.go +++ b/Godeps/_workspace/src/github.com/fatih/structs/structs_test.go @@ -442,6 +442,39 @@ func TestValues_Anonymous(t *testing.T) { } } +func TestNames(t *testing.T) { + var T = struct { + A string + B int + C bool + }{ + A: "a-value", + B: 2, + C: true, + } + + s := Names(T) + + if len(s) != 3 { + t.Errorf("Names should return a slice of len 3, got: %d", len(s)) + } + + inSlice := func(val string) bool { + for _, v := range s { + if reflect.DeepEqual(v, val) { + return true + } + } + return false + } + + for _, val := range []string{"A", "B", "C"} { + if !inSlice(val) { + t.Errorf("Names should have the value %v", val) + } + } +} + func TestFields(t *testing.T) { var T = struct { A string diff --git a/pkg/qconfig/qconfig.go b/pkg/qconfig/qconfig.go new file mode 100644 index 00000000..c3bda75d --- /dev/null +++ b/pkg/qconfig/qconfig.go @@ -0,0 +1,229 @@ +/* + * qconfig for config files and persistent state files + * + * Mini Copy, (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package qconfig + +import ( + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "os" + "reflect" + "runtime" + "strings" + "sync" + + "github.com/fatih/structs" + "github.com/minio-io/minio/pkg/iodine" +) + +// Config - generic config interface functions +type Config interface { + String() string + Version() string + Save(string) error + Load(string) error + Data() interface{} + Diff(Config) ([]structs.Field, error) + DeepDiff(Config) ([]structs.Field, error) +} + +// config - implements qconfig.config interface +type config struct { + data *interface{} + lock *sync.RWMutex +} + +// CheckData - checks the validity of config data. Data sould be of type struct and contain a string type field called "Version" +func CheckData(data interface{}) error { + if !structs.IsStruct(data) { + return iodine.New(errors.New("Invalid argument type. Expecing \"struct\" type."), nil) + } + + st := structs.New(data) + f, ok := st.FieldOk("Version") + if !ok { + return iodine.New(fmt.Errorf("Invalid type of struct argument. No [%s.Version] field found.", st.Name()), nil) + } + + if f.Kind() != reflect.String { + return iodine.New(fmt.Errorf("Invalid type of struct argument. Expecting \"string\" type [%s.Version] field.", st.Name()), nil) + } + + return nil +} + +// New - instantiate a new config +func New(data interface{}) (Config, error) { + err := CheckData(data) + if err != nil { + return nil, iodine.New(err, nil) + } + + d := new(config) + d.data = &data + d.lock = new(sync.RWMutex) + return d, nil +} + +// Version returns the current config file format version +func (d config) Version() string { + st := structs.New(*d.data) + + f, ok := st.FieldOk("Version") + if !ok { + return "" + } + + val := f.Value() + ver, ok := val.(string) + if ok { + return ver + } + return "" +} + +// String converts JSON config to printable string +func (d config) String() string { + configBytes, _ := json.MarshalIndent(*d.data, "", "\t") + return string(configBytes) +} + +// Save writes config data in JSON format to a file. +func (d config) Save(filename string) (err error) { + d.lock.Lock() + defer d.lock.Unlock() + + jsonData, err := json.MarshalIndent(d.data, "", "\t") + if err != nil { + return iodine.New(err, nil) + } + + file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) + if err != nil { + return iodine.New(err, nil) + } + defer file.Close() + + if runtime.GOOS == "windows" { + jsonData = []byte(strings.Replace(string(jsonData), "\n", "\r\n", -1)) + } + _, err = file.Write(jsonData) + if err != nil { + return iodine.New(err, nil) + } + return nil +} + +// Load - loads JSON config from file and merge with currently set values +func (d *config) Load(filename string) (err error) { + (*d).lock.Lock() + defer (*d).lock.Unlock() + + _, err = os.Stat(filename) + if err != nil { + return iodine.New(err, nil) + } + + fileData, err := ioutil.ReadFile(filename) + if err != nil { + return iodine.New(err, nil) + } + + if runtime.GOOS == "windows" { + fileData = []byte(strings.Replace(string(fileData), "\r\n", "\n", -1)) + } + + err = json.Unmarshal(fileData, (*d).data) + if err != nil { + return iodine.New(err, nil) + } + + err = CheckData(*(*d).data) + if err != nil { + return iodine.New(err, nil) + } + + st := structs.New(*(*d).data) + f, ok := st.FieldOk("Version") + if !ok { + return iodine.New(fmt.Errorf("Argument struct [%s] does not contain field \"Version\".", st.Name()), nil) + } + + if (*d).Version() != f.Value() { + return iodine.New(errors.New("Version mismatch"), nil) + } + + return nil +} + +// Data - grab internal data map for reading +func (d config) Data() interface{} { + return *d.data +} + +//Diff - list fields that are in A but not in B +func (d config) Diff(c Config) (fields []structs.Field, err error) { + err = CheckData(c.Data()) + if err != nil { + return []structs.Field{}, iodine.New(err, nil) + } + + currFields := structs.Fields(d.Data()) + newFields := structs.Fields(c.Data()) + + found := false + for _, currField := range currFields { + found = false + for _, newField := range newFields { + if reflect.DeepEqual(currField.Name(), newField.Name()) { + found = true + } + } + if !found { + fields = append(fields, *currField) + } + } + return fields, nil +} + +//DeepDiff - list fields in A that are missing or not equal to fields in B +func (d config) DeepDiff(c Config) (fields []structs.Field, err error) { + err = CheckData(c.Data()) + if err != nil { + return []structs.Field{}, iodine.New(err, nil) + } + + currFields := structs.Fields(d.Data()) + newFields := structs.Fields(c.Data()) + + found := false + for _, currField := range currFields { + found = false + for _, newField := range newFields { + if reflect.DeepEqual(currField.Value(), newField.Value()) { + found = true + } + } + if !found { + fields = append(fields, *currField) + } + } + return fields, nil +} diff --git a/pkg/qconfig/qconfig_test.go b/pkg/qconfig/qconfig_test.go new file mode 100644 index 00000000..b1c6152e --- /dev/null +++ b/pkg/qconfig/qconfig_test.go @@ -0,0 +1,111 @@ +/* + * qdb - Quick key value store for config files and persistent state files + * + * Mini Copy, (C) 2015 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package qconfig + +import ( + "fmt" + "os" + "testing" + + . "github.com/minio-io/check" +) + +func Test(t *testing.T) { TestingT(t) } + +type MySuite struct{} + +var _ = Suite(&MySuite{}) + +func (s *MySuite) TestSaveLoad(c *C) { + defer os.RemoveAll("test.json") + type myStruct struct { + Version string + User string + Password string + Folders []string + } + saveMe := myStruct{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}} + config, err := New(&saveMe) + c.Assert(err, IsNil) + config.Save("test.json") + + loadMe := myStruct{Version: "1"} + newConfig, err := New(&loadMe) + c.Assert(err, IsNil) + newConfig.Load("test.json") + + c.Assert(config.Data(), DeepEquals, newConfig.Data()) + c.Assert(config.Data(), DeepEquals, &loadMe) + + mismatch := myStruct{"1.1", "guest", "nopassword", []string{"Work", "Documents", "Music"}} + c.Assert(newConfig.Data(), Not(DeepEquals), &mismatch) +} + +func (s *MySuite) TestDiff(c *C) { + type myStruct struct { + Version string + User string + Password string + Folders []string + } + saveMe := myStruct{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}} + config, err := New(&saveMe) + c.Assert(err, IsNil) + + type myNewStruct struct { + Version string + // User string + Password string + Folders []string + } + + mismatch := myNewStruct{"1", "nopassword", []string{"Work", "documents", "Music"}} + newConfig, err := New(&mismatch) + c.Assert(err, IsNil) + + fields, ok := config.Diff(newConfig) + c.Assert(ok, IsNil) + c.Assert(len(fields), Equals, 1) + for i, field := range fields { + fmt.Printf("Diff[%d]: %s=%v\n", i, field.Name(), field.Value()) + } +} + +func (s *MySuite) TestDeepDiff(c *C) { + type myStruct struct { + Version string + User string + Password string + Folders []string + } + saveMe := myStruct{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}} + config, err := New(&saveMe) + c.Assert(err, IsNil) + + mismatch := myStruct{"1", "Guest", "nopassword", []string{"Work", "documents", "Music"}} + newConfig, err := New(&mismatch) + c.Assert(err, IsNil) + + fields, err := config.DeepDiff(newConfig) + c.Assert(err, IsNil) + c.Assert(len(fields), Equals, 2) + for i, field := range fields { + fmt.Printf("DeepDiff[%d]: %s=%v\n", i, field.Name(), field.Value()) + } +}