1
0
mirror of https://github.com/mainflux/mainflux.git synced 2025-04-26 13:48:53 +08:00
João Matos 3273c30d8b
MF-1268 - CLI improvements (#1274)
* Prefix error messages in CLI with a bold "error: ".

Signed-off-by: Joao Matos <joao@tritao.eu>

* Remove duplicated "Usage: " from groups command help.

Signed-off-by: Joao Matos <joao@tritao.eu>

* Add a raw output mode for CLI and use it on logCreated.

Signed-off-by: Joao Matos <joao@tritao.eu>

* Add CLI global flag for user auth token.

Signed-off-by: Joao Matos <joao@tritao.eu>

* Add CLI config flag and parsing logic.

Signed-off-by: Joao Matos <joao@tritao.eu>

* Refactor CLI users commands outside array structure.

Signed-off-by: Joao Matos <joao@tritao.eu>

* Refactor CLI certificates commands using flags.

Signed-off-by: Joao Matos <joao@tritao.eu>

* Refactor CLI things create command using flags.

Signed-off-by: Joao Matos <joao@tritao.eu>

Co-authored-by: Drasko DRASKOVIC <drasko.draskovic@gmail.com>
2020-11-01 00:29:06 +01:00

82 lines
1.7 KiB
Go

package cli
import (
"fmt"
"io/ioutil"
"log"
"os"
"path"
"github.com/mainflux/mainflux/pkg/errors"
"github.com/pelletier/go-toml"
)
type Config struct {
AuthToken string `toml:"auth_token"`
}
// save - store config in a file
func save(c Config, file string) error {
b, err := toml.Marshal(c)
if err != nil {
return errors.New(fmt.Sprintf("failed to read config file: %s", err))
}
if err := ioutil.WriteFile(file, b, 0644); err != nil {
return errors.New(fmt.Sprintf("failed to write config TOML: %s", err))
}
return nil
}
// read - retrieve config from a file
func read(file string) (Config, error) {
data, err := ioutil.ReadFile(file)
c := Config{}
if err != nil {
return c, errors.New(fmt.Sprintf("failed to read config file: %s", err))
}
if err := toml.Unmarshal(data, &c); err != nil {
return Config{}, errors.New(fmt.Sprintf("failed to unmarshal config TOML: %s", err))
}
return c, nil
}
func getConfigPath() (string, error) {
// Check if a config path passed by user exists.
if ConfigPath != "" {
if _, err := os.Stat(ConfigPath); os.IsNotExist(err) {
errConfigNotFound := errors.Wrap(errors.New("config file was not found"), err)
logError(errConfigNotFound)
return "", err
}
}
// If not, then read it from the user config directory.
if ConfigPath == "" {
userConfigDir, _ := os.UserConfigDir()
ConfigPath = path.Join(userConfigDir, "mainflux", "cli.toml")
}
if _, err := os.Stat(ConfigPath); os.IsNotExist(err) {
return "", err
}
return ConfigPath, nil
}
func ParseConfig() {
path, err := getConfigPath()
if err != nil {
return
}
config, err := read(path)
if err != nil {
log.Fatal(err)
}
if UserAuthToken == "" {
UserAuthToken = config.AuthToken
}
}