package comfunc
import (
"os"
"os/exec"
"path/filepath"
"strings"
)
func Workdir () string {
dir , _ := os .Getwd ()
return dir
}
func ExpandHome (pathStr string ) string {
if len (pathStr ) == 0 {
return pathStr
}
if pathStr [0 ] != '~' {
return pathStr
}
if len (pathStr ) > 1 && pathStr [1 ] != '/' && pathStr [1 ] != '\\' {
return pathStr
}
homeDir , err := os .UserHomeDir ()
if err != nil {
return pathStr
}
return homeDir + pathStr [1 :]
}
func ExecCmd (binName string , args []string , workDir ...string ) (string , error ) {
cmd := exec .Command (binName , args ...)
if len (workDir ) > 0 {
cmd .Dir = workDir [0 ]
}
bs , err := cmd .Output ()
return string (bs ), err
}
func ShellExec (cmdLine string , shells ...string ) (string , error ) {
shell := "sh"
if len (shells ) > 0 {
shell = shells [0 ]
}
cmd := exec .Command (shell , "-c" , cmdLine )
bs , err := cmd .Output ()
return string (bs ), err
}
var curShellCache string
func CurrentShell (onlyName bool , fallbackShell ...string ) (binPath string ) {
var err error
fbShell := ""
if len (fallbackShell ) > 0 {
fbShell = fallbackShell [0 ]
}
if curShellCache == "" {
parentProcess := os .Getenv ("GOPROCESS" )
if parentProcess != "" {
binPath = parentProcess
} else {
binPath = os .Getenv ("SHELL" )
if len (binPath ) == 0 {
binPath , err = ShellExec ("echo $SHELL" )
if err != nil {
binPath = fbShell
}
}
binPath = strings .TrimSpace (binPath )
}
if pos := strings .IndexByte (binPath , '.' ); pos > 0 {
binPath = binPath [:pos ]
}
curShellCache = binPath
} else {
binPath = curShellCache
}
if onlyName && len (binPath ) > 0 {
binPath = filepath .Base (binPath )
} else if len (binPath ) == 0 {
binPath = fbShell
}
return
}
func HasShellEnv (shell string ) bool {
out , err := ShellExec ("echo OK" , shell )
if err != nil {
return false
}
return strings .TrimSpace (out ) == "OK"
}
The pages are generated with Golds v0.8.4 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .