提交 ad088f85 编写于 作者: aaronchen2k2k's avatar aaronchen2k2k

fix a issue when provide yaml with -d

上级 90811afd
Version = 1
Language = zh
......@@ -7,6 +7,8 @@ field: ip
instances:
- instance: privateC
prefix: 192.168.
loop: 2
loopfix: "-"
fields:
- field: part3
range: 0-254
......
......@@ -8,7 +8,7 @@ fields:
note: 引用同级目录中的yaml文件,取small和large两个分组的值
from: numb.yaml
use: small,large
loop: 3
loop: 2
loopfix: "|"
prefix: "["
postfix: "]"
\ No newline at end of file
......@@ -5,3 +5,7 @@ version: 1.0
fields:
- field: field1
loop: 2
loopfix: " "
prefix: "{"
postfix: "}"
\ No newline at end of file
......@@ -7,7 +7,7 @@ field: number
prefix: "'"
postfix: "'"
loop: 2
loopfix: "."
loopfix: "-"
ranges:
small: 1-9
medium: 11-99
......
......@@ -13,14 +13,17 @@ fields:
from: numb.yaml
use: small,large
loop: 3
loopfix: "-"
postfix: ","
loopfix: " "
postfix: " "
expect: 1,2,3,101,102...
- field: field2
note: 引用內置IP地址数据定义中的C类地址
from: system.ip.v1.yaml
use: privateC
prefix: _
loop: 3
loopfix: " "
expect: 192.168.0.1 ...​
- field: field3
......
$>zd.exe -s 根据系统提示,设置工具语言等属性
$>zd.exe -h 查看使用帮助
$>zd.exe -h 查看使用帮助。
$>zd.exe -y demo/test.yaml -c 15 -field field1 -o demo/output.txt -f text
执行数据生成命令。使用配置文件demo/test.yaml,生成15行数据,以text格式的输出到demo/output.txt文件中。
$>zd.exe -y demo/test.yaml -c 15 -field field1 -o demo/output.txt -f text
执行数据生成命令。使用配置文件demo/test.yaml,生成15行数据,以text格式的输出到demo/output.txt文件中
$>zd.exe -y demo/test.yaml -c 15 -field field1 -o demo/insert.sql -f sql -t table_name
执行数据生成命令。以SQL语句形式输出到demo/insert.sql文件中,表名为table_name
$>zd.exe -y demo/test.yaml -c 15 -field field1 -o demo/insert.sql -f sql -t table_name
执行数据生成命令。以SQL语句形式输出到demo/insert.sql文件中,表名为table_name
$>zd.exe -d demo/base.yaml -y demo/test.yaml -c 15 -field field1 -o demo/output.txt
执行数据生成命令。使用文件demo/test.yam覆盖默认配置demo/common.yaml中的内容
$>zd.exe -d demo/base.yaml -y demo/test.yaml -c 15 -field field1 -o demo/output.txt
执行数据生成命令。使用文件demo/test.yam覆盖默认配置demo/common.yaml中的内容。
$>zd.exe -i xdoc/test/zentao.sql -o out
从指定的数据库Schema,创建yaml定义文件,输出到out目录下。
\ No newline at end of file
$>zd.exe -i xdoc/test/zentao.sql -o out
从指定的数据库Schema,创建yaml定义文件,输出到out目录下。
\ No newline at end of file
-h --help 查看帮助信息。
-s --set 设置工具语言属性。用户对当前目录需要有写权限。
-h --help 查看帮助信息。
-s --set 设置工具语言属性。用户对当前目录需要有写权限。
默认根据定义文件生成数据。
-d --default 默认定义文件
-y --yaml 指定定义文件
-c --count 指定生成数据的条数
--field 需要输出的字段,用逗号分隔。未指定时,默认输出-yaml文件中的所有字段。
-o --out 指定输出文件
-f --format 输出格式,支持text、json、xml和sql语句,默认为text。
-t --table 输出格式为table时,用于指定insert语句的表名
--verbose 增加此参数,显示详细调试信息。
默认根据定义文件生成数据。
-d --default 默认定义文件
-y --yaml 指定定义文件
-c --count 指定生成数据的条数
--field 需要输出的字段,用逗号分隔。未指定时,默认输出-yaml文件中的所有字段。
-o --out 指定输出文件
-f --format 输出格式,支持text、json、xml和sql语句,默认为text。
-t --table 输出格式为table时,用于指定insert语句的表名
--verbose 增加此参数,显示详细调试信息。
为了方便在任意目录中执行%s命令,建议将其加入环境变量中,具体方法参照以下地址。
https://www.ztesting.net/book/ztf-doc/add-to-path-46.html
\ No newline at end of file
为了方便在任意目录中执行%s命令,建议将其加入环境变量中,具体方法参照以下地址。
https://www.ztesting.net/book/ztf-doc/add-to-path-46.html
\ No newline at end of file
此差异已折叠。
package action
import configUtils "github.com/easysoft/zendata/src/utils/config"
func Set() {
configUtils.InputForSet()
}
......@@ -7,27 +7,29 @@ import (
"github.com/easysoft/zendata/src/gen"
"github.com/easysoft/zendata/src/model"
constant "github.com/easysoft/zendata/src/utils/const"
i118Utils "github.com/easysoft/zendata/src/utils/i118"
logUtils "github.com/easysoft/zendata/src/utils/log"
"github.com/easysoft/zendata/src/utils/vari"
"os"
"path/filepath"
"strings"
"time"
)
func Generate(deflt string, yml string, total int, fieldsToExportStr string, out string, format string, table string) {
startTime := time.Now().Unix()
//startTime := time.Now().Unix()
if deflt != "" && yml == "" {
yml = deflt
deflt = ""
}
fieldsToExport := make([]string, 0)
if fieldsToExportStr != "" {
fieldsToExport = strings.Split(fieldsToExportStr, ",")
}
vari.InputDir = filepath.Dir(yml) + string(os.PathSeparator)
constant.Total = total
fieldsToExport := strings.Split(fieldsToExportStr, ",")
rows, colTypes := gen.GenerateForDefinition(deflt, yml, fieldsToExport, total)
content := Print(rows, format, table, colTypes, fieldsToExport)
......@@ -35,8 +37,8 @@ func Generate(deflt string, yml string, total int, fieldsToExportStr string, out
WriteToFile(out, content)
}
entTime := time.Now().Unix()
logUtils.Screen(i118Utils.I118Prt.Sprintf("generate_records", len(rows), out, entTime - startTime ))
//entTime := time.Now().Unix()
//logUtils.Screen(i118Utils.I118Prt.Sprintf("generate_records", len(rows), out, entTime - startTime ))
}
func Print(rows [][]string, format string, table string, colTypes []bool, fields []string) string {
......@@ -55,8 +57,8 @@ func Print(rows [][]string, format string, table string, colTypes []bool, fields
for j, col := range cols {
if j >0 {
line = line + ", "
valueList = valueList + ", "
line = line + ""
valueList = valueList + ""
}
line = line + col
......
......@@ -37,27 +37,28 @@ func LoadRootDef(defaultFile, ymlFile string, fieldsToExport *[]string) model.De
return ymlDef
}
MergerDefine(&defaultDef, &ymlDef)
if len(*fieldsToExport) == 0 {
for _, field := range ymlDef.Fields {
*fieldsToExport = append(*fieldsToExport, field.Field)
}
}
MergerDefine(&defaultDef, &ymlDef)
return defaultDef
}
func MergerDefine(defaultDef, ymlDef *model.DefData) {
defaultFieldMap := map[string]*model.DefField{}
ymlFieldMap := map[string]*model.DefField{}
sortedKeys := make([]string, 0)
for i := range defaultDef.Fields {
CreatePathToFieldMap(&defaultDef.Fields[i], defaultFieldMap)
CreatePathToFieldMap(&defaultDef.Fields[i], defaultFieldMap, nil)
}
for i := range ymlDef.Fields {
CreatePathToFieldMap(&ymlDef.Fields[i], ymlFieldMap)
CreatePathToFieldMap(&ymlDef.Fields[i], ymlFieldMap, &sortedKeys)
}
for path, field := range ymlFieldMap {
......@@ -68,7 +69,8 @@ func MergerDefine(defaultDef, ymlDef *model.DefData) {
}
}
for _, field := range ymlFieldMap {
for _, key := range sortedKeys {
field := ymlFieldMap[key]
if strings.Index(field.Path, "~~") > -1 { continue } // only for top fields
_, exist := defaultFieldMap[field.Path]
......@@ -78,7 +80,7 @@ func MergerDefine(defaultDef, ymlDef *model.DefData) {
}
}
func CreatePathToFieldMap(field *model.DefField, mp map[string]*model.DefField) {
func CreatePathToFieldMap(field *model.DefField, mp map[string]*model.DefField, keys *[]string) {
if field.Path == "" { // root
field.Path = field.Field
}
......@@ -87,12 +89,16 @@ func CreatePathToFieldMap(field *model.DefField, mp map[string]*model.DefField)
for i := range field.Fields {
field.Fields[i].Path = field.Path + "~~" + field.Fields[i].Field
CreatePathToFieldMap(&field.Fields[i], mp)
CreatePathToFieldMap(&field.Fields[i], mp, keys)
}
} else {
path := field.Path
//logUtils.Screen(path + " -> " + field.Field)
mp[path] = field
if keys != nil {
*keys = append(*keys, path)
}
}
}
......
......@@ -23,7 +23,7 @@ func GenerateForDefinition(deflt, yml string, fieldsToExport []string, total int
continue
}
values := GenerateForField(&field, total)
values := GenerateForField(&field, total, true)
constant.Def.Fields[index].Precision = field.Precision
fieldNameToValues[field.Field] = values
......@@ -48,13 +48,13 @@ func GenerateForDefinition(deflt, yml string, fieldsToExport []string, total int
return rows, colTypes
}
func GenerateForField(field *model.DefField, total int) []string {
func GenerateForField(field *model.DefField, total int, withFix bool) []string {
values := make([]string, 0)
if len(field.Fields) > 0 { // sub fields
arr := make([][]string, 0) // 2 dimension arr for child, [ [a,b,c], [1,2,3] ]
for _, child := range field.Fields {
childValues := GenerateForField(&child, total)
childValues := GenerateForField(&child, total, withFix)
arr = append(arr, childValues)
}
......@@ -67,7 +67,7 @@ func GenerateForField(field *model.DefField, total int) []string {
concat = field.Prefix + concat + field.Postfix
values = append(values, concat)
}
values = LoopSubFields(field, values, total)
values = LoopSubFields(field, values, total, withFix)
} else if field.From != "" { // refer to res
groupValues := constant.Res[field.From]
......@@ -82,7 +82,7 @@ func GenerateForField(field *model.DefField, total int) []string {
values = append(values, groupValues[slct]...)
}
values = LoopSubFields(field, values, total)
values = LoopSubFields(field, values, total, true)
} else { // basic field
values = GenerateFieldItemsFromDefinition(field)
......@@ -96,10 +96,6 @@ func GenerateFieldItemsFromDefinition(field *model.DefField) []string {
values := make([]string, 0)
// 整理出值的列表
//datatype := strings.TrimSpace(field.Type)
//if datatype == "" { datatype = "list" }
fieldValue := GenerateList(field)
index := 0
......@@ -169,7 +165,7 @@ func GetFieldValStr(field model.DefField, val interface{}) string {
return str
}
func LoopSubFields(field *model.DefField, oldValues []string, total int) []string {
func LoopSubFields(field *model.DefField, oldValues []string, total int, withFix bool) []string {
if field.Loop == 0 {field.Loop = 1}
values := make([]string, 0)
......@@ -183,7 +179,7 @@ func LoopSubFields(field *model.DefField, oldValues []string, total int) []strin
count := 0
for {
// 处理格式、前后缀、loop等
str := GenerateFieldValWithFix(*field, fieldValue, &index, true)
str := GenerateFieldValWithFix(*field, fieldValue, &index, withFix)
values = append(values, str)
count++
......@@ -195,7 +191,7 @@ func LoopSubFields(field *model.DefField, oldValues []string, total int) []strin
return values
}
func GenerateFieldValWithFix(field model.DefField, fieldValue model.FieldValue, indexOfRow *int, withLoop bool) string {
func GenerateFieldValWithFix(field model.DefField, fieldValue model.FieldValue, indexOfRow *int, withFix bool) string {
prefix := field.Prefix
postfix := field.Postfix
......@@ -211,7 +207,7 @@ func GenerateFieldValWithFix(field model.DefField, fieldValue model.FieldValue,
*indexOfRow++
}
if withLoop {
if withFix {
loopStr = prefix + loopStr + postfix
}
......
......@@ -142,7 +142,7 @@ func getResForRanges(ranges model.ResRanges) map[string][]string {
tempField.Field = ranges.Field
tempField.Range = exp
groupedValue[group] = GenerateForField(&tempField, constant.Total)
groupedValue[group] = GenerateForField(&tempField, constant.Total, false)
}
return groupedValue
......@@ -165,7 +165,7 @@ func getResForInstances(insts model.ResInsts) map[string][]string {
tempField.Fields = append(tempField.Fields, child)
groupedValue[group] = GenerateForField(&tempField, constant.Total)
groupedValue[group] = GenerateForField(&tempField, constant.Total, false)
}
return groupedValue
......
package configUtils
import (
"fmt"
"github.com/easysoft/zendata/src/model"
commonUtils "github.com/easysoft/zendata/src/utils/common"
"github.com/easysoft/zendata/src/utils/const"
"github.com/easysoft/zendata/src/utils/display"
fileUtils "github.com/easysoft/zendata/src/utils/file"
"github.com/easysoft/zendata/src/utils/i118"
logUtils "github.com/easysoft/zendata/src/utils/log"
stdinUtils "github.com/easysoft/zendata/src/utils/stdin"
"github.com/easysoft/zendata/src/utils/vari"
"github.com/fatih/color"
"gopkg.in/ini.v1"
"os"
"reflect"
)
func InitConfig() {
vari.ExeDir = fileUtils.GetExeDir()
vari.WorkDir = fileUtils.GetWorkDir()
CheckConfigPermission()
constant.ConfigFile = vari.WorkDir + constant.ConfigFile
vari.Config = getInst()
InitScreenSize()
i118Utils.InitI118(vari.Config.Language)
......@@ -35,116 +20,4 @@ func InitScreenSize() {
w, h := display.GetScreenSize()
vari.ScreenWidth = w
vari.ScreenHeight = h
}
func SaveConfig(conf model.Config) error {
fileUtils.MkDirIfNeeded(fileUtils.GetExeDir() + "def")
conf.Version = constant.ConfigVer
cfg := ini.Empty()
cfg.ReflectFrom(&conf)
cfg.SaveTo(constant.ConfigFile)
vari.Config = ReadCurrConfig()
return nil
}
func PrintCurrConfig() {
logUtils.PrintToWithColor("\n"+i118Utils.I118Prt.Sprintf("current_config"), color.FgCyan)
val := reflect.ValueOf(vari.Config)
typeOfS := val.Type()
for i := 0; i < reflect.ValueOf(vari.Config).NumField(); i++ {
if !commonUtils.IsWin() && i > 4 {
break
}
val := val.Field(i)
name := typeOfS.Field(i).Name
fmt.Printf(" %s: %v \n", name, val.Interface())
}
}
func ReadCurrConfig() model.Config {
config := model.Config{}
configPath := constant.ConfigFile
if !fileUtils.FileExist(configPath) {
config.Language = "en"
i118Utils.InitI118("en")
return config
}
ini.MapTo(&config, constant.ConfigFile)
return config
}
func getInst() model.Config {
isSetAction := len(os.Args) > 1 && (os.Args[1] == "set" || os.Args[1] == "-set")
if !isSetAction {
CheckConfigReady()
}
ini.MapTo(&vari.Config, constant.ConfigFile)
if vari.Config.Version != constant.ConfigVer { // old config file, re-init
if vari.Config.Language != "en" && vari.Config.Language != "zh" {
vari.Config.Language = "en"
}
SaveConfig(vari.Config)
}
return vari.Config
}
func CheckConfigPermission() {
//err := syscall.Access(vari.WorkDir, syscall.O_RDWR)
err := fileUtils.MkDirIfNeeded(vari.WorkDir + "def")
if err != nil {
logUtils.PrintToWithColor(
fmt.Sprintf("Permission denied to open %s for write. Please change work dir.", vari.WorkDir), color.FgRed)
os.Exit(0)
}
}
func CheckConfigReady() {
if !fileUtils.FileExist(constant.ConfigFile) {
InputForSet()
}
}
func InputForSet() {
conf := ReadCurrConfig()
logUtils.PrintToWithColor(i118Utils.I118Prt.Sprintf("begin_config"), color.FgCyan)
enCheck := ""
var numb string
if conf.Language == "en" {
enCheck = "*"
numb = "1"
}
zhCheck := ""
if conf.Language == "zh" {
zhCheck = "*"
numb = "2"
}
numbSelected := stdinUtils.GetInput("(1|2)", numb, "enter_language", enCheck, zhCheck)
if numbSelected == "1" {
conf.Language = "en"
} else {
conf.Language = "zh"
}
SaveConfig(conf)
PrintCurrConfig()
}
\ No newline at end of file
......@@ -26,7 +26,7 @@ func PrintUsage() {
exeFile += ".exe"
}
usage = fmt.Sprintf(usage, exeFile)
fmt.Printf(" %s\n", usage)
fmt.Printf("%s\n", usage)
PrintToWithColor("\n" + i118Utils.I118Prt.Sprintf("example"), color.FgCyan)
sample := fileUtils.ReadResData(sampleFile)
......@@ -43,7 +43,7 @@ func PrintUsage() {
regx, _ = regexp.Compile(`\.bat\s{4}`)
sample = regx.ReplaceAllString(sample, ".shell")
}
fmt.Printf(" %s\n", sample)
fmt.Printf("%s\n", sample)
}
func PrintTo(str string) {
......
......@@ -6,7 +6,7 @@ import (
)
var (
Config = model.Config{}
Config = model.Config{Version: 1, Language: "en"}
RunMode constant.RunMode
......
......@@ -76,8 +76,6 @@ func main() {
}
switch os.Args[1] {
case "-s", "-set":
set()
case "-h", "-help":
usage()
default:
......@@ -91,10 +89,6 @@ func main() {
}
}
func set() {
action.Set()
}
func gen(args []string) {
flagSet.SetOutput(ioutil.Discard)
if err := flagSet.Parse(args[2:]); err == nil {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册