schastsp/client/config.go

136 lines
2.4 KiB
Go
Raw Permalink Normal View History

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