diff --git a/cmd/main.go b/cmd/main.go index 3e22132..51451a2 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -10,6 +10,7 @@ import ( "mpwt/internal/tui" "mpwt/pkg/log" "os" + "path/filepath" ) func main() { @@ -17,17 +18,22 @@ func main() { debug := flag.Bool("debug", false, "Enable debug mode") flag.Parse() + // Get executable path + exeDir, err := getExecDirectory() + if err != nil { + panic(fmt.Errorf("failed to get executable directory: %v", err)) + } + // Intialize logger and set config file path based on application environment - pwd, _ := os.Getwd() - configPath := pwd + configPath := "" if *debug { - configPath += "/config/config.dev.yaml" + configPath = filepath.Join(exeDir, "/config/config.dev.yaml") log.NewLog(log.EnvDevelopment) } else { - configPath += "/config.yaml" - file, err := os.OpenFile(pwd+"/mpwt.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) + configPath = filepath.Join(exeDir, "/config.yaml") + file, err := os.OpenFile(exeDir+"/mpwt.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if err != nil { - panic(fmt.Sprintf("Failed to create log file: %v", err)) + panic(fmt.Errorf("failed to create log file: %v", err)) } defer file.Close() @@ -42,7 +48,7 @@ func main() { } // Initialize database connection - r, err := repository.NewDbConn(pwd + "/mpwt.db") + r, err := repository.NewDbConn(exeDir + "/mpwt.db") if err != nil { log.Fatal(fmt.Errorf("failed to initialize sqlite: %v", err)) } @@ -67,3 +73,20 @@ func main() { log.Fatal(fmt.Errorf("failed to run tui: %v", err)) } } + +// getExecDirectory returns the directory containing the application executable +func getExecDirectory() (string, error) { + exePath, err := os.Executable() + if err != nil { + return "", fmt.Errorf("failed to retrieve executable path: %v", err) + } + + // Evaluate symlinks to prevent unstable result from os.Executable + resolvedPath, err := filepath.EvalSymlinks(exePath) + if err != nil { + return "", fmt.Errorf("failed to resolve symlink: %v", err) + } + + // Get the directory of the resolved executable + return filepath.Dir(resolvedPath), nil +}