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

close task #7496

上级 52a434f8
......@@ -14,10 +14,6 @@ require (
github.com/mattn/go-colorable v0.1.6 // indirect
github.com/mattn/go-runewidth v0.0.9
github.com/mattn/go-sqlite3 v2.0.3+incompatible
github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5
github.com/satori/go.uuid v1.2.0
github.com/sirupsen/logrus v1.6.0
github.com/stretchr/objx v0.1.1 // indirect
github.com/stretchr/testify v1.6.0 // indirect
golang.org/x/net v0.0.0-20200602114024-627f9648deb9 // indirect
golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980 // indirect
......
......@@ -10,10 +10,17 @@ import (
i118Utils "github.com/easysoft/zendata/src/utils/i118"
logUtils "github.com/easysoft/zendata/src/utils/log"
"github.com/easysoft/zendata/src/utils/vari"
"net/http"
"os"
"strings"
"time"
)
var (
FileWriter *os.File
HttpWriter http.ResponseWriter
)
func Generate(defaultFile string, configFile string, total int, fieldsToExportStr string, out string, format string, table string) {
startTime := time.Now().Unix()
......@@ -30,12 +37,7 @@ func Generate(defaultFile string, configFile string, total int, fieldsToExportSt
constant.Total = total
rows, colTypes := gen.GenerateForDefinition(defaultFile, configFile, &fieldsToExport, total)
var content string
content, vari.JsonResp = Print(rows, format, table, colTypes, fieldsToExport)
if out != "" {
WriteToFile(out, content)
}
Print(rows, format, out, table, colTypes, fieldsToExport)
entTime := time.Now().Unix()
if vari.RunMode == constant.RunModeServerRequest {
......@@ -43,97 +45,144 @@ func Generate(defaultFile string, configFile string, total int, fieldsToExportSt
}
}
func Print(rows [][]string, format string, table string, colTypes []bool, fields []string) (string, string) {
content := ""
sql := ""
if vari.WithHead {
line := ""
for idx, field := range fields {
line += field
if idx < len(fields) - 1 {
line += vari.HeadSep
}
}
if vari.RunMode != constant.RunModeServerRequest {
logUtils.Screen(fmt.Sprintf("%s", line))
}
content += line + "\n"
func Print(rows [][]string, format string, out string, table string, colTypes []bool, fields []string) {
if format == constant.FormatText {
printTextHeader(fields)
} else if format == constant.FormatSql {
printSqlHeader(fields, table)
} else if format == constant.FormatJson {
printJsonHeader()
} else if format == constant.FormatXml {
printXmlHeader(fields, table)
}
testData := model.TestData{}
testData.Title = "Test Data"
for i, cols := range rows {
line := ""
row := model.Row{}
valueList := ""
row := make([]string, 0)
rowXml := model.XmlRow{}
lineForText := ""
valuesForSql := ""
for j, col := range cols {
if j >0 && format == constant.FormatSql {
line = line + ","
valueList = valueList + ","
if j > 0 && format == constant.FormatSql {
valuesForSql = valuesForSql + ", "
}
line = line + col
lineForText = lineForText + col
row.Cols = append(row.Cols, col)
row = append(row, col)
rowXml.Cols = append(rowXml.Cols, col)
colVal := col
//colVal = stringUtils.AddPad(colVal, vari.Def.Fields[j])
if !colTypes[j] { colVal = "'" + colVal + "'" }
valueList = valueList + colVal
valuesForSql = valuesForSql + colVal
}
if format == constant.FormatText && i < len(rows) {
content = content + line + "\n"
if format == constant.FormatText {
printLine(lineForText)
} else if format == constant.FormatSql {
printLine(genSqlLine(valuesForSql, i, len(rows)))
} else if format == constant.FormatJson {
printLine(genJsonLine(i, row, len(rows), fields))
} else if format == constant.FormatXml {
printLine(getXmlLine(i, rowXml, len(rows)))
}
}
}
if vari.RunMode != constant.RunModeServerRequest {
logUtils.Screen(fmt.Sprintf("%s", line))
func printTextHeader(fields []string) {
if !vari.WithHead {
return
}
headerLine := ""
for idx, field := range fields {
headerLine += field
if idx < len(fields)-1 {
headerLine += vari.HeadSep
}
}
testData.Table.Rows = append(testData.Table.Rows, row)
printLine(headerLine)
}
if format == constant.FormatSql {
fieldNames := make([]string, 0)
func printSqlHeader(fields []string, table string) {
fieldNames := make([]string, 0)
for _, f := range fields { fieldNames = append(fieldNames, "`" + f + "`") }
printLine(fmt.Sprintf("INSERT INTO %s(%s)", table, strings.Join(fieldNames, ", ")))
}
for _, f := range fields {
fieldNames = append(fieldNames, "`" + f + "`")
}
sent := fmt.Sprintf("INSERT INTO %s(%s) VALUES(%s)", table, strings.Join(fieldNames, ", "), valueList)
sql = sql + sent + ";\n"
}
func printJsonHeader() {
printLine("[")
}
func printXmlHeader(fields []string, table string) {
printLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<testdata>\n <title>Test Data</title>")
}
func RowToJson(cols []string, fieldsToExport []string) string {
rowMap := map[string]string{}
for j, col := range cols {
rowMap[fieldsToExport[j]] = col
}
respJson := "{}"
if format == constant.FormatJson || vari.RunMode == constant.RunModeServer {
mapArr := RowsToMap(rows, fields)
jsonObj, _ := json.Marshal(mapArr)
respJson = string(jsonObj)
jsonObj, _ := json.Marshal(rowMap)
respJson := string(jsonObj)
return respJson
}
func genSqlLine(valuesForSql string, i int, length int) string {
temp := ""
if i == 0 {
temp = fmt.Sprintf(" VALUES (%s)", valuesForSql)
} else {
temp = fmt.Sprintf(" (%s)", valuesForSql)
}
if format == constant.FormatJson {
content = respJson
} else if format == constant.FormatJson {
xml, _ := xml.Marshal(testData)
content = string(xml)
} else if format == constant.FormatSql {
content = sql
if i < length - 1 {
temp = temp + ", "
} else {
temp = temp + "; "
}
return content, respJson
return temp
}
func RowsToMap(rows [][]string, fieldsToExport []string) (ret []map[string]string) {
ret = []map[string]string{}
func genJsonLine(i int, row []string, length int, fields []string) string {
temp := " " + RowToJson(row, fields)
if i < length - 1 {
temp = temp + ", "
} else {
temp = temp + "\n]"
}
for _, cols := range rows {
rowMap := map[string]string{}
for j, col := range cols {
rowMap[fieldsToExport[j]] = col
}
return temp
}
func getXmlLine(i int, rowXml model.XmlRow, length int) string {
rowXmlStr, _ := xml.Marshal(rowXml)
text := " " + string(rowXmlStr)
if i == length - 1 {
text = text + "\n</testdata>"
}
return text
}
ret = append(ret, rowMap)
func printLine(line string) {
if FileWriter != nil {
PrintToFile(line)
} else if vari.RunMode == constant.RunModeServerRequest {
PrintToHttp(line)
} else {
PrintToScreen(line)
}
return
}
func PrintToFile(line string) {
fmt.Fprintln(FileWriter, line)
}
func PrintToHttp(line string) {
fmt.Fprintln(HttpWriter, line)
}
func PrintToScreen(line string) {
fmt.Println(line)
}
\ No newline at end of file
......@@ -36,12 +36,12 @@ func ParseSql(file string, out string) {
outFile := out + tableName + ".yaml"
WriteToFile(outFile, content)
} else {
logUtils.Screen(content)
logUtils.PrintTo(content)
}
}
entTime := time.Now().Unix()
logUtils.Screen(i118Utils.I118Prt.Sprintf("generate_yaml", len(statements), out, entTime - startTime ))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("generate_yaml", len(statements), out, entTime - startTime ))
}
func getCreateStatement(file string) map[string]string {
......@@ -49,7 +49,7 @@ func getCreateStatement(file string) map[string]string {
content, err := ioutil.ReadFile(file)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_read_file", file))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_read_file", file))
return statements
}
......
......@@ -20,14 +20,14 @@ func Upgrade() {
db, err := sql.Open(constant.SqliteDriver, constant.SqliteSource)
defer db.Close()
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_connect_sqlite", constant.SqliteSource, err.Error()))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_connect_sqlite", constant.SqliteSource, err.Error()))
return
}
sql := "SELECT id, name, state, zipCode, cityCode FROM city"
rows, err := db.Query(sql)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_exec_query", sql, err.Error()))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_exec_query", sql, err.Error()))
return
}
......@@ -50,7 +50,7 @@ func Upgrade() {
err = rows.Scan(&id, &name, &state, &zipCode, &cityCode)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_parse_row", err.Error()))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_parse_row", err.Error()))
return
}
......@@ -77,13 +77,13 @@ func Upgrade() {
for _, sql := range sqls {
_, err := db.Exec(sql)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_exec_query", sql, err.Error()))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_exec_query", sql, err.Error()))
}
}
err = excel.SaveAs("export.excel")
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_save_excel", err.Error()))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_save_excel", err.Error()))
}
}
......
......@@ -32,7 +32,7 @@ func Decode(defaultFile, configFile, fieldsToExportStr, input, output string) {
jsonObj, _ := json.Marshal(ret)
vari.JsonResp = string(jsonObj)
logUtils.Screen(i118Utils.I118Prt.Sprintf("analyse_success", output ))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("analyse_success", output ))
if vari.RunMode != constant.RunModeServerRequest {
fileUtils.WriteFile(output, vari.JsonResp)
}
......
......@@ -20,12 +20,12 @@ func LoadConfigDef(defaultFile, configFile string, fieldsToExport *[]string) mod
defaultContent, err := ioutil.ReadFile(defaultFile)
defaultContent = ReplaceSpecialChars(defaultContent)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_read_file", defaultFile))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_read_file", defaultFile))
return defaultDef
}
err = yaml.Unmarshal(defaultContent, &defaultDef)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_read_file", defaultFile))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_read_file", defaultFile))
return defaultDef
}
}
......@@ -34,12 +34,12 @@ func LoadConfigDef(defaultFile, configFile string, fieldsToExport *[]string) mod
yamlContent, err := ioutil.ReadFile(configFile)
yamlContent = ReplaceSpecialChars(yamlContent)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_read_file", configFile))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_read_file", configFile))
return configDef
}
err = yaml.Unmarshal(yamlContent, &configDef)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_parse_file", configFile))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_parse_file", configFile))
return configDef
}
......
......@@ -57,7 +57,7 @@ func GenerateFieldValuesFromExcel(path string, field *model.DefField) (map[strin
func ConvertExcelToSQLiteIfNeeded(dbName string, path string) {
excel, err := excelize.OpenFile(path)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_read_file", path))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_read_file", path))
return
}
......@@ -132,19 +132,19 @@ func ConvertExcelToSQLiteIfNeeded(dbName string, path string) {
defer db.Close()
_, err = db.Exec(dropSql)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_drop_table", tableName, err.Error()))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_drop_table", tableName, err.Error()))
return
}
_, err = db.Exec(ddl)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_create_table", tableName, err.Error()))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_create_table", tableName, err.Error()))
return
}
_, err = db.Exec(insertSql)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_exec_query", insertSql, err.Error()))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_exec_query", insertSql, err.Error()))
return
}
}
......@@ -156,7 +156,7 @@ func ReadDataFromSQLite(field model.DefField, dbName string, tableName string) (
db, err := sql.Open(constant.SqliteDriver, constant.SqliteSource)
defer db.Close()
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_connect_sqlite", constant.SqliteSource, err.Error()))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_connect_sqlite", constant.SqliteSource, err.Error()))
return list, ""
}
......@@ -170,7 +170,7 @@ func ReadDataFromSQLite(field model.DefField, dbName string, tableName string) (
sqlStr := fmt.Sprintf("SELECT %s FROM %s WHERE %s", selectCol, from, where)
rows, err := db.Query(sqlStr)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_exec_query", sqlStr, err.Error()))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_exec_query", sqlStr, err.Error()))
return list, ""
}
......@@ -192,7 +192,7 @@ func ReadDataFromSQLite(field model.DefField, dbName string, tableName string) (
for rows.Next() {
err = rows.Scan(values...)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_parse_row", err.Error()))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_parse_row", err.Error()))
return list, ""
}
......@@ -222,7 +222,7 @@ func isExcelChanged(path string) bool {
db, err := sql.Open(constant.SqliteDriver, constant.SqliteSource)
defer db.Close()
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_connect_sqlite", constant.SqliteSource, err.Error()))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_connect_sqlite", constant.SqliteSource, err.Error()))
return true
}
......@@ -230,7 +230,7 @@ func isExcelChanged(path string) bool {
constant.SqliteTrackTable, path)
rows, err := db.Query(sqlStr)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_exec_query", sqlStr, err.Error()))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_exec_query", sqlStr, err.Error()))
return true
}
......@@ -246,7 +246,7 @@ func isExcelChanged(path string) bool {
err = rows.Scan(&id, &name, &changeTime)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_parse_row", err.Error()))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_parse_row", err.Error()))
changed = true
break
}
......@@ -271,7 +271,7 @@ func isExcelChanged(path string) bool {
_, err = db.Exec(sqlStr)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_exec_query", sqlStr, err.Error()))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_exec_query", sqlStr, err.Error()))
}
}
......
......@@ -116,7 +116,7 @@ func getResForYaml(resFile string) (map[string][]string, string) {
yamlContent, err := ioutil.ReadFile(resFile)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_read_file", resFile))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_read_file", resFile))
return valueMap, ""
}
......@@ -184,7 +184,7 @@ func getRootRangeOrInstant(inst model.DefField) (parentRanges model.ResRanges, p
yamlContent, err := ioutil.ReadFile(resFile)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_read_file", resFile))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_read_file", resFile))
return
}
......@@ -193,7 +193,7 @@ func getRootRangeOrInstant(inst model.DefField) (parentRanges model.ResRanges, p
err2 := yaml.Unmarshal(yamlContent, &parentInsts)
if err2 != nil || parentInsts.Instances == nil || len(parentInsts.Instances) == 0 { // ranges
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_parse_file", resFile))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_parse_file", resFile))
return
}
}
......
......@@ -28,7 +28,7 @@ func GenerateFieldValuesFromText(field *model.DefField, fieldValue *model.FieldV
realPath := findFilePath(file)
content, err := ioutil.ReadFile(realPath)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_read_file", realPath))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_read_file", realPath))
fieldValue.Values = append(fieldValue.Values, fmt.Sprintf("FILE_NOT_FOUND: %s", realPath))
return
}
......
......@@ -2,16 +2,17 @@ package model
import "encoding/xml"
type TestData struct {
XMLName xml.Name `xml:"testdata"`
Title string `json:"title" xml:"title"`
Table Table `json:"table" xml:"table"`
type XmlData struct {
XMLName xml.Name `xml:"testdata"`
Title string `xml:"title"`
Table XmlTable `xml:"table"`
}
type Table struct {
Rows []Row `json:"row" xml:"row"`
type XmlTable struct {
Rows []XmlRow `xml:"row"`
}
type Row struct {
Cols []string `json:"col" xml:"col"`
type XmlRow struct {
XMLName xml.Name `xml:"row"`
Cols []string `xml:"col"`
}
\ No newline at end of file
......@@ -84,7 +84,7 @@ func ListRes() {
idx++
}
logUtils.Screen(msg)
logUtils.PrintTo(msg)
}
func GetFilesAndDirs(path string, res *map[string][size]string) {
......@@ -117,12 +117,12 @@ func readYamlInfo(path string) (title string, desc string) {
yamlContent, err := ioutil.ReadFile(path)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_read_file", path))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_read_file", path))
return
}
err = yaml.Unmarshal(yamlContent, &configDef)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_parse_file", path))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_parse_file", path))
return
}
......@@ -134,7 +134,7 @@ func readYamlInfo(path string) (title string, desc string) {
func readExcelInfo(path string) (title string, desc string) {
excel, err := excelize.OpenFile(path)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_read_file", path))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_read_file", path))
return
}
......
......@@ -17,7 +17,7 @@ const (
func AddMd5(path string) {
excel, err := excelize.OpenFile(path)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_read_file", path))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_read_file", path))
return
}
......@@ -52,7 +52,7 @@ func AddMd5(path string) {
}
if err := excel.SaveAs(path); err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_write_file", path))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_write_file", path))
}
}
......
......@@ -31,7 +31,7 @@ func ViewRes(res string) {
func readYamlData(path string) (typ string, insts model.ResInsts, ranges model.ResRanges) {
yamlContent, err := ioutil.ReadFile(path)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_read_file", path))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_read_file", path))
return
}
......@@ -64,7 +64,7 @@ func printInst(inst model.ResInsts) {
idx+1, item.Instance + strings.Repeat(" ", width - runewidth.StringWidth(item.Instance)), item.Note)
}
logUtils.Screen(msg)
logUtils.PrintTo(msg)
}
func printRanges(ranges model.ResRanges) {
......@@ -87,14 +87,14 @@ func printRanges(ranges model.ResRanges) {
i++
}
logUtils.Screen(msg)
logUtils.PrintTo(msg)
}
func printExcelSheet(path, sheetName string) {
excel, err := excelize.OpenFile(path)
if err != nil {
logUtils.Screen(i118Utils.I118Prt.Sprintf("fail_to_read_file", path))
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("fail_to_read_file", path))
return
}
......@@ -106,7 +106,7 @@ func printExcelSheet(path, sheetName string) {
}
}
logUtils.Screen(msg)
logUtils.PrintTo(msg)
if sheetName != "" {
for _, sheet := range excel.GetSheetList() {
......@@ -160,7 +160,7 @@ func printExcelSheet(path, sheetName string) {
line = line + col + strings.Repeat(" ", space) + " "
}
logUtils.Screen(line)
logUtils.PrintTo(line)
}
}
}
......
......@@ -12,7 +12,6 @@ import (
"os/exec"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
)
......@@ -42,6 +41,10 @@ func WriteFile(filePath string, content string) {
check(err2)
}
func RemoveExist(path string) {
os.Remove(path)
}
func check(e error) {
if e != nil {
panic(e)
......@@ -162,50 +165,6 @@ func GetWorkDir() string { // where run command in
return dir
}
func GetLogDir() string {
path := vari.ExeDir + constant.LogDir
dir, _ := ioutil.ReadDir(path)
regx := `^\d\d\d$`
numb := 0
for _, fi := range dir {
if fi.IsDir() {
name := fi.Name()
pass, _ := regexp.MatchString(regx, name)
if pass { // 999
name = strings.TrimLeft(name, "0")
nm, _ := strconv.Atoi(name)
if nm >= numb {
numb = nm
}
}
}
}
if numb >= 9 {
numb = 0
tempDir := path[:len(path)-1] + "-bak" + string(os.PathSeparator) + path[len(path):]
childDir := path + "bak" + string(os.PathSeparator) + path[len(path):]
os.RemoveAll(childDir)
os.Rename(path, tempDir)
MkDirIfNeeded(path)
err := os.Rename(tempDir, childDir)
_ = err
}
ret := getLogNumb(numb + 1)
return UpdateDir(path + ret)
}
func getLogNumb(numb int) string {
return fmt.Sprintf("%03s", strconv.Itoa(numb))
}
......
package logUtils
import (
"fmt"
fileUtils "github.com/easysoft/zendata/src/utils/file"
i118Utils "github.com/easysoft/zendata/src/utils/i118"
"github.com/easysoft/zendata/src/utils/vari"
"github.com/fatih/color"
"github.com/rifflock/lfshook"
"github.com/sirupsen/logrus"
"io/ioutil"
"strings"
"unicode/utf8"
)
var Logger *logrus.Logger
func GetWholeLine(msg string, char string) string {
prefixLen := (vari.ScreenWidth - utf8.RuneCountInString(msg) - 2) / 2
if prefixLen <= 0 { // no width in debug mode
prefixLen = 6
}
postfixLen := vari.ScreenWidth - utf8.RuneCountInString(msg) - 2 - prefixLen - 1
if postfixLen <= 0 { // no width in debug mode
postfixLen = 6
}
preFixStr := strings.Repeat(char, prefixLen)
postFixStr := strings.Repeat(char, postfixLen)
return fmt.Sprintf("%s %s %s", preFixStr, msg, postFixStr)
}
func ColoredStatus(status string) string {
temp := strings.ToLower(status)
switch temp {
case "pass":
return color.GreenString(i118Utils.I118Prt.Sprintf(temp))
case "fail":
return color.RedString(i118Utils.I118Prt.Sprintf(temp))
case "skip":
return color.YellowString(i118Utils.I118Prt.Sprintf(temp))
}
return status
}
func InitLogger() *logrus.Logger {
vari.LogDir = fileUtils.GetLogDir()
if Logger != nil {
return Logger
}
Logger = logrus.New()
Logger.Out = ioutil.Discard
pathMap := lfshook.PathMap{
logrus.WarnLevel: vari.LogDir + "log.txt",
logrus.ErrorLevel: vari.LogDir + "result.txt",
}
Logger.Hooks.Add(lfshook.NewHook(
pathMap,
&MyFormatter{},
))
Logger.SetFormatter(&MyFormatter{})
return Logger
}
func Screen(msg string) {
PrintTo(msg)
}
func Log(msg string) {
Logger.Warnln(msg)
}
func Result(msg string) {
Logger.Errorln(msg)
}
func ScreenAndResult(msg string) {
Screen(msg)
Result(msg)
}
type MyFormatter struct {
logrus.TextFormatter
}
func (f *MyFormatter) Format(entry *logrus.Entry) ([]byte, error) {
return []byte(entry.Message + "\n"), nil
}
package logUtils
import (
"encoding/json"
"fmt"
commonUtils "github.com/easysoft/zendata/src/utils/common"
fileUtils "github.com/easysoft/zendata/src/utils/file"
......@@ -66,31 +65,3 @@ func PrintToWithColor(msg string, attr color.Attribute) {
color.New(attr).Fprintf(output, msg+"\n")
}
}
func PrintToCmd(msg string, attr color.Attribute) {
output := color.Output
if attr == -1 {
fmt.Fprint(output, msg+"\n")
} else {
clr := color.New(attr)
clr.Fprint(output, msg+"\n")
}
}
func PrintUnicode(str []byte) {
var a interface{}
temp := strings.Replace(string(str), "\\\\", "\\", -1)
err := json.Unmarshal([]byte(temp), &a)
var msg string
if err == nil {
msg = fmt.Sprint(a)
} else {
msg = temp
}
PrintToCmd(msg, -1)
}
......@@ -57,7 +57,7 @@ func ExeShellWithOutput(cmdStr string) []string {
if err2 != nil || io.EOF == err2 {
break
}
logUtils.Screen(strings.TrimRight(line, "\n"))
logUtils.PrintTo(strings.TrimRight(line, "\n"))
output = append(output, line)
}
......
......@@ -9,6 +9,7 @@ import (
commonUtils "github.com/easysoft/zendata/src/utils/common"
configUtils "github.com/easysoft/zendata/src/utils/config"
constant "github.com/easysoft/zendata/src/utils/const"
fileUtils "github.com/easysoft/zendata/src/utils/file"
i118Utils "github.com/easysoft/zendata/src/utils/i118"
logUtils "github.com/easysoft/zendata/src/utils/log"
stringUtils "github.com/easysoft/zendata/src/utils/string"
......@@ -154,6 +155,9 @@ func main() {
func toGen() {
if vari.RunMode == constant.RunModeServer {
StartServer()
} else if vari.RunMode == constant.RunModeServerRequest {
format = constant.FormatJson
action.Generate(defaultFile, configFile, count, fields, output, format, table)
} else if vari.RunMode == constant.RunModeParse {
action.ParseSql(input, output)
} else if vari.RunMode == constant.RunModeGen {
......@@ -165,6 +169,10 @@ func toGen() {
}
if output != "" {
fileUtils.RemoveExist(output)
action.FileWriter, _ = os.OpenFile(output, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
defer action.FileWriter.Close()
ext := strings.ToLower(path.Ext(output))
if len(ext) > 1 {
ext = strings.TrimLeft(ext,".")
......@@ -174,8 +182,6 @@ func toGen() {
}
}
action.Generate(defaultFile, configFile, count, fields, output, format, table)
} else if vari.RunMode == constant.RunModeServerRequest {
action.Generate(defaultFile, configFile, count, fields, output, format, table)
}
}
......@@ -196,27 +202,25 @@ func StartServer() {
http.ListenAndServe(fmt.Sprintf(":%d", vari.Port), nil)
}
func DataHandler(w http.ResponseWriter, req *http.Request) {
func DataHandler(writer http.ResponseWriter, req *http.Request) {
action.HttpWriter = writer
root, defaultFile, configFile, fields, count, vari.HeadSep,
format, table, decode, input, output = service.ParseRequestParams(req)
if decode {
gen.Decode(defaultFile, configFile, fields, input, output)
fmt.Fprintln(w, vari.JsonResp)
fmt.Fprintln(writer, vari.JsonResp)
} else if defaultFile != "" || configFile != "" {
vari.RunMode = constant.RunModeServerRequest
logUtils.PrintTo(i118Utils.I118Prt.Sprintf("server_request", req.Method, req.URL))
toGen()
fmt.Fprintln(w, vari.JsonResp)
}
}
func init() {
cleanup()
logUtils.InitLogger()
configUtils.InitConfig()
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册