You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

140 lines
2.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package CommonUtil
import (
"bufio"
"bytes"
"errors"
uuid "github.com/satori/go.uuid"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
)
/**
功能带回显的执行DOS命令
作者:黄海
时间2020-05-18
*/
func Exec(name string, dir string, args ...string) error {
cmd := exec.Command(name, args...)
stderr, _ := cmd.StderrPipe()
stdout, _ := cmd.StdoutPipe()
cmd.Dir = dir
if err := cmd.Start(); err != nil {
log.Println("exec the cmd ", name, " failed")
return err
}
// 正常日志
logScan := bufio.NewScanner(stdout)
go func() {
for logScan.Scan() {
log.Println(logScan.Text())
}
}()
// 错误日志
errBuf := bytes.NewBufferString("")
scan := bufio.NewScanner(stderr)
for scan.Scan() {
s := scan.Text()
log.Println("", s)
errBuf.WriteString(s)
errBuf.WriteString("\n")
}
// 等待命令执行完
cmd.Wait()
if !cmd.ProcessState.Success() {
// 执行失败,返回错误信息
return errors.New(errBuf.String())
}
return nil
}
/*
判断文件或文件夹是否存在
如果返回的错误为nil,说明文件或文件夹存在
如果返回的错误类型使用os.IsNotExist()判断为true,说明文件或文件夹不存在
如果返回的错误为其它类型,则不确定是否在存在
*/
func PathExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
/**
功能:获取当前路径
作者:黄海
时间2020-06-02
*/
func GetCurrentPath() string {
dir, _ := os.Getwd()
dir = strings.ReplaceAll(dir, "\\", "/")
return dir
}
/**
功能:获取当前工作目录的父路径
作者:黄海
时间2020-06-02
*/
func GetCurrentParentPath()string{
return GetParentPath(GetCurrentPath())
}
/**
功能:返回上一级目录
*/
func GetParentPath(directory string) string {
return strings.Replace(filepath.Dir(directory), "\\", "/", -1)
}
/**
功能:数组中是否存在某个字符串
作者:黄海
时间2020-05-30
*/
func IsContainString(items []string, item string) bool {
for _, eachItem := range items {
if eachItem == item {
return true
}
}
return false
}
func IsContainInt32(items []int32, item int32) bool {
for _, eachItem := range items {
if eachItem == item {
return true
}
}
return false
}
/**
功能获取UUID
作者:黄海
时间2020-02-03
*/
func GetUUID() string {
u2 := strings.ToUpper(uuid.NewV4().String())
return u2
}
/**
功能:将字符串转为整数
作者:黄海
时间2020-06-03
*/
func ConvertStringToInt(s string) int {
int, _ := strconv.Atoi(s)
return int
}