diff --git a/file.go b/file.go new file mode 100644 index 0000000..28ea6dd --- /dev/null +++ b/file.go @@ -0,0 +1,145 @@ +// Package command ... +// +// Description : 文件相关操作 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2022-05-22 12:23 +package command + +import ( + "errors" + "os" + "strings" +) + +// File ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 12:25 2022/5/22 +func File(workDir string, filePath string) *fileOperate { + if len(workDir) == 0 { + workDir, _ = os.Getwd() + } + if !strings.HasPrefix(filePath, "/") { + filePath = strings.ReplaceAll(workDir+"/"+filePath, "//", "/") + } + return &fileOperate{ + workDir: workDir, + filePath: filePath, + permission: 0644, + openFlag: os.O_RDONLY, + } +} + +// file ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 12:24 2022/5/22 +type fileOperate struct { + workDir string + filePath string + autoCreate bool + permission os.FileMode + openFlag int + fileHandler *os.File +} + +// IsExist 文件是否存在 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 12:30 2022/5/22 +func (f *fileOperate) IsExist() (bool, bool, error) { + fileState, err := os.Stat(f.filePath) + if err != nil { + if os.IsNotExist(err) { + return false, false, nil + } + return false, false, err + } + return true, fileState.IsDir(), nil +} + +// AutoCreate 文件不存在时自动创建 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 12:28 2022/5/22 +func (f *fileOperate) AutoCreate() *fileOperate { + f.autoCreate = true + return f +} + +// Permission 设置文件权限 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 13:00 2022/5/22 +func (f *fileOperate) Permission(fileModel os.FileMode) *fileOperate { + f.permission = fileModel + return f +} + +// SetOpenFlag ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 13:40 2022/5/22 +func (f *fileOperate) SetOpenFlag(flagList ...int) *fileOperate { + for _, flag := range flagList { + f.openFlag = f.openFlag | flag + } + return f +} + +// Create 创建文件 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 13:04 2022/5/22 +func (f *fileOperate) Create() error { + + var ( + fileExist bool + isDir bool + err error + ) + + if fileExist, isDir, err = f.IsExist(); nil != err { + return err + } + + if isDir { + return errors.New("路径已存在, 且为目录 : " + f.filePath) + } + + if !fileExist { + // 文件不存在 + if !f.autoCreate { + return errors.New("文件不存在, 且不允许自动创建 : " + f.filePath) + } + } + f.fileHandler, err = os.OpenFile(f.filePath, f.openFlag, f.permission) + return err +} + +// Open 打开文件 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 13:22 2022/5/22 +func (f *fileOperate) Open() error { + return f.Create() +} + +// GetFileHandler 获取文件处理句柄 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 13:23 2022/5/22 +func (f *fileOperate) GetFileHandler() *os.File { + return f.fileHandler +}