拓展类型 自定义工具类型

This commit is contained in:
2024-10-10 18:22:50 +08:00
parent 3b69ba93ad
commit 1a0a9466d8
14 changed files with 374 additions and 31 deletions
+51
View File
@@ -0,0 +1,51 @@
package utils
import (
"bufio"
"context"
"io"
"os/exec"
"strings"
"syscall"
)
type execUtils struct{}
var Exec = &execUtils{}
func (e *execUtils) Command(cmdstr, dir string) (string, error) {
reader, err := e.CommandContext(context.Background(), cmdstr, dir, nil)
if err != nil {
return "", err
}
scanner := bufio.NewScanner(reader)
var out string
for scanner.Scan() {
out += scanner.Text() + "\n"
}
return out, reader.Close()
}
func (e *execUtils) CommandContext(ctx context.Context, cmdstr, dir string, cancel func()) (io.ReadCloser, error) {
cmdArgs := strings.Split(cmdstr, " ")
cmd := exec.CommandContext(ctx, cmdArgs[0], cmdArgs[1:]...)
cmd.Dir = dir
cmd.Cancel = func() error {
if cancel != nil {
cancel()
}
return cmd.Process.Kill()
}
// 关闭黑框
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
// 输出
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
err = cmd.Start()
if err != nil {
return nil, err
}
return stdout, nil
}
+95
View File
@@ -0,0 +1,95 @@
package utils
import (
"io"
"os"
"os/exec"
"path/filepath"
)
type FileUtils struct{}
var File = &FileUtils{}
func (f *FileUtils) CopyDir(src, dst string) error {
// 获取源文件夹信息
srcInfo, err := os.Stat(src)
if err != nil {
return err
}
// 创建目标文件夹
err = os.MkdirAll(dst, srcInfo.Mode())
if err != nil {
return err
}
// 读取源文件夹
dir, err := os.ReadDir(src)
if err != nil {
return err
}
for _, file := range dir {
srcFile := filepath.Join(src, file.Name())
dstFile := filepath.Join(dst, file.Name())
if file.IsDir() {
// 递归复制子文件夹
err = f.CopyDir(srcFile, dstFile)
if err != nil {
return err
}
} else {
// 复制文件
err = f.CopyFile(srcFile, dstFile)
if err != nil {
return err
}
}
}
return nil
}
func (f *FileUtils) CopyFile(src, dst string) error {
srcFile, err := os.Open(src)
if err != nil {
return err
}
defer srcFile.Close()
dstFile, err := os.Create(dst)
if err != nil {
return err
}
defer dstFile.Close()
_, err = io.Copy(dstFile, srcFile)
if err != nil {
return err
}
return nil
}
func (*FileUtils) WinOpenFolder(folderPath string) error {
cmd := exec.Command("explorer", folderPath)
return cmd.Run()
//fileInfo, err := os.Stat(folderPath)
//if os.IsNotExist(err) {
// return err
//}
//var (
// dir = ""
// f = ""
//)
//if fileInfo.IsDir() {
// dir = ""
// f = folderPath
//} else {
// dir = filepath.Dir(folderPath)
// f = filepath.Base(folderPath)
//}
//_, err = Exec.Command(fmt.Sprintf("explorer %s", f), dir)
//return err
}