github.com/cidverse/cid-sdk-go@v0.0.0-20240318001225-c193d83f053e/file.go (about) 1 package cidsdk 2 3 import ( 4 "os" 5 "path/filepath" 6 "strings" 7 8 cp "github.com/otiai10/copy" 9 ) 10 11 type FileRequest struct { 12 Directory string `json:"dir"` 13 Extensions []string `json:"ext"` 14 } 15 16 type File struct { 17 Path string `json:"path"` 18 Directory string `json:"dir"` 19 Name string `json:"name"` 20 NameShort string `json:"name_short"` 21 Extension string `json:"ext"` 22 } 23 24 func NewFile(path string) File { 25 split := strings.SplitN(filepath.Base(path), ".", 2) 26 fileName := split[0] 27 fileExt := "" 28 if len(split) > 1 && split[1] != "" { 29 fileExt = "." + split[1] 30 } 31 32 return File{ 33 Path: path, 34 Directory: filepath.Dir(path), 35 Name: filepath.Base(path), 36 NameShort: fileName, 37 Extension: fileExt, 38 } 39 } 40 41 // FileRead command 42 func (sdk SDK) FileRead(file string) (string, error) { 43 data, err := os.ReadFile(file) 44 if err != nil { 45 return "", err 46 } 47 48 return string(data), nil 49 } 50 51 // FileList command 52 func (sdk SDK) FileList(req FileRequest) (files []File, err error) { 53 err = filepath.Walk(req.Directory, func(path string, info os.FileInfo, err error) error { 54 if info != nil && !info.IsDir() { 55 if len(req.Extensions) > 0 { 56 for _, ext := range req.Extensions { 57 if strings.HasSuffix(path, ext) { 58 files = append(files, NewFile(path)) 59 break 60 } 61 } 62 } else { 63 files = append(files, NewFile(path)) 64 } 65 } 66 67 return nil 68 }) 69 70 return 71 } 72 73 // FileRename command 74 func (sdk SDK) FileRename(old string, new string) error { 75 err := os.Rename(old, new) 76 if err != nil { 77 return err 78 } 79 80 return nil 81 } 82 83 // FileCopy command 84 func (sdk SDK) FileCopy(old string, new string) error { 85 err := cp.Copy(old, new) 86 87 return err 88 } 89 90 // FileRemove command 91 func (sdk SDK) FileRemove(file string) error { 92 err := os.Remove(file) 93 if err != nil { 94 return err 95 } 96 97 return nil 98 } 99 100 // FileWrite command 101 func (sdk SDK) FileWrite(file string, content []byte) error { 102 err := os.WriteFile(file, content, os.ModePerm) 103 if err != nil { 104 return err 105 } 106 107 return nil 108 } 109 110 // FileExists command 111 func (sdk SDK) FileExists(file string) bool { 112 if _, err := os.Stat(file); err == nil { 113 return true 114 } 115 116 return false 117 }