1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-11 08:12:26 +08:00

fix: fix ExecCommand bug in windows

This commit is contained in:
dudaodong
2022-12-09 19:10:55 +08:00
parent af5cfe6da1
commit 09d98745b0
2 changed files with 64 additions and 20 deletions

View File

@@ -9,6 +9,10 @@ import (
"os"
"os/exec"
"runtime"
"unicode/utf8"
"github.com/duke-git/lancet/v2/validator"
"golang.org/x/text/encoding/simplifiedchinese"
)
// IsWindows check if current os is windows
@@ -50,27 +54,61 @@ func CompareOsEnv(key, comparedEnv string) bool {
return env == comparedEnv
}
// ExecCommand use shell /bin/bash -c to execute command
// ExecCommand execute command, return the stdout and stderr string of command, and error if error occur
// param `command` is a complete command strinig, like, ls -a (linux), dir(windows), ping 127.0.0.1
// for linux, use /bin/bash -c to execute command
// for windows, use powershell.exe to execute command
func ExecCommand(command string) (stdout, stderr string, err error) {
var out bytes.Buffer
var errout bytes.Buffer
var errOut bytes.Buffer
cmd := exec.Command("/bin/bash", "-c", command)
if IsWindows() {
cmd = exec.Command("cmd")
cmd = exec.Command("powershell.exe", command)
}
cmd.Stdout = &out
cmd.Stderr = &errout
cmd.Stderr = &errOut
err = cmd.Run()
if err != nil {
stderr = string(errout.Bytes())
if utf8.Valid(errOut.Bytes()) {
stderr = byteToString(errOut.Bytes(), "UTF8")
} else if validator.IsGBK(errOut.Bytes()) {
stderr = byteToString(errOut.Bytes(), "GBK")
}
return
}
data := out.Bytes()
if utf8.Valid(data) {
stdout = byteToString(data, "UTF8")
} else if validator.IsGBK(data) {
stdout = byteToString(data, "GBK")
}
stdout = string(out.Bytes())
return
}
func byteToString(data []byte, charset string) string {
var result string
switch charset {
case "GBK":
decodeBytes, _ := simplifiedchinese.GBK.NewDecoder().Bytes(data)
result = string(decodeBytes)
case "GB18030":
decodeBytes, _ := simplifiedchinese.GB18030.NewDecoder().Bytes(data)
result = string(decodeBytes)
case "UTF8":
fallthrough
default:
result = string(data)
}
return result
}
// GetOsBits get this system bits 32bit or 64bit
// return bit int (32/64)
func GetOsBits() int {