github.com/richardwilkes/toolbox@v1.121.0/appdir.go (about) 1 // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved. 2 // 3 // This Source Code Form is subject to the terms of the Mozilla Public 4 // License, version 2.0. If a copy of the MPL was not distributed with 5 // this file, You can obtain one at http://mozilla.org/MPL/2.0/. 6 // 7 // This Source Code Form is "Incompatible With Secondary Licenses", as 8 // defined by the Mozilla Public License, version 2.0. 9 10 package toolbox 11 12 import ( 13 "os" 14 "path/filepath" 15 "runtime" 16 "strings" 17 18 "github.com/richardwilkes/toolbox/errs" 19 ) 20 21 // AppDir returns the logical directory the application resides within. For macOS, this means the directory where the 22 // .app bundle resides, not the binary that's tucked down inside it. 23 func AppDir() (string, error) { 24 path, err := os.Executable() 25 if err != nil { 26 return "", errs.Wrap(err) 27 } 28 if path, err = filepath.EvalSymlinks(path); err != nil { 29 return "", errs.Wrap(err) 30 } 31 if path, err = filepath.Abs(path); err != nil { 32 return "", errs.Wrap(err) 33 } 34 path = filepath.Dir(path) 35 if runtime.GOOS == MacOS { 36 // Account for macOS bundles 37 if i := strings.LastIndex(path, ".app/"); i != -1 { 38 path = filepath.Dir(path[:i]) 39 } 40 } 41 return path, nil 42 }