Skip to content

Commit

Permalink
refactor: use executable file path instead of pwd
Browse files Browse the repository at this point in the history
  • Loading branch information
songlim327 committed Oct 8, 2024
1 parent 4d6df7e commit 0947020
Showing 1 changed file with 30 additions and 7 deletions.
37 changes: 30 additions & 7 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,30 @@ import (
"mpwt/internal/tui"
"mpwt/pkg/log"
"os"
"path/filepath"
)

func main() {
// Identify application enviroment (development/production)
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()

Expand All @@ -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))
}
Expand All @@ -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
}

0 comments on commit 0947020

Please sign in to comment.