github.com/easysoft/zendata@v0.0.0-20240513203326-705bd5a7fd67/internal/pkg/service/file.go (about) 1 package service 2 3 import ( 4 "os" 5 "strings" 6 7 consts "github.com/easysoft/zendata/internal/pkg/const" 8 "github.com/easysoft/zendata/internal/pkg/domain" 9 fileUtils "github.com/easysoft/zendata/pkg/utils/file" 10 i118Utils "github.com/easysoft/zendata/pkg/utils/i118" 11 logUtils "github.com/easysoft/zendata/pkg/utils/log" 12 "github.com/easysoft/zendata/pkg/utils/vari" 13 "github.com/fatih/color" 14 ) 15 16 type FileService struct { 17 } 18 19 func (s *FileService) ComputerReferFilePath(file string, field *domain.DefField) (resPath string) { 20 resPath = file 21 if fileUtils.IsAbsPath(resPath) && fileUtils.FileExist(resPath) { 22 return 23 } 24 25 resPath = field.FileDir + file 26 if fileUtils.FileExist(resPath) { 27 return 28 } 29 30 resPath = vari.GlobalVars.ConfigFileDir + file 31 if fileUtils.FileExist(resPath) { 32 return 33 } 34 35 resPath = vari.WorkDir + consts.ResDirUsers + consts.PthSep + file 36 if fileUtils.FileExist(resPath) { 37 return 38 } 39 resPath = vari.WorkDir + consts.ResDirYaml + consts.PthSep + file 40 if fileUtils.FileExist(resPath) { 41 return 42 } 43 44 resPath = vari.WorkDir + file 45 if fileUtils.FileExist(resPath) { 46 return 47 } 48 49 return 50 } 51 52 func (s *FileService) LoadFilesContents(files []string) (contents [][]byte) { 53 contents = make([][]byte, 0) 54 for _, f := range files { 55 if f == "" { 56 continue 57 } 58 pathDefaultFile := fileUtils.GetAbsolutePath(f) 59 if !fileUtils.FileExist(pathDefaultFile) { 60 logUtils.PrintToWithColor(i118Utils.I118Prt.Sprintf("fail_to_read_file", pathDefaultFile), color.FgCyan) 61 return 62 } 63 content, err := os.ReadFile(pathDefaultFile) 64 if err != nil { 65 logUtils.PrintToWithColor(i118Utils.I118Prt.Sprintf("fail_to_parse_file", pathDefaultFile), color.FgCyan) 66 return 67 } 68 contents = append(contents, content) 69 } 70 71 return 72 } 73 74 func (s *FileService) GetFilesFromParams(args []string) (files []string, count int) { 75 for _, arg := range args { 76 if strings.Index(arg, "-") != 0 { 77 files = append(files, arg) 78 count++ 79 } else { 80 break 81 } 82 } 83 84 return 85 } 86 87 func (s *FileService) HandleFiles(files []string) []string { 88 if len(files) != 2 { 89 return files 90 } 91 92 if files[0] == "" && files[1] != "" { // no defaultFile 93 files[0] = files[1] 94 files[1] = "" 95 } else if files[1] == "" && files[0] != "" { // no configFile 96 files[1] = files[0] 97 files[0] = "" 98 } 99 100 return files 101 } 102 103 func (s *FileService) HandleFileBuffers(files [][]byte) [][]byte { 104 if len(files) != 2 { 105 return files 106 } 107 108 if files[0] == nil && files[1] != nil { // no defaultFile 109 return [][]byte{files[1]} 110 111 } else if files[1] == nil && files[0] != nil { // no configFile 112 return [][]byte{files[0]} 113 } 114 115 return files 116 }