package client; import ( "git.xdrm.io/schastsp/client/keyset" "fmt" "path/filepath" "errors" "os" ) type config struct { path string // absolute configuration file path } /* (1) Constructor * * @dir Dir path * @name file name * ---------------------------------------------------------*/ func Config(dir string, name string) (*config, error) { inst := new(config); /* (1) Build full path */ absoluteDir, err := filepath.Abs(dir); if err != nil { return nil, err; } basename := filepath.Base(name); fullpath := fmt.Sprintf("%s/%s", absoluteDir, basename); /* (2) Check directory */ if info, err := os.Stat(absoluteDir); err != nil { // Unknown error if !os.IsNotExist(err) { return nil, err } // not exists -> try to create dir err2 := os.MkdirAll(absoluteDir, 0755); if err2 != nil { return nil, err2 } // fail if not a directory } else if !info.Mode().IsDir() { return nil, errors.New("Configuration dir is not a directory"); } /* (3) Check file */ info, err := os.Stat(fullpath); if err != nil { // Unknown error if !os.IsNotExist(err) { return nil, err } // File does not exist -> try to create file _, err2 := os.Create(fullpath); if err2 != nil { return nil, err2 } // fail if exists but not regular file } else if !info.Mode().IsRegular() { return nil, errors.New("Configuration file is not a regular file"); } inst.path = fullpath return inst, nil } /* (2) Fetches a keyset from a file * * @ks<*keyset.T> Set to fetch into * * @return err Fetching error * NIL on error * ---------------------------------------------------------*/ func (c config) Fetch(ks *keyset.T) (err error) { /* (1) Open file */ file, err := os.Open(c.path) if err != nil { return err } /* (2) Defer close */ defer file.Close() /* (3) Fetch from file */ err = ks.Fetch(file); if err != nil { return err } return nil } /* (3) Stores a keyset into file * * @ks<*keyset.T> Set to store * * @return err Storage error * NIL on error * ---------------------------------------------------------*/ func (c config) Store(ks *keyset.T) error { /* (1) Open file */ file, err := os.OpenFile(c.path, os.O_RDWR|os.O_CREATE, 0755); if err != nil { return err } /* (2) Defer close */ defer file.Close() /* (3) Store into file */ err = ks.Store(file) if err != nil { return err } return nil }