github.com/easysoft/zendata@v0.0.0-20240513203326-705bd5a7fd67/internal/pkg/service/text.go (about) 1 package service 2 3 import ( 4 "fmt" 5 "os" 6 "regexp" 7 "strconv" 8 "strings" 9 10 consts "github.com/easysoft/zendata/internal/pkg/const" 11 "github.com/easysoft/zendata/internal/pkg/domain" 12 "github.com/easysoft/zendata/internal/pkg/helper" 13 i118Utils "github.com/easysoft/zendata/pkg/utils/i118" 14 logUtils "github.com/easysoft/zendata/pkg/utils/log" 15 stringUtils "github.com/easysoft/zendata/pkg/utils/string" 16 ) 17 18 type TextService struct { 19 RangeService *RangeService `inject:""` 20 FileService *FileService `inject:""` 21 } 22 23 func (s *TextService) CreateFieldValuesFromText(field *domain.DefField) { 24 ranges := strings.Split(strings.TrimSpace(field.Range), ",") 25 26 for _, rang := range ranges { 27 rang = strings.TrimSpace(rang) 28 repeat, repeatTag, rangWithoutRepeat := s.RangeService.ParseRepeat(rang) 29 30 // get file and step string 31 sectionArr := strings.Split(rangWithoutRepeat, ":") 32 file := sectionArr[0] 33 stepStr := "1" 34 if len(sectionArr) == 2 { 35 stepStr = sectionArr[1] 36 } 37 38 // read from file 39 list := make([]string, 0) 40 realPath := s.FileService.ComputerReferFilePath(file, field) 41 content, err := os.ReadFile(realPath) 42 if err != nil { 43 logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_read_file", file+" - "+realPath)) 44 field.Values = append(field.Values, fmt.Sprintf("FILE_NOT_FOUND")) 45 return 46 } 47 48 str := string(content) 49 re := regexp.MustCompile(`\r?\t?\n`) 50 str = re.ReplaceAllString(str, "\n") 51 str = stringUtils.TrimAll(str) 52 list = strings.Split(str, "\n") 53 54 // get step and rand 55 rand := false 56 step := 1 57 if strings.ToLower(strings.TrimSpace(stepStr)) == "r" { 58 rand = true 59 } else { 60 stepInt, err := strconv.Atoi(stepStr) 61 if err == nil { 62 step = stepInt 63 if step < 0 { 64 step = step * -1 65 } 66 } 67 } 68 69 // get index list for data retrieve 70 numbs := helper.GenerateItems(int64(0), int64(len(list)-1), int64(step), 0, rand, 1, "", 0) 71 72 // gen data by index 73 count := 0 74 if repeatTag == "" { 75 for _, numb := range numbs { 76 item := list[numb.(int64)] 77 if strings.TrimSpace(item) == "" { // ignore empty line 78 continue 79 } 80 81 for i := 0; i < repeat; i++ { 82 field.Values = append(field.Values, item) 83 84 count++ 85 if count >= consts.MaxNumb { 86 break 87 } 88 } 89 90 count++ 91 if count >= consts.MaxNumb { 92 break 93 } 94 } 95 } else if repeatTag == "!" { 96 for i := 0; i < repeat; i++ { 97 for _, numb := range numbs { 98 item := list[numb.(int64)] 99 if strings.TrimSpace(item) == "" { // ignore empty line 100 continue 101 } 102 103 field.Values = append(field.Values, item) 104 105 count++ 106 if count >= consts.MaxNumb { 107 break 108 } 109 } 110 111 count++ 112 if count >= consts.MaxNumb { 113 break 114 } 115 } 116 } 117 } 118 119 if len(field.Values) == 0 { 120 field.Values = append(field.Values, "N/A") 121 } 122 }