From 0c64670c334e6dbf5d874c7be6a759e5290391e3 Mon Sep 17 00:00:00 2001 From: Piper Pentagram Date: Thu, 14 Nov 2024 11:16:30 -0800 Subject: [PATCH] Use absolute paths where possible bingobot blindly uses the shell's working dir to write logs and read configs. This change introduces the following changes: 1. start.sh now determines the project root's absolute path before reading the token file and starting the app. 2. the config package now determine's the executable's working directory (rather than assuming it's the same as the shell's) before loading configs. It also now exposes this for use in other packages. 3. the logging package now uses config.GetWorkingDir() to determine where to write logs. --- internal/config/config.go | 17 ++++++++++++++++- internal/logging/logging.go | 2 +- start.sh | 9 ++++++--- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/internal/config/config.go b/internal/config/config.go index 00e1983..7830a98 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -2,6 +2,8 @@ package config import ( "fmt" + "os" + "path/filepath" "github.com/spf13/viper" ) @@ -36,16 +38,29 @@ type AppConfig struct { } var config *AppConfig +var workingDir string func init() { setDefaults() viper.Unmarshal(&config) + + ex, err := os.Executable() + + if err != nil { + panic(fmt.Errorf("failed to get path of executable (self): %v", err)) + } + + workingDir = filepath.Dir(ex) } func Get() *AppConfig { return config } +func GetWorkingDir() string { + return workingDir +} + func GetDefaultConfig() *AppConfig { var config *AppConfig setDefaults() @@ -62,7 +77,7 @@ func Init() error { viper.SetConfigName("config") viper.SetConfigType("yaml") - viper.AddConfigPath(".") + viper.AddConfigPath(workingDir) err := viper.ReadInConfig() if err != nil { diff --git a/internal/logging/logging.go b/internal/logging/logging.go index c7e2153..44374ce 100644 --- a/internal/logging/logging.go +++ b/internal/logging/logging.go @@ -20,7 +20,7 @@ func Init() { cfg := config.Get() lj := &lumberjack.Logger{ - Filename: filepath.Join(cfg.LogDir, cfg.LogFile), + Filename: filepath.Join(config.GetWorkingDir(), cfg.LogDir, cfg.LogFile), MaxSize: cfg.LogMaxSizeMB, MaxBackups: cfg.LogMaxBackups, MaxAge: cfg.LogMaxAgeDays, diff --git a/start.sh b/start.sh index c2cc142..ef731b3 100755 --- a/start.sh +++ b/start.sh @@ -1,10 +1,13 @@ +PROJECT_ROOT=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) +TOKEN_FILE="${PROJECT_ROOT}/bot.token" + APP_ID=1303795224857804851 -if [ ! -f "bot.token" ]; then +if [ ! -f "${TOKEN_FILE}" ]; then echo "can't startup: bot.token file missing" exit 2 fi -BOT_TOKEN=$(cat bot.token) +BOT_TOKEN=$(cat ${TOKEN_FILE}) -./bingobot --token ${BOT_TOKEN} +${PROJECT_ROOT}/bingobot --token ${BOT_TOKEN}