Skip to content

Commit

Permalink
added environment variables for configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
Kharonus committed Jun 30, 2023
1 parent b39db97 commit effe522
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
2 changes: 1 addition & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func init() {
activePrinter := &printer.ConsolePrinter{}
printer.Init(activePrinter)

host, token, err := configuration.ReadConfigFile()
host, token, err := configuration.ReadConfig()
if err != nil {
printer.Error(err)
return
Expand Down
26 changes: 22 additions & 4 deletions components/configuration/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,19 @@ package configuration

import (
"fmt"
"github.com/opf/openproject-cli/components/errors"
"os"
"path/filepath"
"strings"

"github.com/opf/openproject-cli/components/errors"
)

const configDirName = "openproject"
const configFileName = "config"
const (
envHost = "OP_CLI_HOST"
envToken = "OP_CLI_TOKEN"
configDirName = "openproject"
configFileName = "config"
)

func WriteConfigFile(host, token string) error {
err := ensureConfigDir()
Expand All @@ -21,12 +26,17 @@ func WriteConfigFile(host, token string) error {
return os.WriteFile(configFile(), bytes, 0644)
}

func ReadConfigFile() (host, token string, err error) {
func ReadConfig() (host, token string, err error) {
err = ensureConfigDir()
if err != nil {
return "", "", err
}

ok, h, t := readEnvironment()
if ok {
return h, t, nil
}

file, err := os.ReadFile(configFile())
if os.IsNotExist(err) {
// Empty config file is no error,
Expand All @@ -43,6 +53,14 @@ func ReadConfigFile() (host, token string, err error) {
return parts[0], parts[1], nil
}

func readEnvironment() (ok bool, host, token string) {
host, hasHost := os.LookupEnv(envHost)
token, hasToken := os.LookupEnv(envToken)
ok = hasHost && hasToken

return
}

func ensureConfigDir() error {
if _, err := os.Stat(configFileDir()); os.IsNotExist(err) {
err = os.MkdirAll(configFileDir(), 0700)
Expand Down

0 comments on commit effe522

Please sign in to comment.