From 4acdd09745113c95ce8ac72d3e0e2c93e8efa4cd Mon Sep 17 00:00:00 2001 From: rodley82 Date: Sun, 19 Jun 2022 02:53:27 -0300 Subject: [PATCH] Reading actions from the comma separated values on the ENV vars --- config/app.go | 73 ++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 67 insertions(+), 6 deletions(-) diff --git a/config/app.go b/config/app.go index 35f93f7..2eb2d53 100644 --- a/config/app.go +++ b/config/app.go @@ -1,24 +1,85 @@ package config import ( + "fmt" "os" - + "encoding/csv" + "strings" + "io" "github.com/joho/godotenv" ) type ConfigEntries struct { SlackAuthToken string SlackAppToken string - ActionScript1 string - ActionScript2 string + Actions []ActionScript +} + +type ActionScript struct { + Name string + DisplayName string + Path string } var Config ConfigEntries +// var Actions []ActionScript -func init(){ - // fmt.Println("init de config!") - // Load Env variables from .dot file +func init() { + fmt.Println("Initializing App Config settings") + // TODO: Add if defined app will read from .env godotenv.Load(".env") Config.SlackAuthToken = os.Getenv("SLACK_AUTH_TOKEN") Config.SlackAppToken = os.Getenv("SLACK_APP_TOKEN") + actionsLoaded := initalizeDefinedActions() + fmt.Println("Finished loading config. Actions found:", actionsLoaded) + fmt.Println("Actions:", Config.Actions) +} + +// Each action is defined on an env variable named `BOT_ACTION_1` `BOT_ACTION_2` +// the index starts with 1 and each must contain three comma separated values +// `Name,Display Name,Path` +// For example: +// `poweron,Encender Server,/some/script.sh` +func initalizeDefinedActions() int { + fmt.Println("initalizeDefinedActions") + var count = 1 + var value string + var exists bool + for { + envVarName := fmt.Sprintf("BOT_ACTION_%d", count) + fmt.Println("Checking for env var:", envVarName) + value, exists = os.LookupEnv(envVarName) + if !exists { + fmt.Println("Not fonud, giving up") + break + } + fmt.Println("Action found:", value) + action := actionStringToActionScript(value) + // Actions = append(Actions, action) + Config.Actions = append(Config.Actions, action) + count++ + } + return count +} + +func actionStringToActionScript(actionString string) ActionScript{ + var action ActionScript + var csvArr []string + var err error + r := csv.NewReader(strings.NewReader(actionString)) + for { + csvArr, err = r.Read() + if err == io.EOF { + break + } + if err != nil { + // log.Fatal(err) + } else { + action.Name = csvArr[0] + action.DisplayName = csvArr[1] + action.Path = csvArr[2] + } + } + + return action }