package generator import ( "bufio" "fmt" "io" "os" "service/bizcommon/util" "service/codecreate/consts" "strings" "github.com/xuri/excelize/v2" ) func CreateFileDirectory(genSource *GenSource) { //在/service/api/proto下准备保存proto的文件夹 //判断是否存在,不存在就创建 path := fmt.Sprintf("%v%v%v/proto", consts.RootPath, consts.ProtoOutPath, genSource.ModuleName) _, err := os.Stat(path) if os.IsNotExist(err) { // mkdir 创建目录,mkdirAll 可创建多层级目录 err = os.MkdirAll(path, os.ModePerm) if err != nil { fmt.Printf("Create directory fail : %v", err) } } else if err != nil { fmt.Printf("Stat fail :%v", err) } } func GenerateEntity(genSource *GenSource) { infile, err := os.Open(genSource.InPath) if err != nil { fmt.Printf("Open File Err : %v", err) } outfile, err := os.OpenFile(genSource.OutPath, os.O_WRONLY|os.O_CREATE, 0666) if err != nil { fmt.Printf("Open File Err : %v", err) } entityDefineFile, err := excelize.OpenFile(consts.RootPath + consts.ExcelPath) if err != nil { fmt.Printf("Open File Err : %v", err) } rows, err := entityDefineFile.GetRows(genSource.EntityName) if err != nil { fmt.Printf("Get rows Err : %v", err) } defer infile.Close() defer outfile.Close() defer entityDefineFile.Close() reader := bufio.NewReader(infile) writer := bufio.NewWriter(outfile) entityDef := CreateEntityDefination(rows) for { str, err := reader.ReadString('\n') str = strings.ReplaceAll(str, consts.EntityNamePlaceHolder, genSource.EntityName) str = strings.ReplaceAll(str, consts.EntityCNNamePlaceHolder, genSource.EntityCNName) str = strings.ReplaceAll(str, consts.EntityDefinationPlaceHolder, entityDef) writer.WriteString(str) if err == io.EOF { break } } writer.Flush() } func GenerateModule(genSource *GenSource) { infile, err := os.Open(genSource.InPath) if err != nil { fmt.Printf("Open File Err : %v", err) } outfile, err := os.OpenFile(genSource.OutPath, os.O_WRONLY|os.O_CREATE, 0666) if err != nil { fmt.Printf("Open File Err : %v", err) } defer infile.Close() defer outfile.Close() reader := bufio.NewReader(infile) writer := bufio.NewWriter(outfile) for { str, err := reader.ReadString('\n') str = strings.ReplaceAll(str, consts.EntityNamePlaceHolder, genSource.EntityName) str = strings.ReplaceAll(str, consts.ModuleNamePlaceHolder, genSource.ModuleName) str = strings.ReplaceAll(str, consts.EntityCNNamePlaceHolder, genSource.EntityCNName) str = strings.ReplaceAll(str, consts.ErrCodeSeqPlaceHolder, genSource.ErrCodeSeq) writer.WriteString(str) if err == io.EOF { break } } writer.Flush() } func CreateEntityDefination(rows [][]string) string { var sb strings.Builder //第四列为ID row := rows[3] sb.WriteString(fmt.Sprintf(" Id *%v `json:\"id\" bson:\"_id\"` // %v\n", row[2], row[1])) //第五列开始为表其他字段 for i := 4; i < len(rows); i++ { row = rows[i] sb.WriteString(fmt.Sprintf(" %v *%v `json:\"%v\" bson:\"%v\"` // %v\n", util.UderscoreToUpperCamelCase(row[0]), row[2], row[0], row[0], row[1])) } return sb.String() }