github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/osx/logdir.go (about) 1 package osx 2 3 import ( 4 "os" 5 "os/exec" 6 "path/filepath" 7 "strconv" 8 "strings" 9 ) 10 11 // GetGroupID the current user's group ID. 12 func GetGroupID() int64 { 13 if out, err := exec.Command("id", "-g").Output(); err == nil { 14 v := strings.TrimSpace(string(out)) 15 if g, e := strconv.ParseInt(v, 10, 32); e == nil { 16 return g 17 } 18 } 19 return -1 20 } 21 22 // IsRootGroup tells the current user's group is zero or not. 23 func IsRootGroup() bool { 24 return GetGroupID() == 0 25 } 26 27 // CreateLogDir creates a log path. 28 // If logDir is empty, /var/log/{appName} or ~/logs/{appName} will used as logDir. 29 // If appName is empty, os.Args[0]'s base will be use as appName. 30 func CreateLogDir(logDir, appName string) string { 31 if appName == "" { 32 appName = filepath.Base(os.Args[0]) 33 } 34 35 if logDir == "" { 36 if IsRootGroup() { 37 logDir = filepath.Join("/var/log/", appName) 38 } else { 39 logDir = filepath.Join("~/logs/" + appName) 40 } 41 } else { 42 if stat, err := os.Stat(logDir); err == nil && !stat.IsDir() { 43 logDir = filepath.Dir(logDir) 44 } 45 } 46 47 logDir = ExpandHome(logDir) 48 if stat, err := os.Stat(logDir); err == nil && stat.IsDir() { 49 return logDir 50 } 51 52 if err := os.MkdirAll(logDir, os.ModeSticky|os.ModePerm); err != nil { 53 panic(err) 54 } 55 56 return logDir 57 }